hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
489feab8fc2b45c5c00da203e917f42ee0b19882
65,386
cpp
C++
src/engine/shader/shader.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
2
2019-06-22T23:29:44.000Z
2019-07-07T18:34:04.000Z
src/engine/shader/shader.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
src/engine/shader/shader.cpp
dream-overflow/o3d
087ab870cc0fd9091974bb826e25c23903a1dde0
[ "FSFAP" ]
null
null
null
/** * @file shader.cpp * @brief Implementation of Shader.h * @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org) * @author Emmanuel RUFFIO (emmanuel.ruffio@gmail.com) * @date 2005-10-19 * @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved. * @details */ #include "o3d/engine/precompiled.h" #include "o3d/engine/glextdefines.h" #include "o3d/engine/shader/shader.h" #include "o3d/engine/shader/shadermanager.h" #include "o3d/core/filemanager.h" #include "o3d/core/stringtokenizer.h" #include "o3d/engine/texture/texture.h" #include "o3d/engine/context.h" #include "o3d/engine/renderer.h" #include "o3d/engine/scene/scene.h" using namespace o3d; O3D_IMPLEMENT_DYNAMIC_CLASS1(Shader, ENGINE_SHADER, SceneEntity) Shader::T_ProgramInfo::T_ProgramInfo() : programName(), programType(TYPE_UNDEFINED), programSource() { } /* Bool hader::T_ProgramInfo::isNull() { return (programName.isNull() && (programType == TYPE_UNDEFINED)); } void Shader::T_ProgramInfo::reset() { programName.destroy(); programType = TYPE_UNDEFINED; programSource.destroy(); programs.clear(); } */ Shader::T_ProgramInfo::T_Program::T_Program() : programId(0), programState(PROGRAM_UNDEFINED) { } Shader::Shader(BaseObject *parent) : SceneEntity(parent), m_vertexProgramArray(), m_fragmentProgramArray(), m_geometryProgramArray(), m_tessControlProgramArray(), m_tessEvaluationProgramArray(), m_programName(), m_instances() { } Shader::~Shader() { destroy(); } void Shader::compileInstance(T_InstanceInfo & _instance) { O3D_ASSERT((_instance.shaderState & SHADER_COMPILED) != SHADER_COMPILED); const Int32 & lVertexId = _instance.vertexProgramId; const Int32 & lFragmentId = _instance.fragmentProgramId; const Int32 & lGeometryId = _instance.geometryProgramId; const Int32 & lTessControlId = _instance.tessControlProgramId; const Int32 & lTessEvaluationId = _instance.tessEvaluationProgramId; const String & lOptions = _instance.options; if ((lVertexId != -1) && (m_vertexProgramArray[lVertexId].programs[lOptions].programState == PROGRAM_UNDEFINED)) { compileProgram(TYPE_VERTEX_PROGRAM, lVertexId, lOptions); } if ((lFragmentId != -1) && (m_fragmentProgramArray[lFragmentId].programs[lOptions].programState == PROGRAM_UNDEFINED)) { compileProgram(TYPE_FRAGMENT_PROGRAM, lFragmentId, lOptions); } if ((lGeometryId != -1) && (m_geometryProgramArray[lGeometryId].programs[lOptions].programState == PROGRAM_UNDEFINED)) { compileProgram(TYPE_GEOMETRY_PROGRAM, lGeometryId, lOptions); } if ((lTessControlId != -1) && (m_tessControlProgramArray[lTessControlId].programs[lOptions].programState == PROGRAM_UNDEFINED)) { compileProgram(TYPE_TESS_CONTROL_PROGRAM, lTessControlId, lOptions); } if ((lTessEvaluationId != -1) && (m_tessEvaluationProgramArray[lTessEvaluationId].programs[lOptions].programState == PROGRAM_UNDEFINED)) { compileProgram(TYPE_TESS_EVALUATION_PROGRAM, lTessEvaluationId, lOptions); } if ((lVertexId != -1) && (m_vertexProgramArray[lVertexId].programs[lOptions].programState != PROGRAM_COMPILED)) { return; } if ((lFragmentId != -1) && (m_fragmentProgramArray[lFragmentId].programs[lOptions].programState != PROGRAM_COMPILED)) { return; } if ((lGeometryId != -1) && (m_geometryProgramArray[lGeometryId].programs[lOptions].programState != PROGRAM_COMPILED)) { return; } if ((lTessControlId != -1) && (m_tessControlProgramArray[lTessControlId].programs[lOptions].programState != PROGRAM_COMPILED)) { return; } if ((lTessEvaluationId != -1) && (m_tessEvaluationProgramArray[lTessEvaluationId].programs[lOptions].programState != PROGRAM_COMPILED)) { return; } _instance.shaderState |= SHADER_COMPILED; } void Shader::linkInstance(T_InstanceInfo & _instance) { O3D_ASSERT((_instance.shaderState & SHADER_COMPILED) == SHADER_COMPILED); O3D_ASSERT((_instance.shaderState & SHADER_LINKED) != SHADER_LINKED); const Int32 & lVertexId = _instance.vertexProgramId; const Int32 & lFragmentId = _instance.fragmentProgramId; const Int32 & lGeometryId = _instance.geometryProgramId; const Int32 & lTessControlId = _instance.tessControlProgramId; const Int32 & lTessEvaluationId = _instance.tessEvaluationProgramId; const String & lOptions = _instance.options; const T_ProgramInfo & lVertexProgram = m_vertexProgramArray[lVertexId]; const T_ProgramInfo & lFragmentProgram = m_fragmentProgramArray[lFragmentId]; if (_instance.shaderId == 0) { _instance.shaderId = glCreateProgram(); } // Bind the attribute's slots @todo layout everywhere and remove that // glBindAttribLocation(_instance.shaderId, V_VERTICES_ARRAY, "a_vertex"); // glBindAttribLocation(_instance.shaderId, V_NORMALS_ARRAY, "a_normal"); // glBindAttribLocation(_instance.shaderId, V_TANGENT_ARRAY, "a_tangent"); // glBindAttribLocation(_instance.shaderId, V_BITANGENT_ARRAY, "a_bitangent"); // glBindAttribLocation(_instance.shaderId, V_COLOR_ARRAY, "a_color"); // glBindAttribLocation(_instance.shaderId, V_RIGGING_ARRAY, "a_rigging"); // glBindAttribLocation(_instance.shaderId, V_SKINNING_ARRAY, "a_skinning"); // glBindAttribLocation(_instance.shaderId, V_WEIGHTING_ARRAY, "a_weighting"); // glBindAttribLocation(_instance.shaderId, V_UV_MAP_ARRAY, "a_texCoords1"); // glBindAttribLocation(_instance.shaderId, V_UVW_ARRAY, "a_tex3D_1"); // glBindAttribLocation(_instance.shaderId, V_UV_MAP2_ARRAY, "a_tex2D_2"); // glBindAttribLocation(_instance.shaderId, V_UVW_2_ARRAY, "a_tex3D_2"); // glBindAttribLocation(_instance.shaderId, V_UV_MAP3_ARRAY, "a_tex2D_3"); // glBindAttribLocation(_instance.shaderId, V_UVW_3_ARRAY, "a_tex3D_3"); // Since OpenGL 3.3 bind out fragments, but not for GLES // @todo Uses layouts everywhere and remove that // if (glBindFragDataLocation) { // glBindFragDataLocation(_instance.shaderId, 0, "o_finalColor"); // glBindFragDataLocation(_instance.shaderId, 0, "o_fragData"); // glBindFragDataLocation(_instance.shaderId, 0, "o_ambient"); // glBindFragDataLocation(_instance.shaderId, 1, "o_normal"); // glBindFragDataLocation(_instance.shaderId, 2, "o_position"); // glBindFragDataLocation(_instance.shaderId, 3, "o_diffuse"); // glBindFragDataLocation(_instance.shaderId, 4, "o_specular"); // } T_ProgramInfo::CIT_ProgramMap lVpCit = lVertexProgram.programs.find(lOptions); T_ProgramInfo::CIT_ProgramMap lFpCit = lFragmentProgram.programs.find(lOptions); T_ProgramInfo::CIT_ProgramMap lGpCit; T_ProgramInfo::CIT_ProgramMap lTcCit; T_ProgramInfo::CIT_ProgramMap lTeCit; glAttachShader(_instance.shaderId, lVpCit->second.programId); glAttachShader(_instance.shaderId, lFpCit->second.programId); // optional geometry program if (lGeometryId != -1) { const T_ProgramInfo & lGeometryProgram = m_geometryProgramArray[lGeometryId]; lGpCit = lGeometryProgram.programs.find(lOptions); glAttachShader(_instance.shaderId, lGpCit->second.programId); } // optional tesselation program if (lTessControlId != -1 && lTessEvaluationId != -1) { const T_ProgramInfo & lTessControlProgram = m_tessControlProgramArray[lTessControlId]; lTcCit = lTessControlProgram.programs.find(lOptions); const T_ProgramInfo & lTessEvaluationProgram = m_tessEvaluationProgramArray[lTessEvaluationId]; lTcCit = lTessEvaluationProgram.programs.find(lOptions); glAttachShader(_instance.shaderId, lTcCit->second.programId); glAttachShader(_instance.shaderId, lTeCit->second.programId); } glLinkProgram(_instance.shaderId); GLint lResult = 0; glGetProgramiv(_instance.shaderId, GL_LINK_STATUS, (GLint*)&lResult); if (lResult == GL_FALSE) { GLint lLogSize = 0; glGetProgramiv(_instance.shaderId, GL_INFO_LOG_LENGTH, &lLogSize); ArrayChar lLogMessage(lLogSize); glGetProgramInfoLog(_instance.shaderId, lLogSize, nullptr, lLogMessage.getData()); glDetachShader(_instance.shaderId, lVpCit->second.programId); glDetachShader(_instance.shaderId, lFpCit->second.programId); if (lGeometryId != -1) { glDetachShader(_instance.shaderId, lGpCit->second.programId); } if (lTessControlId != -1) { glDetachShader(_instance.shaderId, lTcCit->second.programId); } if (lTessEvaluationId != -1) { glDetachShader(_instance.shaderId, lTeCit->second.programId); } glDeleteProgram(_instance.shaderId); _instance.shaderId = 0; _instance.shaderState &= ~SHADER_LINKED; String vp = String("> using VP <") << lVertexProgram.programName; String fp = String("> using FP <") << lFragmentProgram.programName; String gp, tc, te; if (lGeometryId != -1) { const T_ProgramInfo & lGeometryProgram = m_geometryProgramArray[lGeometryId]; gp = String("> using GP <") << lGeometryProgram.programName; } if (lTessControlId != -1) { const T_ProgramInfo & lTesselationProgram = m_tessControlProgramArray[lTessControlId]; tc = String("> using TC <") << lTesselationProgram.programName; } if (lTessEvaluationId != -1) { const T_ProgramInfo & lEvaluationProgram = m_tessEvaluationProgramArray[lTessEvaluationId]; te = String("> using TE <") << lEvaluationProgram.programName; } O3D_ERROR(E_InvalidOperation(String("Shader : Unable to link the program <") << m_name << vp << fp << gp << tc << te << "> to the object <" << m_name << "> contained in the file : <" << m_programName << "> : " << lLogMessage.getData())); } else { GLint lLogSize = 0; glGetProgramiv(_instance.shaderId, GL_INFO_LOG_LENGTH, &lLogSize); if (lLogSize > 1) { ArrayChar lLogMessage('\0', lLogSize+1, 0); glGetProgramInfoLog(_instance.shaderId, lLogSize, nullptr, lLogMessage.getData()); String vp = String("> using VP <") << lVertexProgram.programName; String fp = String("> using FP <") << lFragmentProgram.programName; String gp, tc, te; if (lGeometryId != -1) { const T_ProgramInfo & lGeometryProgram = m_geometryProgramArray[lGeometryId]; gp = String("> using GP <") << lGeometryProgram.programName; } if (lTessControlId != -1) { const T_ProgramInfo & lTesselationProgram = m_tessControlProgramArray[lTessControlId]; tc = String("> using TC <") << lTesselationProgram.programName; } if (lTessEvaluationId != -1) { const T_ProgramInfo & lEvaluationProgram = m_tessEvaluationProgramArray[lTessEvaluationId]; te = String("> using TE <") << lEvaluationProgram.programName; } O3D_MESSAGE(String("Shader : Warning when link the program <") << m_name << vp << fp << gp << tc << te << "> to the object <" << m_name << "> contained in the file : <" << m_programName << "> : " << lLogMessage.getData()); } _instance.shaderState |= SHADER_LINKED; } glDetachShader(_instance.shaderId, lVpCit->second.programId); glDetachShader(_instance.shaderId, lFpCit->second.programId); if (lGeometryId != -1) { glDetachShader(_instance.shaderId, lGpCit->second.programId); } if (lTessControlId != -1) { glDetachShader(_instance.shaderId, lTcCit->second.programId); } if (lTessEvaluationId != -1) { glDetachShader(_instance.shaderId, lTeCit->second.programId); } } void Shader::refreshInstanceState() { for (IT_InstanceArray it = m_instances.begin(); it != m_instances.end(); it++) { String lOptions = (*it)->options; if (((*it)->vertexProgramId != -1) && ((m_vertexProgramArray[(*it)->vertexProgramId].programs[lOptions].programState & PROGRAM_COMPILED) != PROGRAM_COMPILED)) { continue; } if (((*it)->fragmentProgramId != -1) && ((m_fragmentProgramArray[(*it)->fragmentProgramId].programs[lOptions].programState & PROGRAM_COMPILED) != PROGRAM_COMPILED)) { continue; } if (((*it)->geometryProgramId != -1) && ((m_geometryProgramArray[(*it)->geometryProgramId].programs[lOptions].programState & PROGRAM_COMPILED) != PROGRAM_COMPILED)) { continue; } if (((*it)->tessControlProgramId != -1) && ((m_tessControlProgramArray[(*it)->tessControlProgramId].programs[lOptions].programState & PROGRAM_COMPILED) != PROGRAM_COMPILED)) { continue; } if (((*it)->tessEvaluationProgramId != -1) && ((m_tessEvaluationProgramArray[(*it)->tessEvaluationProgramId].programs[lOptions].programState & PROGRAM_COMPILED) != PROGRAM_COMPILED)) { continue; } (*it)->shaderState |= SHADER_COMPILED; } } void Shader::load(ProgramType programType, const String &programName, InStream &is) { if (programName.isEmpty()) { O3D_ERROR(E_InvalidParameter("Shader : Program name is missing")); } ArrayChar data; Int32 count = is.getAvailable(); data.setSize(count); is.read(data.getData(), count); addProgram(programType, programName, data.getData(), count); } void Shader::load(ProgramType programType, const String &programName, const String &filename) { if (programName.isEmpty()) { O3D_ERROR(E_InvalidParameter("Shader : Program name is missing")); } AutoPtr<InStream> lis(FileManager::instance()->openInStream(filename)); load(programType, programName, *lis); } void Shader::compileProgram(ProgramType _programType, Int32 _programIndex, const String & _options) { if (!isLoaded()) { O3D_ERROR(E_InvalidOperation(String("Shader : Attempt to compile an unloaded program."))); } if (_programIndex < 0) { O3D_ERROR(E_IndexOutOfRange(String("Shader : _programIndex < 0"))); } GLint lResult = 0; // transform the options string into multiple defines lines String options; if (_options.isValid()) { StringTokenizer optionsTokenizer(_options, ";"); while (optionsTokenizer.hasMoreElements()) { String define = optionsTokenizer.nextElement(); Int32 pos = define.find('='); if (pos != -1) { // define with value options += String("#define ") + define.sub(0, pos) + ' ' + define.sub(pos+1) + '\n'; } else { // simple define without value options += String("#define ") + define + '\n'; } } } T_ProgramArray *programArray = nullptr; GLuint programType = 0; String message; switch(_programType) { case TYPE_VERTEX_PROGRAM: programArray = &m_vertexProgramArray; programType = GL_VERTEX_SHADER; message = "VERTEX"; break; case TYPE_FRAGMENT_PROGRAM: programArray = &m_fragmentProgramArray; programType = GL_FRAGMENT_SHADER; message = "FRAGMENT"; break; case TYPE_GEOMETRY_PROGRAM: programArray = &m_geometryProgramArray; programType = GL_GEOMETRY_SHADER; message = "GEOMETRY"; break; case TYPE_TESS_CONTROL_PROGRAM: programArray = &m_tessControlProgramArray; programType = GL_TESS_CONTROL_SHADER; message = "TESSCTRL"; break; case TYPE_TESS_EVALUATION_PROGRAM: programArray = &m_tessEvaluationProgramArray; programType = GL_TESS_EVALUATION_SHADER; message = "TESSEVAL"; break; default: O3D_ERROR(E_InvalidParameter( String("Shader : Invalid program type <") << UInt32(_programType) << '>')); break; } if (_programIndex >= Int32(programArray->size())) { O3D_ERROR(E_IndexOutOfRange(String("Shader : _index (") << _programIndex << ") > " << Int32(programArray->size()))); } T_ProgramInfo & lProgramInfo = (*programArray)[_programIndex]; T_ProgramInfo::T_Program & lProgram = lProgramInfo.programs[_options]; if (lProgram.programState != PROGRAM_UNDEFINED) { O3D_ERROR(E_InvalidOperation(String("Shader : Trying to compile an already compiled or invalid program"))); } O3D_ASSERT(lProgram.programId == 0); // @todo inject optimal version if necessary (@see GLES too) String programStr = lProgramInfo.programSource.getData(); Int32 versionPos = programStr.sub("#version", 0); if (versionPos != -1) { versionPos = programStr.find('\n', versionPos); programStr.insert(options, versionPos+1); } else { programStr.insert(options, 0); } CString program = programStr.toAscii(); const Char *lBufferSource = program.getData(); const GLint lBufferSize = program.length(); lProgram.programId = glCreateShader(programType); glShaderSource(lProgram.programId, 1, &lBufferSource, &lBufferSize); glCompileShader(lProgram.programId); glGetShaderiv(lProgram.programId, GL_COMPILE_STATUS, &lResult); // If the compilation failed if(lResult == GL_FALSE) { GLint lLogSize = 0; glGetShaderiv(lProgram.programId, GL_INFO_LOG_LENGTH, &lLogSize); ArrayChar lLogMessage(lLogSize); glGetShaderInfoLog(lProgram.programId, lLogSize, nullptr, lLogMessage.getData()); glDeleteShader(lProgram.programId); lProgram.programId = 0; lProgram.programState = PROGRAM_INVALID; O3D_ERROR(E_InvalidOperation(String("Shader : Unable to compile the ") << message << " program <" << lProgramInfo.programName << "> of the object <" << m_name << "> contained in the file <" << m_programName << "> : " << lLogMessage.getData())); } else { GLint lLogSize = 0; glGetShaderiv(lProgram.programId, GL_INFO_LOG_LENGTH, &lLogSize); if (lLogSize > 1) { ArrayChar lLogMessage('\0', lLogSize+1, 0); glGetShaderInfoLog(lProgram.programId, lLogSize, nullptr, lLogMessage.getData()); O3D_WARNING(String("Shader : Warning when compile the ") << message << " program <" << lProgramInfo.programName << "> of the object <" << m_name << "> contained in the file <" << m_programName << "> : " << lLogMessage.getData()); } lProgram.programState = PROGRAM_COMPILED; } refreshInstanceState(); } //Bool Shader::CompileAllPrograms( // T_ProgramIndexArray * _vProgramArray, // T_ProgramIndexArray * _fProgramArray, // T_ProgramIndexArray * _gProgramArray) //{ // if (!isLoaded()) { // O3D_ERROR(O3D_E_InvalidOperation(O3DString("Shader : Attempt to compile an unloaded object."))); // } // Bool lRet = True; // // vertex // for (UInt32 k = 0 ; k < UInt32(m_vertexProgramArray.size()) ; ++k) // if (m_vertexProgramArray[k].programState == PROGRAM_UNDEFINED) // { // try // { // CompileProgram(TYPE_VERTEX_PROGRAM, k, ""); // } // catch(const O3D_E_InvalidOperation &) // { // if (_vProgramArray != nullptr) // { // _vProgramArray->push_back(k); // lRet = False; // } // } // } // else if ((m_vertexProgramArray[k].programState == PROGRAM_INVALID) && (_vProgramArray != nullptr)) // { // _vProgramArray->push_back(k); // lRet = False; // } // // fragment // for (UInt32 k = 0 ; k < UInt32(m_fragmentProgramArray.size()) ; ++k) // if (m_fragmentProgramArray[k].programState == PROGRAM_UNDEFINED) // { // try // { // CompileProgram(TYPE_FRAGMENT_PROGRAM, k, ""); // } // catch(const O3D_E_InvalidOperation &) // { // if (_fProgramArray != nullptr) // { // _fProgramArray->push_back(k); // lRet = False; // } // } // } // else if ((m_fragmentProgramArray[k].programState == PROGRAM_INVALID) && (_fProgramArray != nullptr)) // { // _fProgramArray->push_back(k); // lRet = False; // } // // geometry // for (UInt32 k = 0 ; k < UInt32(m_geometryProgramArray.size()) ; ++k) // if (m_geometryProgramArray[k].programState == PROGRAM_UNDEFINED) // { // try // { // CompileProgram(TYPE_GEOMETRY_PROGRAM, k, ""); // } // catch(const O3D_E_InvalidOperation &) // { // if (_gProgramArray != nullptr) // { // _gProgramArray->push_back(k); // lRet = False; // } // } // } // else if ((m_geometryProgramArray[k].programState == PROGRAM_INVALID) && (_gProgramArray != nullptr)) // { // _gProgramArray->push_back(k); // lRet = False; // } // refreshInstanceState(); // return lRet; //} void Shader::addProgram( ProgramType _programType, const String & _programName, const Char * _pBuffer, UInt32 _bufferSize) { O3D_ASSERT(_pBuffer != nullptr); T_ProgramInfo lProgramInfo; lProgramInfo.programName = _programName; lProgramInfo.programType = _programType; if (_bufferSize == 0) { lProgramInfo.programSource = CString(_pBuffer); } else if (_pBuffer != nullptr) { lProgramInfo.programSource = CString(_pBuffer, _bufferSize-1); } switch(_programType) { case TYPE_VERTEX_PROGRAM: if (findVertexProgram(_programName) != -1) { O3D_ERROR(E_InvalidOperation(String("Shader : Attempt to add a program <") << _programName << "> whose name is already used")); } else { m_vertexProgramArray.push_back(lProgramInfo); } break; case TYPE_FRAGMENT_PROGRAM: if (findFragmentProgram(_programName) != -1) { O3D_ERROR(E_InvalidOperation(String("Shader : Attempt to add a program <") << _programName << "> whose name is already used")); } else { m_fragmentProgramArray.push_back(lProgramInfo); } break; case TYPE_GEOMETRY_PROGRAM: if (findGeometryProgram(_programName) != -1) { O3D_ERROR(E_InvalidOperation(String("Shader : Attempt to add a program <") << _programName << "> whose name is already used")); } else { m_geometryProgramArray.push_back(lProgramInfo); } break; case TYPE_TESS_CONTROL_PROGRAM: if (findTessControlProgram(_programName) != -1) { O3D_ERROR(E_InvalidOperation(String("Shader : Attempt to add a program <") << _programName << "> whose name is already used")); } else { m_tessControlProgramArray.push_back(lProgramInfo); } break; case TYPE_TESS_EVALUATION_PROGRAM: if (findTessEvaluationProgram(_programName) != -1) { O3D_ERROR(E_InvalidOperation(String("Shader : Attempt to add a program <") << _programName << "> whose name is already used")); } else { m_tessEvaluationProgramArray.push_back(lProgramInfo); } break; default: break; } } void Shader::removeProgram(ProgramType _programType, const String & _programName) { Int32 lProgramId = -1; switch(_programType) { case TYPE_VERTEX_PROGRAM: if ((lProgramId = findVertexProgram(_programName)) == -1) { O3D_ERROR(E_InvalidOperation(String("Shader : Attempt to remove a unknown program <") << _programName << ">")); } else { T_ReferenceArray lToDetach; for (IT_ReferenceArray it = m_references.begin(); it != m_references.end(); it++) { if ((*it)->getVertexProgramIndex() == lProgramId) { lToDetach.push_back(*it); } } for (IT_ReferenceArray it = lToDetach.begin() ; it != lToDetach.end() ; it++) { (*it)->detach(); } IT_ProgramArray programIt = m_vertexProgramArray.begin() + lProgramId; // delete any shader for (T_ProgramInfo::IT_ProgramMap it = programIt->programs.begin(); it != programIt->programs.end(); it++) { if (it->second.programId != 0) { glDeleteShader(it->second.programId); } } // and the structure of the program m_vertexProgramArray.erase(programIt); } break; case TYPE_FRAGMENT_PROGRAM: if ((lProgramId = findFragmentProgram(_programName)) == -1) { O3D_ERROR(E_InvalidOperation(String("Shader : Attempt to remove a unknown program <") << _programName << ">")); } else { T_ReferenceArray lToDetach; for (IT_ReferenceArray it = m_references.begin(); it != m_references.end(); it++) { if ((*it)->getFragmentProgramIndex() == lProgramId) { lToDetach.push_back(*it); } } for (IT_ReferenceArray it = lToDetach.begin() ; it != lToDetach.end() ; it++) { (*it)->detach(); } IT_ProgramArray programIt = m_fragmentProgramArray.begin() + lProgramId; // delete any shader for (T_ProgramInfo::IT_ProgramMap it = programIt->programs.begin(); it != programIt->programs.end(); it++) { if (it->second.programId != 0) { glDeleteShader(it->second.programId); } } // and the structure of the program m_fragmentProgramArray.erase(programIt); } break; case TYPE_GEOMETRY_PROGRAM: if ((lProgramId = findGeometryProgram(_programName)) == -1) { O3D_ERROR(E_InvalidOperation(String("Shader : Attempt to remove a unknown program <") << _programName << ">")); } else { T_ReferenceArray lToDetach; for (IT_ReferenceArray it = m_references.begin(); it != m_references.end(); it++) { if ((*it)->getGeometryProgramIndex() == lProgramId) { lToDetach.push_back(*it); } } for (IT_ReferenceArray it = lToDetach.begin() ; it != lToDetach.end() ; it++) { (*it)->detach(); } IT_ProgramArray programIt = m_geometryProgramArray.begin() + lProgramId; // delete any shader for (T_ProgramInfo::IT_ProgramMap it = programIt->programs.begin(); it != programIt->programs.end(); it++) { if (it->second.programId != 0) { glDeleteShader(it->second.programId); } } // and the structure of the program m_geometryProgramArray.erase(programIt); } break; case TYPE_TESS_CONTROL_PROGRAM: if ((lProgramId = findTessControlProgram(_programName)) == -1) { O3D_ERROR(E_InvalidOperation(String("Shader : Attempt to remove a unknown program <") << _programName << ">")); } else { T_ReferenceArray lToDetach; for (IT_ReferenceArray it = m_references.begin(); it != m_references.end(); it++) { if ((*it)->getTessControlProgramIndex() == lProgramId) { lToDetach.push_back(*it); } } for (IT_ReferenceArray it = lToDetach.begin() ; it != lToDetach.end() ; it++) { (*it)->detach(); } IT_ProgramArray programIt = m_tessControlProgramArray.begin() + lProgramId; // delete any shader for (T_ProgramInfo::IT_ProgramMap it = programIt->programs.begin(); it != programIt->programs.end(); it++) { if (it->second.programId != 0) { glDeleteShader(it->second.programId); } } // and the structure of the program m_tessControlProgramArray.erase(programIt); } break; case TYPE_TESS_EVALUATION_PROGRAM: if ((lProgramId = findTessEvaluationProgram(_programName)) == -1) { O3D_ERROR(E_InvalidOperation(String("Shader : Attempt to remove a unknown program <") << _programName << ">")); } else { T_ReferenceArray lToDetach; for (IT_ReferenceArray it = m_references.begin(); it != m_references.end(); it++) { if ((*it)->getTessEvaluationProgramIndex() == lProgramId) { lToDetach.push_back(*it); } } for (IT_ReferenceArray it = lToDetach.begin() ; it != lToDetach.end() ; it++) { (*it)->detach(); } IT_ProgramArray programIt = m_tessEvaluationProgramArray.begin() + lProgramId; // delete any shader for (T_ProgramInfo::IT_ProgramMap it = programIt->programs.begin(); it != programIt->programs.end(); it++) { if (it->second.programId != 0) { glDeleteShader(it->second.programId); } } // and the structure of the program m_tessEvaluationProgramArray.erase(programIt); } break; default: { O3D_ASSERT(0); break; } } } void Shader::destroy() { m_programName.destroy(); m_name.destroy(); for (IT_ProgramArray it = m_vertexProgramArray.begin(); it != m_vertexProgramArray.end(); it++) { for (T_ProgramInfo::IT_ProgramMap it2 = it->programs.begin(); it2 != it->programs.end(); it2++) { if (it2->second.programId != 0) { glDeleteShader(it2->second.programId); } } } for (IT_ProgramArray it = m_fragmentProgramArray.begin() ; it != m_fragmentProgramArray.end() ; it++) { for (T_ProgramInfo::IT_ProgramMap it2 = it->programs.begin(); it2 != it->programs.end(); it2++) { if (it2->second.programId != 0) { glDeleteShader(it2->second.programId); } } } for (IT_ProgramArray it = m_geometryProgramArray.begin() ; it != m_geometryProgramArray.end() ; it++) { for (T_ProgramInfo::IT_ProgramMap it2 = it->programs.begin(); it2 != it->programs.end(); it2++) { if (it2->second.programId != 0) { glDeleteShader(it2->second.programId); } } } for (IT_ProgramArray it = m_tessControlProgramArray.begin() ; it != m_tessControlProgramArray.end() ; it++) { for (T_ProgramInfo::IT_ProgramMap it2 = it->programs.begin(); it2 != it->programs.end(); it2++) { if (it2->second.programId != 0) { glDeleteShader(it2->second.programId); } } } for (IT_ProgramArray it = m_tessEvaluationProgramArray.begin() ; it != m_tessEvaluationProgramArray.end() ; it++) { for (T_ProgramInfo::IT_ProgramMap it2 = it->programs.begin(); it2 != it->programs.end(); it2++) { if (it2->second.programId != 0) { glDeleteShader(it2->second.programId); } } } m_vertexProgramArray.clear(); m_fragmentProgramArray.clear(); m_geometryProgramArray.clear(); m_tessControlProgramArray.clear(); m_tessEvaluationProgramArray.clear(); T_ReferenceArray lArray = m_references; for (std::vector<ShaderInstance*>::iterator itInstance = lArray.begin(); itInstance != lArray.end(); itInstance++) { ((*itInstance)->detach()); } O3D_ASSERT(m_instances.empty()); } void Shader::buildInstance(ShaderInstance & _instance) const { _instance.attach(const_cast<Shader*>(this)); } const String& Shader::getVertexProgramName(Int32 _vertexIndex) const { if ((_vertexIndex < 0) || (_vertexIndex >= Int32(m_vertexProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid vertex index"))); } return m_vertexProgramArray[_vertexIndex].programName; } const String& Shader::getFragmentProgramName(Int32 _fragmentIndex) const { if ((_fragmentIndex < 0) || (_fragmentIndex >= Int32(m_fragmentProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid fragment index"))); } return m_fragmentProgramArray[_fragmentIndex].programName; } const String& Shader::getGeometryProgramName(Int32 _geometryIndex) const { if ((_geometryIndex < 0) || (_geometryIndex >= Int32(m_geometryProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid geometry index"))); } return m_geometryProgramArray[_geometryIndex].programName; } const String &Shader::getTessControlProgramName(Int32 _tessControlIndex) const { if ((_tessControlIndex < 0) || (_tessControlIndex >= Int32(m_tessControlProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid tesselation control index"))); } return m_tessControlProgramArray[_tessControlIndex].programName; } const String &Shader::getTessEvaluationProgramName(Int32 _tessEvaluationIndex) const { if ((_tessEvaluationIndex < 0) || (_tessEvaluationIndex >= Int32(m_tessEvaluationProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid tesselation evaluation index"))); } return m_tessEvaluationProgramArray[_tessEvaluationIndex].programName; } //! Return the source of a given vertex program const CString& Shader::getVertexProgramSource(Int32 _vertexIndex) const { if ((_vertexIndex < 0) || (_vertexIndex >= Int32(m_vertexProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid vertex index"))); } return m_vertexProgramArray[_vertexIndex].programSource; } //! Return the source of a given fragment program const CString& Shader::getFragmentProgramSource(Int32 _fragmentIndex) const { if ((_fragmentIndex < 0) || (_fragmentIndex >= Int32(m_fragmentProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid fragment index"))); } return m_fragmentProgramArray[_fragmentIndex].programSource; } const CString& Shader::getGeometryProgramSource(Int32 _geometryIndex) const { if ((_geometryIndex < 0) || (_geometryIndex >= Int32(m_geometryProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid geometry index"))); } return m_geometryProgramArray[_geometryIndex].programSource; } const CString& Shader::getTessControlProgramSource(Int32 _tessControlIndex) const { if ((_tessControlIndex < 0) || (_tessControlIndex >= Int32(m_tessControlProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid tesselation control index"))); } return m_tessControlProgramArray[_tessControlIndex].programSource; } const CString& Shader::getTessEvaluationProgramSource(Int32 _tessEvaluationIndex) const { if ((_tessEvaluationIndex < 0) || (_tessEvaluationIndex >= Int32(m_tessEvaluationProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid tesselation evaluation index"))); } return m_tessEvaluationProgramArray[_tessEvaluationIndex].programSource; } Shader::ProgramState Shader::getVertexProgramState(Int32 _vertexIndex, const String & _options) const { if ((_vertexIndex < 0) || (_vertexIndex >= Int32(m_vertexProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid vertex index"))); } T_ProgramInfo::CIT_ProgramMap cit = m_vertexProgramArray[_vertexIndex].programs.find(_options); if (cit == m_vertexProgramArray[_vertexIndex].programs.end()) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid vertex options"))); } return cit->second.programState; } Shader::ProgramState Shader::getFragmentProgramState(Int32 _fragmentIndex, const String & _options) const { if ((_fragmentIndex < 0) || (_fragmentIndex >= Int32(m_fragmentProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid fragment index"))); } T_ProgramInfo::CIT_ProgramMap cit = m_fragmentProgramArray[_fragmentIndex].programs.find(_options); if (cit == m_fragmentProgramArray[_fragmentIndex].programs.end()) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid fragment options"))); } return cit->second.programState; } Shader::ProgramState Shader::getGeometryProgramState(Int32 _geometryIndex, const String & _options) const { if ((_geometryIndex < 0) || (_geometryIndex >= Int32(m_geometryProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid geometry index"))); } T_ProgramInfo::CIT_ProgramMap cit = m_geometryProgramArray[_geometryIndex].programs.find(_options); if (cit == m_geometryProgramArray[_geometryIndex].programs.end()) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid geometry options"))); } return cit->second.programState; } Shader::ProgramState Shader::getTessControlProgramState(Int32 _tessControlIndex, const String & _options) const { if ((_tessControlIndex < 0) || (_tessControlIndex >= Int32(m_tessControlProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid tesselation control index"))); } T_ProgramInfo::CIT_ProgramMap cit = m_tessControlProgramArray[_tessControlIndex].programs.find(_options); if (cit == m_tessControlProgramArray[_tessControlIndex].programs.end()) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid tesselation control options"))); } return cit->second.programState; } Shader::ProgramState Shader::getTessEvaluationProgramState(Int32 _tessEvaluationIndex, const String & _options) const { if ((_tessEvaluationIndex < 0) || (_tessEvaluationIndex >= Int32(m_tessEvaluationProgramArray.size()))) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid tesselation evaluation index"))); } T_ProgramInfo::CIT_ProgramMap cit = m_tessEvaluationProgramArray[_tessEvaluationIndex].programs.find(_options); if (cit == m_tessEvaluationProgramArray[_tessEvaluationIndex].programs.end()) { O3D_ERROR(E_IndexOutOfRange(String("Shader : Invalid tesselation evaluation options"))); } return cit->second.programState; } Int32 Shader::findVertexProgram(const String & _programName) const { Int32 lIndex = 0; for (CIT_ProgramArray it = m_vertexProgramArray.begin() ; it != m_vertexProgramArray.end() ; it++, ++lIndex) { if (it->programName.compare(_programName, String::CASE_INSENSITIVE) == 0) { return lIndex; } } return -1; } Int32 Shader::findFragmentProgram(const String & _programName) const { Int32 lIndex = 0; for (CIT_ProgramArray it = m_fragmentProgramArray.begin() ; it != m_fragmentProgramArray.end() ; it++, ++lIndex) { if (it->programName.compare(_programName, String::CASE_INSENSITIVE) == 0) { return lIndex; } } return -1; } Int32 Shader::findGeometryProgram(const String & _programName) const { Int32 lIndex = 0; for (CIT_ProgramArray it = m_geometryProgramArray.begin() ; it != m_geometryProgramArray.end() ; it++, ++lIndex) { if (it->programName.compare(_programName, String::CASE_INSENSITIVE) == 0) { return lIndex; } } return -1; } Int32 Shader::findTessControlProgram(const String & _programName) const { Int32 lIndex = 0; for (CIT_ProgramArray it = m_tessControlProgramArray.begin() ; it != m_tessControlProgramArray.end() ; it++, ++lIndex) { if (it->programName.compare(_programName, String::CASE_INSENSITIVE) == 0) { return lIndex; } } return -1; } Int32 Shader::findTessEvaluationProgram(const String & _programName) const { Int32 lIndex = 0; for (CIT_ProgramArray it = m_tessEvaluationProgramArray.begin() ; it != m_tessEvaluationProgramArray.end() ; it++, ++lIndex) { if (it->programName.compare(_programName, String::CASE_INSENSITIVE) == 0) { return lIndex; } } return -1; } //--------------------------------------------------------------------------------------- // ShaderInstance //--------------------------------------------------------------------------------------- ShaderInstance::ShaderInstance(): m_shader(nullptr), m_pInstance(nullptr), m_uniformLocations(), m_attribLocations() { } ShaderInstance::ShaderInstance(const ShaderInstance & _which): m_shader(nullptr), m_pInstance(nullptr), m_uniformLocations(_which.m_uniformLocations), m_attribLocations(_which.m_attribLocations) { attach(_which.m_shader); if ((m_pInstance = _which.m_pInstance) != nullptr) { ++(m_pInstance->refCounter); } } ShaderInstance::~ShaderInstance() { detach(); } ShaderInstance & ShaderInstance::operator = (const ShaderInstance & _which) { if (this == &_which) { return *this; } detach(); m_shader = _which.m_shader; m_pInstance = _which.m_pInstance; if (m_shader != nullptr) { //m_pShader->useIt(); m_shader->m_references.push_back(this); } if (m_pInstance != nullptr) { ++m_pInstance->refCounter; } m_uniformLocations = _which.m_uniformLocations; m_attribLocations = _which.m_attribLocations; return *this; } void ShaderInstance::attach(Shader* _pShading) { if (m_shader != _pShading) { detach(); m_shader = _pShading; if (m_shader != nullptr) { //m_pShader->useIt(); m_shader->m_references.push_back(this); } } } void ShaderInstance::detach() { if (m_pInstance != nullptr) { if (m_pInstance->pOwner == this) { // It means this instance has bound the program O3D_ASSERT(isInUse()); O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Attempt to detach a currently used shader"))); unbindShader(); } if (--(m_pInstance->refCounter) == 0) { Shader::IT_InstanceArray itInstance = std::find(m_shader->m_instances.begin(), m_shader->m_instances.end(), m_pInstance); O3D_ASSERT(itInstance != m_shader->m_instances.end()); if (m_pInstance->shaderId != 0) { glDeleteProgram(m_pInstance->shaderId); } deletePtr(*itInstance); m_shader->m_instances.erase(itInstance); } m_pInstance = nullptr; } if (m_shader != nullptr) { std::vector<ShaderInstance*>::iterator it = std::find(m_shader->m_references.begin(), m_shader->m_references.end(), this); O3D_ASSERT(it != m_shader->m_references.end()); m_shader->m_references.erase(it); //m_pShader->releaseIt(); m_shader = nullptr; } } //! bind the shader program void ShaderInstance::bindShader() { if (!isLoaded()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Object not loaded"))); } else if (!isDefined()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Attempt to bind a shader, but you need to select a vertex/fragment program first"))); } else if (isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Attempt to bind twice the same shader"))); } else { if (!isCompiled()) { m_shader->compileInstance(*m_pInstance); } if (!isLinked()) { m_shader->linkInstance(*m_pInstance); } #ifdef _DEBUG if (m_shader->getScene()->getContext()->getCurrentShader() != 0) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : You must first unbound the current shader"))); } #endif O3D_ASSERT(m_pInstance->pOwner == nullptr); m_shader->getScene()->getContext()->bindShader(m_pInstance->shaderId); m_pInstance->shaderState |= Shader::SHADER_INUSE; m_pInstance->pOwner = this; } } //! unbound the shader program void ShaderInstance::unbindShader() { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Attempt to unbound a shader which is not currently running"))); } else { #ifdef _DEBUG if (m_shader->getScene()->getContext()->getCurrentShader() != m_pInstance->shaderId) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Shader's state is not synchronized with GLContext"))); } #endif O3D_ASSERT(m_pInstance->pOwner == this); m_shader->getScene()->getContext()->bindShader(0); m_pInstance->shaderState &= ~Shader::SHADER_INUSE; m_pInstance->pOwner = nullptr; } } void ShaderInstance::assign( Int32 _vertexIndex, Int32 _fragmentIndex, Int32 _geometryIndex, Int32 _tessControlIndex, Int32 _tessEvaluationIndex, const String & _options, Shader::BuildType _type) { if (!isLoaded()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Object not loaded"))); } if ((_vertexIndex >= Int32(m_shader->m_vertexProgramArray.size())) || (_vertexIndex < 0)) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid vertex program index"))); } if ((_fragmentIndex >= Int32(m_shader->m_fragmentProgramArray.size())) || (_fragmentIndex < 0)) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid fragment program index"))); } if (_geometryIndex >= Int32(m_shader->m_geometryProgramArray.size())) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid geometry program index"))); } if (_tessControlIndex >= Int32(m_shader->m_tessControlProgramArray.size())) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid tesselation program index"))); } if (_tessEvaluationIndex >= Int32(m_shader->m_tessEvaluationProgramArray.size())) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid evaluation program index"))); } if (isDefined()) { if (--(m_pInstance->refCounter) == 0) { Shader::IT_InstanceArray itInstance = std::find(m_shader->m_instances.begin(), m_shader->m_instances.end(), m_pInstance); O3D_ASSERT(itInstance != m_shader->m_instances.end()); if (m_pInstance->shaderId != 0) { glDeleteProgram(m_pInstance->shaderId); } deletePtr(*itInstance); m_shader->m_instances.erase(itInstance); } m_pInstance = nullptr; } for (Shader::IT_InstanceArray it = m_shader->m_instances.begin() ; it != m_shader->m_instances.end() ; it++) { if (((*it)->vertexProgramId == _vertexIndex) && ((*it)->fragmentProgramId == _fragmentIndex) && ((*it)->geometryProgramId == _geometryIndex) && ((*it)->tessControlProgramId == _tessControlIndex) && ((*it)->tessEvaluationProgramId == _tessEvaluationIndex) && ((*it)->options == _options)) { m_pInstance = (*it); ++(m_pInstance->refCounter); } } if (m_pInstance == nullptr) { Shader::T_InstanceInfo * lInfo = new Shader::T_InstanceInfo; lInfo->vertexProgramId = _vertexIndex; lInfo->fragmentProgramId = _fragmentIndex; lInfo->geometryProgramId = _geometryIndex; lInfo->tessControlProgramId = _tessControlIndex; lInfo->tessEvaluationProgramId = _tessEvaluationIndex; lInfo->options = _options; lInfo->shaderId = 0; lInfo->shaderState = Shader::SHADER_DEFINED | Shader::SHADER_LOADED; lInfo->refCounter = 0; lInfo->pOwner = nullptr; m_shader->m_instances.push_back(lInfo); m_pInstance = m_shader->m_instances.back(); m_pInstance->refCounter++; } if (_type != Shader::BUILD_DEFINE) { build(_type); } } void ShaderInstance::assign( Int32 _vertexIndex, Int32 _fragmentIndex, const String & _options, Shader::BuildType _type) { if (!isLoaded()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Object not loaded"))); } if ((_vertexIndex >= Int32(m_shader->m_vertexProgramArray.size())) || (_vertexIndex < 0)) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid vertex program index"))); } if ((_fragmentIndex >= Int32(m_shader->m_fragmentProgramArray.size())) || (_fragmentIndex < 0)) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid fragment program index"))); } if (isDefined()) { if (--(m_pInstance->refCounter) == 0) { Shader::IT_InstanceArray itInstance = std::find(m_shader->m_instances.begin(), m_shader->m_instances.end(), m_pInstance); O3D_ASSERT(itInstance != m_shader->m_instances.end()); if (m_pInstance->shaderId != 0) { glDeleteProgram(m_pInstance->shaderId); } deletePtr(*itInstance); m_shader->m_instances.erase(itInstance); } m_pInstance = nullptr; } for (Shader::IT_InstanceArray it = m_shader->m_instances.begin() ; it != m_shader->m_instances.end() ; it++) { if (((*it)->vertexProgramId == _vertexIndex) && ((*it)->fragmentProgramId == _fragmentIndex) && ((*it)->options == _options)) { m_pInstance = (*it); ++(m_pInstance->refCounter); } } if (m_pInstance == nullptr) { Shader::T_InstanceInfo * lInfo = new Shader::T_InstanceInfo; lInfo->vertexProgramId = _vertexIndex; lInfo->fragmentProgramId = _fragmentIndex; lInfo->geometryProgramId = -1; lInfo->tessControlProgramId = -1; lInfo->tessEvaluationProgramId = -1; lInfo->options = _options; lInfo->shaderId = 0; lInfo->shaderState = Shader::SHADER_DEFINED | Shader::SHADER_LOADED; lInfo->refCounter = 0; lInfo->pOwner = nullptr; m_shader->m_instances.push_back(lInfo); m_pInstance = m_shader->m_instances.back(); m_pInstance->refCounter++; } if (_type != Shader::BUILD_DEFINE) { build(_type); } } void ShaderInstance::assign( const String & _vertexProgram, const String & _fragmentProgram, const String & _geometryProgram, const String & _tessControlProgram, const String & _tessEvaluationProgram, const String & _options, Shader::BuildType _type) { if (!isLoaded()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Object not loaded"))); } if (_vertexProgram.isEmpty()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid vertex program name"))); } if (_fragmentProgram.isEmpty()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid fragment program name"))); } Int32 lVertexIndex = m_shader->findVertexProgram(_vertexProgram); if (lVertexIndex == -1) { O3D_ERROR(E_InvalidParameter(String("ShaderInstance : Unknown vertex program name <") << _vertexProgram << '>')); } Int32 lFragmentIndex = m_shader->findFragmentProgram(_fragmentProgram); if (lFragmentIndex == -1) { O3D_ERROR(E_InvalidParameter(String("ShaderInstance : Unknown fragment program name <") << _fragmentProgram << '>')); } // optional geometry program Int32 lGeometryIndex = -1; if (_geometryProgram.isValid()) { lGeometryIndex = m_shader->findGeometryProgram(_geometryProgram); if (lGeometryIndex == -1) { O3D_ERROR(E_InvalidParameter(String("ShaderInstance : Unknown geometry program name <") << _geometryProgram << '>')); } } // optional tesselation program Int32 lTessControlIndex = -1; Int32 lTessEvaluationIndex = -1; if (_tessControlProgram.isValid() && _tessEvaluationProgram.isValid()) { lTessControlIndex = m_shader->findTessControlProgram(_tessControlProgram); lTessEvaluationIndex = m_shader->findTessEvaluationProgram(_tessEvaluationProgram); if (lTessControlIndex == -1) { O3D_ERROR(E_InvalidParameter(String("ShaderInstance : Unknown tesselation control program name <") << _tessControlProgram << '>')); } if (lTessEvaluationIndex == -1) { O3D_ERROR(E_InvalidParameter(String("ShaderInstance : Unknown tesselation evaluation program name <") << _tessEvaluationProgram << '>')); } } assign(lVertexIndex, lFragmentIndex, lGeometryIndex, lTessControlIndex, lTessEvaluationIndex, _options, _type); } void ShaderInstance::assign( const String & _vertexProgram, const String & _fragmentProgram, const String & _options, Shader::BuildType _type) { if (!isLoaded()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Object not loaded"))); } if (_vertexProgram.isEmpty()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid vertex program name"))); } if (_fragmentProgram.isEmpty()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid fragment program name"))); } Int32 lVertexIndex = m_shader->findVertexProgram(_vertexProgram); if (lVertexIndex == -1) { O3D_ERROR(E_InvalidParameter(String("ShaderInstance : Unknown vertex program name <") << _vertexProgram << '>')); } Int32 lFragmentIndex = m_shader->findFragmentProgram(_fragmentProgram); if (lFragmentIndex == -1) { O3D_ERROR(E_InvalidParameter(String("ShaderInstance : Unknown fragment program name <") << _fragmentProgram << '>')); } assign(lVertexIndex, lFragmentIndex, -1, -1, -1, _options, _type); } void ShaderInstance::build(Shader::BuildType _type) { if (!isLoaded()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Object not loaded"))); } if (!isDefined()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Object not defined"))); } if ((_type == Shader::BUILD_COMPILE) && (!isCompiled())) { m_shader->compileInstance(*m_pInstance); } else if (_type == Shader::BUILD_COMPILE_AND_LINK) { if (!isCompiled()) { m_shader->compileInstance(*m_pInstance); } if (!isLinked()) { m_shader->linkInstance(*m_pInstance); } } } void ShaderInstance::setConstInt(const Char* name,const Int32 constant) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define a uniform location if the shader is not bound"))); } Int32 location = glGetUniformLocation(m_pInstance->shaderId,name); if (location >= 0) { glUniform1i(location,constant); } else { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid uniform variable <") << name << " >")); } } void ShaderInstance::setConstUInt(const Char* name,const UInt32 constant) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define a uniform location if the shader is not bound"))); } Int32 location = glGetUniformLocation(m_pInstance->shaderId,name); if (location >= 0) { glUniform1ui(location,constant); } else { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid uniform variable <") << name << " >")); } } void ShaderInstance::setConstBool(const Char* name,const Bool constant) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define a uniform location if the shader is not bound"))); } Int32 location = glGetUniformLocation(m_pInstance->shaderId,name); if (location >= 0) { glUniform1i(location,Int32(constant)); } else { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid uniform variable <") << name << " >")); } } void ShaderInstance::setConstFloat(const Char* name,const Float constant) { if (!isInUse()) O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define a uniform location if the shader is not bound"))); Int32 location = glGetUniformLocation(m_pInstance->shaderId,name); if (location >= 0) glUniform1f(location,constant); else O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid uniform variable <") << name << " >")); } void ShaderInstance::setConstVector2(const Char* name,const Vector2f& constant) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define a uniform location if the shader is not bound"))); } Int32 location = glGetUniformLocation(m_pInstance->shaderId,name); if (location >= 0) { glUniform2fv(location,1,constant.getData()); } else { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid uniform variable <") << name << " >")); } } void ShaderInstance::setConstColor(const Char* name,const Color& constant) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define a uniform location if the shader is not bound"))); } Int32 location = glGetUniformLocation(m_pInstance->shaderId,name); if (location >= 0) { glUniform4fv(location,1,constant.getData()); } else { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid uniform variable <") << name << " >")); } } void ShaderInstance::setConstVector3(const Char* name,const Vector3& constant) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define a uniform location if the shader is not bound"))); } Int32 location = glGetUniformLocation(m_pInstance->shaderId,name); if (location >= 0) { glUniform3fv(location,1,constant.getData()); } else { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid uniform variable <") << name << " >")); } } void ShaderInstance::setConstVector4(const Char* name,const Vector3& constant) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define a uniform location if the shader is not bound"))); } Int32 location = glGetUniformLocation(m_pInstance->shaderId,name); if (location >= 0) { glUniform4f(location,constant[X],constant[Y],constant[Z],1.0f); } else { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid uniform variable <") << name << " >")); } } void ShaderInstance::setConstVector4(const Char* name,const Vector4& constant) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define a uniform location if the shader is not bound"))); } Int32 location = glGetUniformLocation(m_pInstance->shaderId,name); if (location >= 0) { glUniform4fv(location,1,constant.getData()); } else { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid uniform variable <") << name << " >")); } } void ShaderInstance::setConstMatrix3( const Char* name, const Bool transpose, const Matrix3& constant) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define a uniform location if the shader is not bound"))); } Int32 location = glGetUniformLocation(m_pInstance->shaderId,name); if (location >= 0) { glUniformMatrix3fv(location,1,transpose,constant.getData()); } else { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid uniform variable <") << name << " >")); } } void ShaderInstance::setConstMatrix4( const Char* name, const Bool transpose, const Matrix4& constant) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define a uniform location if the shader is not bound"))); } Int32 location = glGetUniformLocation(m_pInstance->shaderId,name); if (location >= 0) { glUniformMatrix4fv(location,1,transpose,constant.getData()); } else { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid uniform variable <") << name << " >")); } } void ShaderInstance::setNConstMatrix4( const Char* name, Int32 num, const Bool transpose, const Float* constant) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define a uniform location if the shader is not bound"))); } Int32 location = glGetUniformLocation(m_pInstance->shaderId,name); if (location >= 0) { glUniformMatrix4fv(location,num,transpose,constant); } else { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid uniform variable <") << name << " >")); } } void ShaderInstance::setConstTexture(const Char* name, Texture* pTexture, Int32 texUnit) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define define a texture if the shader is not bound"))); } if (pTexture != nullptr) { Int32 location = glGetUniformLocation(m_pInstance->shaderId,name); if (location >= 0) { pTexture->getScene()->getContext()->setActiveTextureUnit(texUnit); pTexture->bind(); glUniform1i(location,texUnit); } else { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid texture name <") << name << " >")); } } else { O3D_ERROR(E_InvalidParameter(String("ShaderInstance : Null texture"))); } } void ShaderInstance::setConstTexture(Int32 Location, Texture* pTexture, Int32 texUnit) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define a uniform location if the shader is not bound"))); } if (pTexture != nullptr) { if (Location >= 0) { pTexture->getScene()->getContext()->setActiveTextureUnit(texUnit); pTexture->bind(); glUniform1i(Location,texUnit); } else { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Invalid texture location <") << pTexture->getName() << " >")); } } else { O3D_ERROR(E_InvalidParameter(String("ShaderInstance : Null texture"))); } } #include <o3d/engine/uniformbuffer.h> UInt32 ShaderInstance::getUniformBlockIndex(const Char *name) { if (!isLinked()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : The shader must be linked to be able to get uniform block index"))); } UInt32 lIndex = glGetUniformBlockIndex(m_pInstance->shaderId, name); return lIndex; } void ShaderInstance::setUniformBlock(const Char *name, UniformBuffer &uniformBuffer, UInt32 bindingPoint) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define define an uniform block if the shader is not bound"))); } UInt32 blockIndex = glGetUniformBlockIndex(m_pInstance->shaderId, name); uniformBuffer.bindBufferBase(bindingPoint); glUniformBlockBinding(m_pInstance->shaderId, blockIndex, bindingPoint); } void ShaderInstance::setUniformBlock(UInt32 blockIndex, UniformBuffer &uniformBuffer, UInt32 bindingPoint) { if (!isInUse()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : Can not define define an uniform block if the shader is not bound"))); } uniformBuffer.bindBufferBase(bindingPoint); glUniformBlockBinding(m_pInstance->shaderId, blockIndex, bindingPoint); } Int32 ShaderInstance::getAttributeLocation(const Char *name) const { if (!isLinked()) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : The shader must be linked to be able to get uniform variable location"))); } Int32 lLocation = glGetAttribLocation(m_pInstance->shaderId, name); if (lLocation == -1) { O3D_ERROR(E_InvalidOperation(String("ShaderInstance : There is not attribute called <") << name << "> in the program <" << getProgramName() << ">")); } else { return lLocation; } } //----------------------------------------------------------------------------------- // LOCATION CONTAINER //----------------------------------------------------------------------------------- void ShaderInstance::setUniform(Int32 _key, Int32 _value) { O3D_ASSERT((_key >= 0) && (_key < 128)); if ((_key < 0) || (_key >= 128)) { O3D_ERROR(E_InvalidOperation("Invalid key : must be <= 128")); } if (UInt32(_key) >= m_uniformLocations.size()) { m_uniformLocations.resize(1+_key, Int32(O3D_INFINITE)); } m_uniformLocations[_key] = _value; } Int32 ShaderInstance::getUniform(Int32 _key) const { O3D_ASSERT((_key >= 0) && (_key < 128)); if ((_key < 0) || (_key >= 128)) { O3D_ERROR(E_InvalidOperation("Invalid uniform key : must be <= 128")); } if ((UInt32(_key) >= m_uniformLocations.size()) || (m_uniformLocations[_key] == Int32(O3D_INFINITE))) { O3D_ERROR(E_InvalidOperation(String::print("Uniform key %d is not assigned", _key))); } return m_uniformLocations[_key]; } void ShaderInstance::setAttribute(Int32 _key, UInt32 _value) { O3D_ASSERT((_key >= 0) && (_key < 128)); if ((_key < 0) || (_key >= 128)) { O3D_ERROR(E_InvalidOperation("Invalid attribute key : must be <= 128")); } if (UInt32(_key) >= m_attribLocations.size()) { m_attribLocations.resize(1+_key, UInt32(O3D_INFINITE)); } m_attribLocations[_key] = _value; } UInt32 ShaderInstance::getAttribute(Int32 _key) const { O3D_ASSERT((_key >= 0) && (_key < 128)); if ((_key < 0) || (_key >= 128)) { O3D_ERROR(E_InvalidOperation("Invalid attribute key : must be <= 128")); } if ((UInt32(_key) >= m_attribLocations.size()) || (m_attribLocations[_key] == O3D_INFINITE)) { O3D_ERROR(E_InvalidOperation(String::print("Attribute key %d is not assigned", _key))); } return m_attribLocations[_key]; } void ShaderInstance::removeUniform(Int32 _key) { O3D_ASSERT((_key >= 0) && (_key < 128)); if ((_key < 0) || (_key >= 128)) { O3D_ERROR(E_InvalidOperation("Invalid uniform key : must be <= 128")); } if (UInt32(_key) < m_uniformLocations.size()) { m_uniformLocations[_key] = O3D_INFINITE; } } void ShaderInstance::removeUniforms() { m_uniformLocations.clear(); } void ShaderInstance::removeAttribute(Int32 _key) { O3D_ASSERT((_key >= 0) && (_key < 128)); if ((_key < 0) || (_key >= 128)) { O3D_ERROR(E_InvalidOperation("Invalid attribute key : must be <= 128")); } if (UInt32(_key) < m_attribLocations.size()) { m_attribLocations[_key] = O3D_INFINITE; } } void ShaderInstance::removeAttributes() { m_attribLocations.clear(); }
34.305352
192
0.660264
[ "geometry", "object", "vector", "transform" ]
48a2e0ca4789575b14126d132be9913286991540
8,143
hpp
C++
attic/test/Aligned_Allocator.hpp
grassofsky/llfio
8b27842c25c47fd49ab64209463fc23268270975
[ "Apache-2.0" ]
356
2018-07-09T23:00:22.000Z
2022-03-27T11:41:35.000Z
attic/test/Aligned_Allocator.hpp
grassofsky/llfio
8b27842c25c47fd49ab64209463fc23268270975
[ "Apache-2.0" ]
80
2018-07-22T13:05:36.000Z
2022-01-12T11:34:57.000Z
attic/test/Aligned_Allocator.hpp
grassofsky/llfio
8b27842c25c47fd49ab64209463fc23268270975
[ "Apache-2.0" ]
35
2018-11-08T20:44:11.000Z
2022-02-27T16:03:01.000Z
/* * File: Aligned_Allocator.hpp * Author: atlas * * Created on July 5, 2013, 6:52 PM Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cstddef> #include <memory> #include <type_traits> #include <typeinfo> #include <vector> //! \def BOOST_AFIO_PACKEDTYPE(typedecl) The markup this compiler uses to pack a structure as tightly as possible #ifndef BOOST_AFIO_PACKEDTYPE #ifdef BOOST_MSVC #define BOOST_AFIO_PACKEDTYPE(typedecl) __pragma(pack(push, 1)) typedecl __pragma(pack(pop)) #elif defined(__GNUC__) #define BOOST_AFIO_PACKEDTYPE(typedecl) typedecl __attribute__((packed)) #else #define BOOST_AFIO_PACKEDTYPE(typedecl) unknown_type_pack_markup_for_this_compiler #endif #endif BOOST_AFIO_V2_NAMESPACE_BEGIN namespace detail { enum class allocator_alignment : size_t { Default = sizeof(void*), //!< The default alignment on this machine. SSE = 16, //!< The alignment for SSE. Better to use M128 for NEON et al support. M128 = 16, //!< The alignment for a 128 bit vector. AVX = 32, //!< The alignment for AVX. Better to use M256 for NEON et al support. M256 = 32 //!< The alignment for a 256 bit vector. }; #ifdef BOOST_WINDOWS extern "C" void *_aligned_malloc(size_t size, size_t alignment); extern "C" void _aligned_free(void *blk); #else extern "C" int posix_memalign(void **memptr, size_t alignment, size_t size); #endif inline void* allocate_aligned_memory(size_t align, size_t size) { #ifdef BOOST_WINDOWS return _aligned_malloc(size, align); #else void *ret=nullptr; if(posix_memalign(&ret, align, size)) return nullptr; return ret; #endif } inline void deallocate_aligned_memory(void* ptr) noexcept { #ifdef BOOST_WINDOWS _aligned_free(ptr); #else free(ptr); #endif } /*! \class aligned_allocator \brief An STL allocator which allocates aligned memory Stolen from http://stackoverflow.com/questions/12942548/making-stdvector-allocate-aligned-memory */ template <typename T, size_t Align=std::alignment_of<T>::value, bool initialize=true> class aligned_allocator { public: typedef T value_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; enum { alignment=Align }; typedef std::true_type propagate_on_container_move_assignment; template <class U> struct rebind { typedef aligned_allocator<U, Align, initialize> other; }; public: aligned_allocator() noexcept {} template <class U> aligned_allocator(const aligned_allocator<U, Align, initialize>&) noexcept {} size_type max_size() const noexcept { return (size_type(~0) - size_type(Align)) / sizeof(T); } pointer address(reference x) const noexcept { return std::addressof(x); } const_pointer address(const_reference x) const noexcept { return std::addressof(x); } pointer allocate(size_type n, typename aligned_allocator<void, Align, initialize>::const_pointer = 0) { const size_type alignment = static_cast<size_type>( Align ); void* ptr = detail::allocate_aligned_memory(alignment , n * sizeof(T)); if (ptr == nullptr) { throw std::bad_alloc(); } return reinterpret_cast<pointer>(ptr); } void deallocate(pointer p, size_type) noexcept { return detail::deallocate_aligned_memory(p); } template <class U, class ...Args> void construct(U* p, Args&&... args) { if(initialize || !std::is_same<char, U>::value) ::new(reinterpret_cast<void*>(p)) U(std::forward<Args>(args)...); } void destroy(pointer p) { (void) p; p->~T(); } }; template <size_t Align, bool initialize> class aligned_allocator<void, Align, initialize> { public: typedef void value_type; typedef void * pointer; typedef const void * const_pointer; typedef void reference; typedef const void const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; enum { alignment=Align }; }; template <size_t Align, bool initialize> class aligned_allocator<const void, Align, initialize> { public: typedef const void value_type; typedef const void* pointer; typedef const void* const_pointer; typedef void reference; typedef const void const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; enum { alignment=Align }; }; template <typename T, size_t Align, bool initialize> class aligned_allocator<const T, Align, initialize> { public: typedef T value_type; typedef const T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; enum { alignment=Align }; typedef std::true_type propagate_on_container_move_assignment; template <class U> struct rebind { typedef aligned_allocator<U, Align, initialize> other; }; public: aligned_allocator() noexcept {} template <class U> aligned_allocator(const aligned_allocator<U, Align, initialize>&) noexcept {} size_type max_size() const noexcept { return (size_type(~0) - size_type(Align)) / sizeof(T); } const_pointer address(const_reference x) const noexcept { return std::addressof(x); } pointer allocate(size_type n, typename aligned_allocator<void, Align, initialize>::const_pointer = 0) { const size_type alignment = static_cast<size_type>( Align ); void* ptr = detail::allocate_aligned_memory(alignment , n * sizeof(T)); if (ptr == nullptr) { throw std::bad_alloc(); } return reinterpret_cast<pointer>(ptr); } void deallocate(pointer p, size_type) noexcept { return detail::deallocate_aligned_memory(p); } template <class U, class ...Args> void construct(U* p, Args&&... args) { if(initialize || !std::is_same<char, U>::value) ::new(reinterpret_cast<void*>(p)) U(std::forward<Args>(args)...); } void destroy(pointer p) { p->~T(); } }; template <typename T, size_t TAlign, bool Tinit, typename U, size_t UAlign, bool Uinit> inline bool operator== (const aligned_allocator<T,TAlign,Tinit>&, const aligned_allocator<U, UAlign, Uinit>&) noexcept { return TAlign == UAlign; } template <typename T, size_t TAlign, bool Tinit, typename U, size_t UAlign, bool Uinit> inline bool operator!= (const aligned_allocator<T,TAlign,Tinit>&, const aligned_allocator<U, UAlign, Uinit>&) noexcept { return TAlign != UAlign; } }//namespace detail BOOST_AFIO_V2_NAMESPACE_END
31.319231
121
0.702812
[ "object", "vector" ]
48aa0da766541465201f066a59a1eef04d55aca0
10,729
hpp
C++
src/collision_tensor/dense/storage/vbcrs_sparsity.hpp
simonpintarelli/2dBoltzmann
bc6b7bbeffa242ce80937947444383b416ba3fc9
[ "BSD-3-Clause" ]
null
null
null
src/collision_tensor/dense/storage/vbcrs_sparsity.hpp
simonpintarelli/2dBoltzmann
bc6b7bbeffa242ce80937947444383b416ba3fc9
[ "BSD-3-Clause" ]
null
null
null
src/collision_tensor/dense/storage/vbcrs_sparsity.hpp
simonpintarelli/2dBoltzmann
bc6b7bbeffa242ce80937947444383b416ba3fc9
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <boost/assert.hpp> #include <iostream> #include <map> #include <ostream> #include <tuple> #include <vector> #include "enum/enum.hpp" #include "aux/filtered_range.hpp" namespace boltzmann { namespace ct_dense { /** * @brief Variable sized block compressed row storage format. E.g. CSR made up of variable sized * blocks. This class stores only locations of non-zero blocks and no actual values/entries. * * @tparam ALIGN Align to ALIGN units (e.g. doubles, floats, ...), this is not alignment in bytes. * * This is a compressed version of \ref MultiSlice. * * Notation: y = A*x * Thus x_offset, x_extent refer to columns and y_offset, y_extent to rows. * */ template <int ALIGN = 4> class VBCRSSparsity { public: typedef unsigned int size_t; typedef long unsigned int mem_size_t; struct block_t { block_t() {} block_t(size_t offset_, size_t extent_) : offset(offset_) , extent(extent_) { } size_t offset; size_t extent; }; typedef int block_idx; public: /// align subblocks to `align` doubles static size_t align; public: VBCRSSparsity() { /* empty */} template <typename INDEX_TYPE, typename SUBBLOCK> void init(const std::multimap<INDEX_TYPE, SUBBLOCK>& multi_slices, const int K); template <typename INDEX_TYPE, typename SUBBLOCK, typename SUPER_BLOCK> void init(const std::multimap<INDEX_TYPE, SUBBLOCK>& multi_slice, const std::vector<SUPER_BLOCK>& super_blocks); /** * @param idx block row index * * for use in \ref get_block * * @return begin of row */ size_t row_begin(size_t idx) const; /** * @param idx block row index * * for use in \ref get_block * * @return end of row */ size_t row_end(size_t idx) const; /** * @param block_idx * * to iterate over a block row use \ref row_begin, \ref row_end as input * * @return column offset, column width */ const block_t& get_block(block_idx block_idx) const; /** * @param idx block row index * * @return row offset, row height (as struct{offset, extent}). */ const block_t& get_row_info(size_t idx) const; /* * number of storage units (assuming each block is aligned to 4 units) * * 4 units because we store 64bit floating point numbers and align to 256 bits (AVX) */ mem_size_t memsize() const; size_t dimz() const; /// number of rows / columns size_t nblock_rows() const; /// total number of blocks size_t nblocks() const; /// number of nonzero entries size_t nnz() const; void save(std::ostream& out) const; private: /// length = number of block rows + 1 std::vector<block_idx> row_ptr_; /// length = number of block rows std::vector<block_t> block_rows_; // row offset, row height (for each block row) /// length = nnz std::vector<block_t> block_columns_; // column offset, column width (for each block) /// length = nnz+1 // std::vector<mem_size_t> mem_offsets_; // memory offset mem_size_t memsize_; size_t dimz_; size_t nnz_; bool is_initialized_ = false; }; template <int ALIGN> unsigned int VBCRSSparsity<ALIGN>::align = ALIGN; template <int ALIGN> template <typename INDEX_TYPE, typename SUBBLOCK> void VBCRSSparsity<ALIGN>::init(const std::multimap<INDEX_TYPE, SUBBLOCK>& multi_slice, const int K) { BOOST_ASSERT(is_initialized_ == false); block_idx block_count = 0; int row_id = 0; // size_t row_offset = 0; mem_size_t mem_offset = 0; nnz_ = 0; block_rows_.resize(2 * K - 1); row_ptr_.resize(2 * K); for (int k = 0; k < K; ++k) { for (auto t : {TRIG::COS, TRIG::SIN}) { // sin(0*phi) == 0 is of course not contained in the basis if (k == 0 && t == TRIG::SIN) continue; // row_ptr points to the first block in this row row_ptr_[row_id] = block_count; auto key = std::make_tuple(k, t); if (multi_slice.find(key) == multi_slice.end()) { block_rows_[row_id] = block_t(0, 0); // this row is empty } else { // key = (angular index, sin or cos) auto range = multi_slice.equal_range(key); block_rows_[row_id] = block_t(range.first->second.offset_x, range.first->second.size_x); dimz_ = range.first->second.size_z; for (auto row_it = range.first; row_it != range.second; ++row_it) { auto& sblock = row_it->second; block_columns_.push_back(block_t(sblock.offset_y, sblock.size_y)); // leading dimension (lda) (e.g. row in col-major matrix storage) // of a sub-block must be 128bit aligned! mem_size_t lsize = (sblock.size_x + (align - (sblock.size_x % align))) * sblock.size_y * sblock.size_z; nnz_ += sblock.size_x * sblock.size_y * sblock.size_z; mem_offset += lsize; block_count++; } } row_id++; // std::cout << std::get<0>(key) << " " << std::get<1>(key) << "\n"; } } row_ptr_[row_id] = block_count; // one past last byte // mem_offsets_.push_back(mem_offset); memsize_ = mem_offset; // one past last row BOOST_ASSERT(row_id == 2 * K - 1); // BOOST_ASSERT(mem_offsets_.size() == block_count + 1); BOOST_ASSERT((*row_ptr_.rbegin()) == block_count); BOOST_ASSERT(multi_slice.size() == this->nblocks()); is_initialized_ = true; } template <int ALIGN> template <typename INDEX_TYPE, typename SUBBLOCK, typename SUPER_BLOCK> void VBCRSSparsity<ALIGN>::init(const std::multimap<INDEX_TYPE, SUBBLOCK>& multi_slice, const std::vector<SUPER_BLOCK>& super_blocks) { // INDEX_TYPE := tuple<k, t> // k: polynomial degree // t: enum TRIG (eg. SIN or COS) nnz_ = 0; block_rows_.resize(super_blocks.size()); row_ptr_.resize(super_blocks.size() + 1); block_idx block_count = 0; std::map<size_t, size_t> sblock_offset_to_idx; size_t offset = 0; for (unsigned int i = 0; i < super_blocks.size(); ++i) { const auto& sblock = super_blocks[i]; size_t loffset = sblock.index_first; size_t extent = sblock.extent; block_rows_[i] = block_t(loffset, extent); offset += extent; sblock_offset_to_idx[offset] = i; } // for each entry in super_blocks find super_block_row_id (row id) // and super_block_col_id (column id) typedef int row_idx_t; typedef int col_idx_t; typedef std::pair<row_idx_t, col_idx_t> block_key_t; std::set<block_key_t> block_nnz_ids; for (const auto& elem : multi_slice) { int row_offset = elem.second.offset_x; int col_offset = elem.second.offset_y; auto it_row = sblock_offset_to_idx.upper_bound(row_offset); BOOST_ASSERT(it_row != sblock_offset_to_idx.end()); auto it_col = sblock_offset_to_idx.upper_bound(col_offset); BOOST_ASSERT(it_col != sblock_offset_to_idx.end()); size_t scol_idx = it_row->second; size_t srow_idx = it_col->second; block_nnz_ids.insert(std::make_pair(srow_idx, scol_idx)); dimz_ = elem.second.size_z; } // for (auto elem : block_nnz_ids) { // std::cout << "block_nnz: " << elem.first << ", " << elem.second << "\n"; // } // todo: fill row_ptr and block_columns_ mem_size_t mem_offset = 0; size_t block_counter = 0; for (unsigned int srow_idx = 0; srow_idx < super_blocks.size(); ++srow_idx) { row_ptr_[srow_idx] = block_counter; size_t row_extent = super_blocks[srow_idx].extent; auto range = filtered_range( block_nnz_ids.begin(), block_nnz_ids.end(), [srow_idx](const block_key_t& key) { return key.first == srow_idx; }); std::vector<block_key_t> elems(std::get<0>(range), std::get<1>(range)); // debug/test output //std::cout << "on block " << srow_idx << " found " << elems.size() << " elements\n"; for (const block_key_t& elem : elems) { //std::cout << elem.first << ", " << elem.second << "\n"; size_t scol_idx = elem.second; const auto& sblock = super_blocks[scol_idx]; int col_begin = sblock.index_first; size_t col_extent = sblock.extent; block_columns_.push_back(block_t(col_begin, col_extent)); block_counter++; mem_size_t lsize = (row_extent + (align - (row_extent % align))) * col_extent * dimz_; nnz_ += row_extent*col_extent*dimz_; mem_offset += lsize; } } // last row_ptr_ points one past the last block row_ptr_[super_blocks.size()] = block_counter; memsize_ = mem_offset; BOOST_ASSERT(block_nnz_ids.size() == this->nblocks()); is_initialized_ = true; } template <int ALIGN> inline typename VBCRSSparsity<ALIGN>::size_t VBCRSSparsity<ALIGN>::row_begin(size_t idx) const { BOOST_ASSERT(idx < row_ptr_.size()); return row_ptr_[idx]; } template <int ALIGN> inline typename VBCRSSparsity<ALIGN>::size_t VBCRSSparsity<ALIGN>::row_end(size_t idx) const { BOOST_ASSERT(idx + 1 < row_ptr_.size()); return row_ptr_[idx + 1]; } template <int ALIGN> inline const typename VBCRSSparsity<ALIGN>::block_t& VBCRSSparsity<ALIGN>::get_block(block_idx block_idx) const { BOOST_ASSERT(block_idx < block_columns_.size()); return block_columns_[block_idx]; } template <int ALIGN> inline const typename VBCRSSparsity<ALIGN>::block_t& VBCRSSparsity<ALIGN>::get_row_info(size_t idx) const { BOOST_ASSERT(idx < block_rows_.size()); return block_rows_[idx]; } template <int ALIGN> inline typename VBCRSSparsity<ALIGN>::mem_size_t VBCRSSparsity<ALIGN>::memsize() const { // return *(mem_offsets_.rbegin()); return memsize_; } template <int ALIGN> inline typename VBCRSSparsity<ALIGN>::size_t VBCRSSparsity<ALIGN>::dimz() const { return dimz_; } template <int ALIGN> inline typename VBCRSSparsity<ALIGN>::size_t VBCRSSparsity<ALIGN>::nblock_rows() const { BOOST_ASSERT(block_rows_.size()); // there is one pointer past the end, thus -1 return block_rows_.size(); } template <int ALIGN> inline void VBCRSSparsity<ALIGN>::save(std::ostream& out) const { out << "row_begin col_begin row_extent col_extent\n"; for(size_t row_idx = 0; row_idx < this->nblock_rows(); ++row_idx) { size_t row_offset = get_row_info(row_idx).offset; size_t row_extent = get_row_info(row_idx).extent; for(size_t ptr = row_begin(row_idx); ptr < row_end(row_idx); ++ptr) { size_t col_offset = get_block(ptr).offset; size_t col_extent = get_block(ptr).extent; out << row_offset << " " << col_offset << " " << row_extent << " " << col_extent << "\n"; } } } template <int ALIGN> inline typename VBCRSSparsity<ALIGN>::size_t VBCRSSparsity<ALIGN>::nblocks() const { return (*row_ptr_.rbegin()); } template<int ALIGN> inline typename VBCRSSparsity<ALIGN>::size_t VBCRSSparsity<ALIGN>::nnz() const { return nnz_; } } // ct_dense } // end namespace boltzmann
29.802778
98
0.670426
[ "vector" ]
48ad00bea17bf3c58757ecf7c756cf03472a214f
5,431
cpp
C++
src/model/Document.cpp
rizwanniazigroupdocs/aspose-slides-cloud-cpp
f668947a72f717a955bc4579537e853b9e43eb45
[ "MIT" ]
null
null
null
src/model/Document.cpp
rizwanniazigroupdocs/aspose-slides-cloud-cpp
f668947a72f717a955bc4579537e853b9e43eb45
[ "MIT" ]
null
null
null
src/model/Document.cpp
rizwanniazigroupdocs/aspose-slides-cloud-cpp
f668947a72f717a955bc4579537e853b9e43eb45
[ "MIT" ]
1
2020-12-25T16:15:58.000Z
2020-12-25T16:15:58.000Z
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Aspose" file="ApiBase.cs"> // Copyright (c) 2020 Aspose.Slides for Cloud // </copyright> // <summary> // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // </summary> // -------------------------------------------------------------------------------------------------------------------- #include "Document.h" namespace asposeslidescloud { namespace model { Document::Document() { } Document::~Document() { } std::shared_ptr<ResourceUri> Document::getDocumentProperties() const { return m_DocumentProperties; } void Document::setDocumentProperties(std::shared_ptr<ResourceUri> value) { m_DocumentProperties = value; } std::shared_ptr<ResourceUri> Document::getViewProperties() const { return m_ViewProperties; } void Document::setViewProperties(std::shared_ptr<ResourceUri> value) { m_ViewProperties = value; } std::shared_ptr<ResourceUri> Document::getSlides() const { return m_Slides; } void Document::setSlides(std::shared_ptr<ResourceUri> value) { m_Slides = value; } std::shared_ptr<ResourceUri> Document::getImages() const { return m_Images; } void Document::setImages(std::shared_ptr<ResourceUri> value) { m_Images = value; } std::shared_ptr<ResourceUri> Document::getLayoutSlides() const { return m_LayoutSlides; } void Document::setLayoutSlides(std::shared_ptr<ResourceUri> value) { m_LayoutSlides = value; } std::shared_ptr<ResourceUri> Document::getMasterSlides() const { return m_MasterSlides; } void Document::setMasterSlides(std::shared_ptr<ResourceUri> value) { m_MasterSlides = value; } web::json::value Document::toJson() const { web::json::value val = this->ResourceBase::toJson(); if (m_DocumentProperties != nullptr) { val[utility::conversions::to_string_t("DocumentProperties")] = ModelBase::toJson(m_DocumentProperties); } if (m_ViewProperties != nullptr) { val[utility::conversions::to_string_t("ViewProperties")] = ModelBase::toJson(m_ViewProperties); } if (m_Slides != nullptr) { val[utility::conversions::to_string_t("Slides")] = ModelBase::toJson(m_Slides); } if (m_Images != nullptr) { val[utility::conversions::to_string_t("Images")] = ModelBase::toJson(m_Images); } if (m_LayoutSlides != nullptr) { val[utility::conversions::to_string_t("LayoutSlides")] = ModelBase::toJson(m_LayoutSlides); } if (m_MasterSlides != nullptr) { val[utility::conversions::to_string_t("MasterSlides")] = ModelBase::toJson(m_MasterSlides); } return val; } void Document::fromJson(web::json::value& val) { this->ResourceBase::fromJson(val); web::json::value* jsonForDocumentProperties = ModelBase::getField(val, "DocumentProperties"); if(jsonForDocumentProperties != nullptr && !jsonForDocumentProperties->is_null()) { std::shared_ptr<ResourceUri> newItem(new ResourceUri()); newItem->fromJson(*jsonForDocumentProperties); setDocumentProperties(newItem); } web::json::value* jsonForViewProperties = ModelBase::getField(val, "ViewProperties"); if(jsonForViewProperties != nullptr && !jsonForViewProperties->is_null()) { std::shared_ptr<ResourceUri> newItem(new ResourceUri()); newItem->fromJson(*jsonForViewProperties); setViewProperties(newItem); } web::json::value* jsonForSlides = ModelBase::getField(val, "Slides"); if(jsonForSlides != nullptr && !jsonForSlides->is_null()) { std::shared_ptr<ResourceUri> newItem(new ResourceUri()); newItem->fromJson(*jsonForSlides); setSlides(newItem); } web::json::value* jsonForImages = ModelBase::getField(val, "Images"); if(jsonForImages != nullptr && !jsonForImages->is_null()) { std::shared_ptr<ResourceUri> newItem(new ResourceUri()); newItem->fromJson(*jsonForImages); setImages(newItem); } web::json::value* jsonForLayoutSlides = ModelBase::getField(val, "LayoutSlides"); if(jsonForLayoutSlides != nullptr && !jsonForLayoutSlides->is_null()) { std::shared_ptr<ResourceUri> newItem(new ResourceUri()); newItem->fromJson(*jsonForLayoutSlides); setLayoutSlides(newItem); } web::json::value* jsonForMasterSlides = ModelBase::getField(val, "MasterSlides"); if(jsonForMasterSlides != nullptr && !jsonForMasterSlides->is_null()) { std::shared_ptr<ResourceUri> newItem(new ResourceUri()); newItem->fromJson(*jsonForMasterSlides); setMasterSlides(newItem); } } } }
29.042781
119
0.710551
[ "model" ]
48ad17c90c18a2e85455550e2a99da9fe4aafc05
98,669
cpp
C++
src/DuMMForceFieldSubsystem.cpp
samuelflores/molmodel
d05a5b69fe0717ba4d9720023bff5a61d206c36f
[ "MIT" ]
null
null
null
src/DuMMForceFieldSubsystem.cpp
samuelflores/molmodel
d05a5b69fe0717ba4d9720023bff5a61d206c36f
[ "MIT" ]
1
2020-12-09T16:45:16.000Z
2020-12-09T16:56:52.000Z
src/DuMMForceFieldSubsystem.cpp
samuelflores/molmodel
d05a5b69fe0717ba4d9720023bff5a61d206c36f
[ "MIT" ]
4
2020-06-23T18:24:37.000Z
2021-04-29T14:44:25.000Z
/* -------------------------------------------------------------------------- * * SimTK Molmodel(tm) * * -------------------------------------------------------------------------- * * This is part of the SimTK biosimulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org. * * * * Portions copyright (c) 2006-11 Stanford University and the Authors. * * Authors: Michael Sherman * * Contributors: Christopher Bruns, Randy Radmer * * * * Permission is hereby granted, free of charge, to any person obtaining a * * copy of this software and associated documentation files (the "Software"), * * to deal in the Software without restriction, including without limitation * * the rights to use, copy, modify, merge, publish, distribute, sublicense, * * and/or sell copies of the Software, and to permit persons to whom the * * Software is furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in * * all copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * * THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * * USE OR OTHER DEALINGS IN THE SOFTWARE. * * -------------------------------------------------------------------------- */ /**@file * * Private implementation of DuMMForceFieldSubsystem. Units here are uniformly * MD units: nanometers, daltons, picoseconds, with energy in kilojoules/mole. * We accept angles from users in degrees, but use only radians internally. */ #include "molmodel/internal/common.h" #include "molmodel/internal/DuMMForceFieldSubsystem.h" #include "DuMMForceFieldSubsystemRep.h" #include "TinkerAmber99.h" using namespace SimTK; //////////////////////////////// // DUMM FORCE FIELD SUBSYSTEM // //////////////////////////////// /*static*/ bool DuMMForceFieldSubsystem::isInstanceOf(const Subsystem& s) { return DuMMForceFieldSubsystemRep::isA(s.getSubsystemGuts()); } /*static*/ const DuMMForceFieldSubsystem& DuMMForceFieldSubsystem::downcast(const Subsystem& s) { assert(isInstanceOf(s)); return reinterpret_cast<const DuMMForceFieldSubsystem&>(s); } /*static*/ DuMMForceFieldSubsystem& DuMMForceFieldSubsystem::updDowncast(Subsystem& s) { assert(isInstanceOf(s)); return reinterpret_cast<DuMMForceFieldSubsystem&>(s); } const DuMMForceFieldSubsystemRep& DuMMForceFieldSubsystem::getRep() const { return dynamic_cast<const DuMMForceFieldSubsystemRep&>( getSubsystemGuts() ); } DuMMForceFieldSubsystemRep& DuMMForceFieldSubsystem::updRep() { return dynamic_cast<DuMMForceFieldSubsystemRep&>( updSubsystemGuts() ); } // Create Subsystem but don't associate it with any System. This isn't much use except // for making std::vector's, which require a default constructor to be available. Real DuMMForceFieldSubsystem::calcPotentialEnergy(const State& state) const {return getRep().calcPotentialEnergy(state);}; DuMMForceFieldSubsystem::DuMMForceFieldSubsystem() : ForceSubsystem() { adoptSubsystemGuts(new DuMMForceFieldSubsystemRep()); } DuMMForceFieldSubsystem::DuMMForceFieldSubsystem(MolecularMechanicsSystem& mms) : ForceSubsystem() { adoptSubsystemGuts(new DuMMForceFieldSubsystemRep()); mms.setMolecularMechanicsForceSubsystem(*this); // steal ownership } DuMM::AtomClassIndex DuMMForceFieldSubsystem::getAtomClassIndex(DuMM::AtomIndex atomIx) const { DuMM::ChargedAtomTypeIndex typeIx = getRep().atoms[atomIx].chargedAtomTypeIndex; return getRep().chargedAtomTypes[typeIx].atomClassIx; } Real DuMMForceFieldSubsystem::getVdwRadius(DuMM::AtomClassIndex atomClassIx) const { return getRep().atomClasses[atomClassIx].vdwRadius; } Real DuMMForceFieldSubsystem::getVdwWellDepth(DuMM::AtomClassIndex atomClassIx) const { return getRep().atomClasses[atomClassIx].vdwWellDepth; } void DuMMForceFieldSubsystem::dumpCForceFieldParameters(std::ostream& os, const String& methodName) const { const DuMMForceFieldSubsystemRep& mm = getRep(); os << "void " << methodName << "(DuMMForceFieldSubsystem& dumm)" << std::endl; os << "{" << std::endl; // open method // 1) define atom classes for (DuMM::AtomClassIndex i(0); i < (int)mm.atomClasses.size(); ++i) { if (!mm.atomClasses[i].isValid()) continue; const AtomClass& atomClass = mm.atomClasses[i]; os << " dumm."; atomClass.generateSelfCode(os); os << std::endl; } os << std::endl; // 2) define charged atom types for (DuMM::ChargedAtomTypeIndex i(0); i < (int)mm.chargedAtomTypes.size(); ++i) { if (!mm.chargedAtomTypes[i].isValid()) continue; const ChargedAtomType& chargedAtomType = mm.chargedAtomTypes[i]; os << " dumm."; chargedAtomType.generateSelfCode(os); os << std::endl; } os << std::endl; // 3) bond stretch parameters std::map<AtomClassIndexPair, BondStretch>::const_iterator b; for (b = mm.bondStretch.begin(); b != mm.bondStretch.end(); ++b) { os << " dumm."; b->second.generateSelfCode(os); os << std::endl; } os << std::endl; // 4) bond bend parameters std::map<AtomClassIndexTriple, BondBend>::const_iterator bendI; for (bendI = mm.bondBend.begin(); bendI != mm.bondBend.end(); ++bendI) { os << " dumm."; bendI->second.generateSelfCode(os); os << std::endl; } os << std::endl; // 5) bond torsion parameters std::map<AtomClassIndexQuad, BondTorsion>::const_iterator t; for (t = mm.bondTorsion.begin(); t != mm.bondTorsion.end(); ++t) { os << " dumm."; t->second.generateSelfCode(os); os << std::endl; } os << std::endl; // 6) amber-style improper torsion parameters for (t = mm.amberImproperTorsion.begin(); t != mm.amberImproperTorsion.end(); ++t) { os << " dumm."; t->second.generateSelfCode(os, 2); os << std::endl; } os << std::endl; // 7) global parameters // van der Waals mixing rule os << " dumm.setVdwMixingRule("; switch (getVdwMixingRule()) { case WaldmanHagler: os << "DuMMForceFieldSubsystem::WaldmanHagler"; break; case HalgrenHHG: os << "DuMMForceFieldSubsystem::HalgrenHHG"; break; case Jorgensen: os << "DuMMForceFieldSubsystem::Jorgensen"; break; case LorentzBerthelot: os << "DuMMForceFieldSubsystem::LorentzBerthelot"; break; case Kong: os << "DuMMForceFieldSubsystem::Kong"; break; default: assert(false); os << "DuMMForceFieldSubsystem::WaldmanHagler"; break; } os << ");" << std::endl; os << " dumm.setVdw12ScaleFactor(" << mm.vdwScale12 << ");" << std::endl; os << " dumm.setVdw13ScaleFactor(" << mm.vdwScale13 << ");" << std::endl; os << " dumm.setVdw14ScaleFactor(" << mm.vdwScale14 << ");" << std::endl; os << " dumm.setVdw15ScaleFactor(" << mm.vdwScale15 << ");" << std::endl; os << " dumm.setCoulomb12ScaleFactor(" << mm.coulombScale12 << ");" << std::endl; os << " dumm.setCoulomb13ScaleFactor(" << mm.coulombScale13 << ");" << std::endl; os << " dumm.setCoulomb14ScaleFactor(" << mm.coulombScale14 << ");" << std::endl; os << " dumm.setCoulomb15ScaleFactor(" << mm.coulombScale15 << ");" << std::endl; os << " dumm.setVdwGlobalScaleFactor(" << mm.vdwGlobalScaleFactor << ");" << std::endl; os << " dumm.setCoulombGlobalScaleFactor(" << mm.coulombGlobalScaleFactor << ");" << std::endl; os << " dumm.setGbsaGlobalScaleFactor(" << mm.gbsaGlobalScaleFactor << ");" << std::endl; os << " dumm.setBondStretchGlobalScaleFactor(" << mm.bondStretchGlobalScaleFactor << ");" << std::endl; os << " dumm.setBondBendGlobalScaleFactor(" << mm.bondBendGlobalScaleFactor << ");" << std::endl; os << " dumm.setBondTorsionGlobalScaleFactor(" << mm.bondTorsionGlobalScaleFactor << ");" << std::endl; os << " dumm.setAmberImproperTorsionGlobalScaleFactor(" << mm.amberImproperTorsionGlobalScaleFactor << ");" << std::endl; os << " dumm.setCustomBondStretchGlobalScaleFactor(" << mm.customBondStretchGlobalScaleFactor << ");" << std::endl; os << " dumm.setCustomBondBendGlobalScaleFactor(" << mm.customBondBendGlobalScaleFactor << ");" << std::endl; os << " dumm.setCustomBondTorsionGlobalScaleFactor(" << mm.customBondTorsionGlobalScaleFactor << ");" << std::endl; os << " dumm.setIncludeGbsaAceApproximation(" << mm.gbsaIncludeAceApproximation << ");" << std::endl; os << "}" << std::endl; // end of method } void DuMMForceFieldSubsystem::defineIncompleteAtomClass (DuMM::AtomClassIndex atomClassIx, const char* atomClassName, int element, int valence) { static const char* MethodName = "defineIncompleteAtomClass"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); // Catch nonsense arguments. SimTK_APIARGCHECK1_ALWAYS(atomClassIx.isValid(), mm.ApiClassName, MethodName, "atom class Index %d invalid: must be nonnegative", (int) atomClassIx); SimTK_APIARGCHECK1_ALWAYS(mm.isValidElement(element), mm.ApiClassName, MethodName, "element %d invalid: must be a valid atomic number and have an entry here",element); SimTK_APIARGCHECK1_ALWAYS(valence >= 0, mm.ApiClassName, MethodName, "expected valence %d invalid: must be nonnegative", valence); // Make sure there is a slot available for this atom class. if (atomClassIx >= (DuMM::AtomClassIndex)mm.atomClasses.size()) mm.atomClasses.resize(atomClassIx+1); // Make sure this atom class hasn't already been defined. SimTK_APIARGCHECK2_ALWAYS(!mm.atomClasses[atomClassIx].isValid(), mm.ApiClassName, MethodName, "atom class Index %d is already in use for '%s'", (int) atomClassIx, mm.atomClasses[atomClassIx].name.c_str()); if (mm.atomClassIndicesByName.find(atomClassName) != mm.atomClassIndicesByName.end()) { DuMM::AtomClassIndex oldAtomClassIx = mm.atomClassIndicesByName.find(atomClassName)->second; if (oldAtomClassIx != atomClassIx) { throw(std::runtime_error(String("Duplicate atom class name: ") + atomClassName)); } } mm.insertNewAtomClass( AtomClass(atomClassIx, atomClassName, element, valence, NaN, NaN) ); } void DuMMForceFieldSubsystem::setAtomClassVdwParameters(DuMM::AtomClassIndex atomClassIx, Real vdwRadiusInNm, Real vdwWellDepthInKJPerMol) { static const char* MethodName = "setAtomClassVdwParameters"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(atomClassIx.isValid(), mm.ApiClassName, MethodName, "atom class Index %d invalid: must be nonnegative", (int) atomClassIx); SimTK_APIARGCHECK1_ALWAYS(vdwRadiusInNm >= 0, mm.ApiClassName, MethodName, "van der Waals radius %g invalid: must be nonnegative", vdwRadiusInNm); SimTK_APIARGCHECK1_ALWAYS(vdwWellDepthInKJPerMol >= 0, mm.ApiClassName, MethodName, "van der Waals energy well depth %g invalid: must be nonnegative", vdwWellDepthInKJPerMol); AtomClass& atomClass = mm.atomClasses[atomClassIx]; atomClass.vdwRadius = vdwRadiusInNm; atomClass.vdwWellDepth = vdwWellDepthInKJPerMol; } bool DuMMForceFieldSubsystem::isValidAtomClass(DuMM::AtomClassIndex atomClassIx) const { return getRep().isValidAtomClass(atomClassIx); } void DuMMForceFieldSubsystem::defineIncompleteChargedAtomType (DuMM::ChargedAtomTypeIndex chargedAtomTypeIndex, const char* typeName, DuMM::AtomClassIndex atomClassIx) { static const char* MethodName = "defineIncompleteChargedAtomType"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); // Check for nonsense arguments. SimTK_APIARGCHECK1_ALWAYS(chargedAtomTypeIndex.isValid(), mm.ApiClassName, MethodName, "charged atom type index %d invalid: must be nonnegative", (int) chargedAtomTypeIndex); SimTK_APIARGCHECK1_ALWAYS(atomClassIx.isValid(), mm.ApiClassName, MethodName, "atom class index %d invalid: must be nonnegative", (int) atomClassIx); // partialCharge is a signed quantity // Make sure the referenced atom class has already been defined. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(atomClassIx), mm.ApiClassName, MethodName, "atom class %d is undefined", (int) atomClassIx); // Make sure there is a slot available for the new chargedAtomType. if (chargedAtomTypeIndex >= (int)mm.chargedAtomTypes.size()) mm.chargedAtomTypes.resize(chargedAtomTypeIndex+1); // Check that this slot is not already in use. SimTK_APIARGCHECK2_ALWAYS(!mm.chargedAtomTypes[chargedAtomTypeIndex].isValid(), mm.ApiClassName, MethodName, "charged atom type index %d is already in use for '%s'", (int) chargedAtomTypeIndex, mm.chargedAtomTypes[chargedAtomTypeIndex].name.c_str()); mm.insertNewChargedAtomType(ChargedAtomType(chargedAtomTypeIndex, typeName, atomClassIx, NaN)); } bool DuMMForceFieldSubsystem::hasAtomClass(DuMM::AtomClassIndex atomClassIndex) const { return getRep().hasAtomClass(atomClassIndex); } bool DuMMForceFieldSubsystem::hasAtomClass(const String& atomClassName) const { return getRep().hasAtomClass(atomClassName); } DuMM::AtomClassIndex DuMMForceFieldSubsystem::getAtomClassIndex(const String& atomClassName) const { return getRep().getAtomClassIndex(atomClassName); } DuMM::AtomClassIndex DuMMForceFieldSubsystem::getNextUnusedAtomClassIndex() const { return getRep().getNextUnusedAtomClassIndex(); } bool DuMMForceFieldSubsystem::hasChargedAtomType(DuMM::ChargedAtomTypeIndex chargedAtomTypeIndex) const { return getRep().hasChargedAtomType(chargedAtomTypeIndex); } bool DuMMForceFieldSubsystem::hasChargedAtomType(const String& chargedTypeName) const { return getRep().hasChargedAtomType(chargedTypeName); } DuMM::ChargedAtomTypeIndex DuMMForceFieldSubsystem::getChargedAtomTypeIndex(const String& chargedTypeName) const { return getRep().getChargedAtomTypeIndex(chargedTypeName); } DuMM::ChargedAtomTypeIndex DuMMForceFieldSubsystem::getNextUnusedChargedAtomTypeIndex() const { return getRep().getNextUnusedChargedAtomTypeIndex(); } void DuMMForceFieldSubsystem::setChargedAtomTypeCharge(DuMM::ChargedAtomTypeIndex chargedAtomTypeIndex, Real charge) { static const char* MethodName = "setChargedAtomTypeCharge"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); // Check for nonsense arguments. SimTK_APIARGCHECK1_ALWAYS(chargedAtomTypeIndex.isValid(), mm.ApiClassName, MethodName, "charged atom type index %d invalid: must be nonnegative", (int) chargedAtomTypeIndex); ChargedAtomType& chargedAtomType = mm.chargedAtomTypes[chargedAtomTypeIndex]; chargedAtomType.partialCharge = charge; } void DuMMForceFieldSubsystem::defineBondStretch (DuMM::AtomClassIndex class1, DuMM::AtomClassIndex class2, Real stiffnessInKJPerNmSq, Real nominalLengthInNm) { static const char* MethodName = "defineBondStretch"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); // Watch for nonsense arguments. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(class1), mm.ApiClassName, MethodName, "class1=%d which is not a valid atom class Index", (int) class1); SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(class2), mm.ApiClassName, MethodName, "class2=%d which is not a valid atom class Index", (int) class2); SimTK_APIARGCHECK1_ALWAYS(stiffnessInKJPerNmSq >= 0, mm.ApiClassName, MethodName, "stiffness %g is not valid: must be nonnegative", stiffnessInKJPerNmSq); SimTK_APIARGCHECK1_ALWAYS(nominalLengthInNm >= 0, mm.ApiClassName, MethodName, "nominal length %g is not valid: must be nonnegative", nominalLengthInNm); // We canonicalize the key so that the atom class pair has the // lower class Index first. const AtomClassIndexPair key(class1,class2,true); // Attempt to create a new bond stretch entry containing no valid // terms. If there was already an entry it will be returned instead // and no insertion is performed. std::pair<std::map<AtomClassIndexPair,BondStretch>::iterator, bool> ret = mm.bondStretch.insert(std::pair<AtomClassIndexPair,BondStretch> (key, BondStretch(key))); BondStretch& bondStretchEntry = ret.first->second; if (bondStretchEntry.hasBuiltinTerm()) { SimTK_APIARGCHECK2_ALWAYS( bondStretchEntry.k==stiffnessInKJPerNmSq && bondStretchEntry.d0==nominalLengthInNm, mm.ApiClassName, MethodName, "There was already a different built-in bond stretch term for atom class pair (%d,%d); only one is allowed." "\nUse a CustomBondStretch term if you need another term for the same atom class pair.", (int)key[0], (int)key[1]); } else bondStretchEntry.setBuiltinTerm(stiffnessInKJPerNmSq,nominalLengthInNm); } void DuMMForceFieldSubsystem::defineCustomBondStretch (DuMM::AtomClassIndex class1, DuMM::AtomClassIndex class2, DuMM::CustomBondStretch* customBondStretch) { static const char* MethodName = "defineCustomBondStretch"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); // Watch for nonsense arguments. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(class1), mm.ApiClassName, MethodName, "class1=%d which is not a valid atom class Index", (int) class1); SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(class2), mm.ApiClassName, MethodName, "class2=%d which is not a valid atom class Index", (int) class2); SimTK_APIARGCHECK_ALWAYS(customBondStretch, mm.ApiClassName, MethodName, "CustomBondStretch pointer was null"); // We canonicalize the key so that the atom class pair has the // lower class Index first. const AtomClassIndexPair key(class1,class2,true); // Attempt to create a new bond stretch entry containing no valid // terms. If there was already an entry it will be returned instead // and no insertion is performed. std::pair<std::map<AtomClassIndexPair,BondStretch>::iterator, bool> ret = mm.bondStretch.insert(std::pair<AtomClassIndexPair,BondStretch> (key, BondStretch(key))); BondStretch& bondStretchEntry = ret.first->second; bondStretchEntry.addCustomTerm(customBondStretch); } void DuMMForceFieldSubsystem::defineBondBend (DuMM::AtomClassIndex class1, DuMM::AtomClassIndex class2, DuMM::AtomClassIndex class3, Real stiffnessInKJPerRadSq, Real nominalAngleInDeg) { static const char* MethodName = "defineBondBend"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); // Watch for nonsense arguments. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(class1), mm.ApiClassName, MethodName, "class1=%d which is not a valid atom class Index", (int) class1); SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(class2), mm.ApiClassName, MethodName, "class2=%d which is not a valid atom class Index", (int) class2); SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(class3), mm.ApiClassName, MethodName, "class3=%d which is not a valid atom class Index", (int) class3); SimTK_APIARGCHECK1_ALWAYS(stiffnessInKJPerRadSq >= 0, mm.ApiClassName, MethodName, "stiffness %g is not valid: must be nonnegative", stiffnessInKJPerRadSq); SimTK_APIARGCHECK1_ALWAYS(0 <= nominalAngleInDeg && nominalAngleInDeg <= 180, mm.ApiClassName, MethodName, "nominal angle %g is not valid: must be between 0 and 180 degrees, inclusive", nominalAngleInDeg); // We canonicalize the key so that the first classIndex is no larger than the third. const AtomClassIndexTriple key(class1,class2,class3,true); // Attempt to create a new bond bend entry containing no valid // terms. If there was already an entry it will be returned instead // and no insertion is performed. std::pair<std::map<AtomClassIndexTriple,BondBend>::iterator, bool> ret = mm.bondBend.insert(std::pair<AtomClassIndexTriple,BondBend> (key, BondBend(key))); BondBend& bondBendEntry = ret.first->second; if (bondBendEntry.hasBuiltinTerm()) { SimTK_APIARGCHECK3_ALWAYS( bondBendEntry.k==stiffnessInKJPerRadSq && bondBendEntry.theta0==nominalAngleInDeg*DuMM::Deg2Rad, mm.ApiClassName, MethodName, "There was already a different built-in bond bend term for atom class triple (%d,%d,%d); only one is allowed." "\nUse a CustomBondBend term if you need another term for the same atom class triple.", (int)key[0], (int)key[1], (int)key[2]); } else bondBendEntry.setBuiltinTerm(stiffnessInKJPerRadSq,nominalAngleInDeg); } void DuMMForceFieldSubsystem::defineCustomBondBend (DuMM::AtomClassIndex class1, DuMM::AtomClassIndex class2, DuMM::AtomClassIndex class3, DuMM::CustomBondBend* customBondBend) { static const char* MethodName = "defineCustomBondBend"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); // Watch for nonsense arguments. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(class1), mm.ApiClassName, MethodName, "class1=%d which is not a valid atom class Index", (int) class1); SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(class2), mm.ApiClassName, MethodName, "class2=%d which is not a valid atom class Index", (int) class2); SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(class3), mm.ApiClassName, MethodName, "class3=%d which is not a valid atom class Index", (int) class3); SimTK_APIARGCHECK_ALWAYS(customBondBend, mm.ApiClassName, MethodName, "CustomBondBend pointer was null"); // We canonicalize the key so that the first classIndex is no larger than the third. const AtomClassIndexTriple key(class1,class2,class3,true); // Attempt to create a new bond bend entry containing no valid // terms. If there was already an entry it will be returned instead // and no insertion is performed. std::pair<std::map<AtomClassIndexTriple,BondBend>::iterator, bool> ret = mm.bondBend.insert(std::pair<AtomClassIndexTriple,BondBend> (key, BondBend(key))); BondBend& bondBendEntry = ret.first->second; bondBendEntry.addCustomTerm(customBondBend); } // // This is a utility method that checks for invalid inputs to the defineBondTorsion() and // defineAmberImproperTorsion() functions, and then inserts the built in torsion terms // if they are legitimate. // void DuMMForceFieldSubsystemRep::defineAnyTorsion (DuMM::AtomClassIndex class1, DuMM::AtomClassIndex class2, DuMM::AtomClassIndex class3, DuMM::AtomClassIndex class4, bool shouldCanonicalizeClassOrder, int periodicity1, Real amp1InKJ, Real phase1InDegrees, int periodicity2, Real amp2InKJ, Real phase2InDegrees, int periodicity3, Real amp3InKJ, Real phase3InDegrees, std::map<AtomClassIndexQuad,BondTorsion>& torsionMap, const char* CallingMethodName) const { // Watch for nonsense arguments. SimTK_APIARGCHECK1_ALWAYS(isValidAtomClass(class1), ApiClassName, CallingMethodName, "class1=%d which is not a valid atom class Index", (int) class1); SimTK_APIARGCHECK1_ALWAYS(isValidAtomClass(class2), ApiClassName, CallingMethodName, "class2=%d which is not a valid atom class Index", (int) class2); SimTK_APIARGCHECK1_ALWAYS(isValidAtomClass(class3), ApiClassName, CallingMethodName, "class3=%d which is not a valid atom class Index", (int) class3); SimTK_APIARGCHECK1_ALWAYS(isValidAtomClass(class4), ApiClassName, CallingMethodName, "class4=%d which is not a valid atom class Index", (int) class4); SimTK_APIARGCHECK_ALWAYS(periodicity1!=-1 || periodicity2!=-1 || periodicity3!=-1, ApiClassName, CallingMethodName, "must be at least one torsion term supplied"); if (periodicity1 != -1) { // No nonsense. SimTK_APIARGCHECK1_ALWAYS(1 <= periodicity1 && periodicity1 <= 6, ApiClassName, CallingMethodName, "periodicity1(%d) is invalid: we require 1 <= periodicity <= 6", periodicity1); SimTK_APIARGCHECK1_ALWAYS(amp1InKJ >= 0, ApiClassName, CallingMethodName, "amplitude1(%g) is not valid: must be nonnegative", amp1InKJ); //scf changed 0 to -180 to allow NAST right handed helices SimTK_APIARGCHECK1_ALWAYS(-180 <= phase1InDegrees && phase1InDegrees <= 180, ApiClassName, CallingMethodName, "phaseAngle1(%g) is not valid: must be between -180 and 180 degrees, inclusive", phase1InDegrees); // No repeats. SimTK_APIARGCHECK1_ALWAYS((periodicity2 != periodicity1) && (periodicity3 != periodicity1), ApiClassName, CallingMethodName, "only one term with a given periodicity may be specified (periodicity %d was repeated)", periodicity1); } if (periodicity2 != -1) { // No nonsense. SimTK_APIARGCHECK1_ALWAYS(1 <= periodicity2 && periodicity2 <= 6, ApiClassName, CallingMethodName, "periodicity2(%d) is invalid: we require 1 <= periodicity <= 6", periodicity2); SimTK_APIARGCHECK1_ALWAYS(amp2InKJ >= 0, ApiClassName, CallingMethodName, "amplitude2(%g) is not valid: must be nonnegative", amp2InKJ); SimTK_APIARGCHECK1_ALWAYS(0 <= phase2InDegrees && phase2InDegrees <= 180, ApiClassName, CallingMethodName, "phaseAngle2(%g) is not valid: must be between 0 and 180 degrees, inclusive", phase2InDegrees); // No repeats. SimTK_APIARGCHECK1_ALWAYS(periodicity3 != periodicity2, ApiClassName, CallingMethodName, "only one term with a given periodicity may be specified (periodicity %d was repeated)", periodicity2); } if (periodicity3 != -1) { // No nonsense. SimTK_APIARGCHECK1_ALWAYS(1 <= periodicity3 && periodicity3 <= 6, ApiClassName, CallingMethodName, "periodicity3(%d) is invalid: we require 1 <= periodicity <= 6", periodicity3); SimTK_APIARGCHECK1_ALWAYS(amp3InKJ >= 0, ApiClassName, CallingMethodName, "amplitude3(%g) is not valid: must be nonnegative", amp3InKJ); SimTK_APIARGCHECK1_ALWAYS(0 <= phase3InDegrees && phase3InDegrees <= 180, ApiClassName, CallingMethodName, "phaseAngle3(%g) is not valid: must be between 0 and 180 degrees, inclusive", phase3InDegrees); // (we've already checked for any possible repeats) } // Canonicalize atom class quad by reversing order if necessary so that the // first class Index is numerically no larger than the fourth. Amber improper // torsions should not be canonicalized because order matters. const AtomClassIndexQuad key(class1, class2, class3, class4, shouldCanonicalizeClassOrder); // Attempt to create a new bond torsion entry containing no valid // terms. If there was already an entry it will be returned instead // and no insertion is performed. std::pair<std::map<AtomClassIndexQuad,BondTorsion>::iterator, bool> ret = torsionMap.insert(std::pair<AtomClassIndexQuad,BondTorsion> (key, BondTorsion(key))); BondTorsion& bondTorsionEntry = ret.first->second; // A new entry or one that just had a custom term in it won't have a built in // term so we can load it up and we're done. if (!bondTorsionEntry.hasBuiltinTerm()) { if (periodicity1 != -1) bondTorsionEntry.addBuiltinTerm(TorsionTerm(periodicity1, amp1InKJ, phase1InDegrees)); if (periodicity2 != -1) bondTorsionEntry.addBuiltinTerm(TorsionTerm(periodicity2, amp2InKJ, phase2InDegrees)); if (periodicity3 != -1) bondTorsionEntry.addBuiltinTerm(TorsionTerm(periodicity3, amp3InKJ, phase3InDegrees)); return; } // If we get here we have discovered that there is already a built in torsion // term present for this atom class quad. We can still insert new terms, and we'll // allow duplicates if they are identical. if (periodicity1 != -1) { const TorsionTerm& term1 = bondTorsionEntry.getTermWithPeriod(periodicity1); if (term1.isValid()) { SimTK_APIARGCHECK5_ALWAYS(term1.amplitude==amp1InKJ && term1.theta0==phase1InDegrees, ApiClassName, CallingMethodName, "atom class quad (%d,%d,%d,%d) already had a different term with periodicity %d", (int)class1,(int)class2,(int)class3,(int)class4,periodicity1); } else bondTorsionEntry.addBuiltinTerm(TorsionTerm(periodicity1, amp1InKJ, phase1InDegrees)); } if (periodicity2 != -1) { const TorsionTerm& term2 = bondTorsionEntry.getTermWithPeriod(periodicity2); if (term2.isValid()) { SimTK_APIARGCHECK5_ALWAYS(term2.amplitude==amp2InKJ && term2.theta0==phase2InDegrees, ApiClassName, CallingMethodName, "atom class quad (%d,%d,%d,%d) already had a different term with periodicity %d", (int)class1,(int)class2,(int)class3,(int)class4,periodicity2); } else bondTorsionEntry.addBuiltinTerm(TorsionTerm(periodicity2, amp2InKJ, phase2InDegrees)); } if (periodicity3 != -1) { const TorsionTerm& term3 = bondTorsionEntry.getTermWithPeriod(periodicity3); if (term3.isValid()) { SimTK_APIARGCHECK5_ALWAYS(term3.amplitude==amp3InKJ && term3.theta0==phase3InDegrees, ApiClassName, CallingMethodName, "atom class quad (%d,%d,%d,%d) already had a different term with periodicity %d", (int)class1,(int)class2,(int)class3,(int)class4,periodicity3); } else bondTorsionEntry.addBuiltinTerm(TorsionTerm(periodicity3, amp3InKJ, phase3InDegrees)); } } // // We allow up to 3 terms in a single torsion function, with three different // periodicities. If any of these are unused, set the corresponding periodicity // to -1. // void DuMMForceFieldSubsystem::defineBondTorsion (DuMM::AtomClassIndex class1, DuMM::AtomClassIndex class2, DuMM::AtomClassIndex class3, DuMM::AtomClassIndex class4, int periodicity1, Real amp1InKJ, Real phase1InDegrees, int periodicity2, Real amp2InKJ, Real phase2InDegrees, int periodicity3, Real amp3InKJ, Real phase3InDegrees) { static const char* MethodName = "defineBondTorsion"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); mm.defineAnyTorsion(class1, class2, class3, class4, true, // canonicalize periodicity1, amp1InKJ, phase1InDegrees, periodicity2, amp2InKJ, phase2InDegrees, periodicity3, amp3InKJ, phase3InDegrees, mm.bondTorsion, MethodName); } void DuMMForceFieldSubsystem::defineCustomBondTorsion (DuMM::AtomClassIndex class1, DuMM::AtomClassIndex class2, DuMM::AtomClassIndex class3, DuMM::AtomClassIndex class4, DuMM::CustomBondTorsion* customBondTorsion) { static const char* MethodName = "defineCustomBondTorsion"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); // Watch for nonsense arguments. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(class1), mm.ApiClassName, MethodName, "class1=%d which is not a valid atom class Index", (int) class1); SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(class2), mm.ApiClassName, MethodName, "class2=%d which is not a valid atom class Index", (int) class2); SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(class3), mm.ApiClassName, MethodName, "class3=%d which is not a valid atom class Index", (int) class3); SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtomClass(class3), mm.ApiClassName, MethodName, "class4=%d which is not a valid atom class Index", (int) class4); SimTK_APIARGCHECK_ALWAYS(customBondTorsion, mm.ApiClassName, MethodName, "CustomBondTorsion pointer was null"); // Canonicalize atom class quad by reversing order if necessary so that the // first class Index is numerically no larger than the fourth. const AtomClassIndexQuad key(class1, class2, class3, class4, true); // Attempt to create a new bond torsion entry containing no valid // terms. If there was already an entry it will be returned instead // and no insertion is performed. std::pair<std::map<AtomClassIndexQuad,BondTorsion>::iterator, bool> ret = mm.bondTorsion.insert(std::pair<AtomClassIndexQuad,BondTorsion> (key, BondTorsion(key))); BondTorsion& bondTorsionEntry = ret.first->second; bondTorsionEntry.addCustomTerm(customBondTorsion); } // Convenient signature for a bond torsion with only one term. void DuMMForceFieldSubsystem::defineBondTorsion (DuMM::AtomClassIndex class1, DuMM::AtomClassIndex class2, DuMM::AtomClassIndex class3, DuMM::AtomClassIndex class4, int periodicity1, Real amp1InKJ, Real phase1InDegrees) { defineBondTorsion(class1, class2, class3, class4, periodicity1,amp1InKJ,phase1InDegrees, -1,0.,0., -1,0.,0.); } // Convenient signature for a bond torsion with two terms. void DuMMForceFieldSubsystem::defineBondTorsion (DuMM::AtomClassIndex class1, DuMM::AtomClassIndex class2, DuMM::AtomClassIndex class3, DuMM::AtomClassIndex class4, int periodicity1, Real amp1InKJ, Real phase1InDegrees, int periodicity2, Real amp2InKJ, Real phase2InDegrees) { defineBondTorsion(class1, class2, class3, class4, periodicity1,amp1InKJ,phase1InDegrees, periodicity2,amp2InKJ,phase2InDegrees, -1,0.,0.); } // // This function is based on the defineBondTorsion function. // As with the normal bond torsions, we allow up to 3 terms in a single torsion function, // with three different periodicities. If any of these are unused, set the corresponding // periodicity to -1. // void DuMMForceFieldSubsystem::defineAmberImproperTorsion (DuMM::AtomClassIndex class1, DuMM::AtomClassIndex class2, DuMM::AtomClassIndex class3, DuMM::AtomClassIndex class4, int periodicity1, Real amp1InKJ, Real phase1InDegrees, int periodicity2, Real amp2InKJ, Real phase2InDegrees, int periodicity3, Real amp3InKJ, Real phase3InDegrees) { static const char* MethodName = "defineAmberImproperTorsion"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); mm.defineAnyTorsion(class1, class2, class3, class4, false, // don't canonicalize periodicity1, amp1InKJ, phase1InDegrees, periodicity2, amp2InKJ, phase2InDegrees, periodicity3, amp3InKJ, phase3InDegrees, mm.amberImproperTorsion, MethodName); } // Convenient signature for an amber improper torsion with only one term. void DuMMForceFieldSubsystem::defineAmberImproperTorsion (DuMM::AtomClassIndex class1, DuMM::AtomClassIndex class2, DuMM::AtomClassIndex class3, DuMM::AtomClassIndex class4, int periodicity1, Real amp1InKJ, Real phase1InDegrees) { defineAmberImproperTorsion(class1, class2, class3, class4, periodicity1,amp1InKJ,phase1InDegrees, -1,0.,0., -1,0.,0.); } // Convenient signature for an amber improper torsion with two terms. void DuMMForceFieldSubsystem::defineAmberImproperTorsion (DuMM::AtomClassIndex class1, DuMM::AtomClassIndex class2, DuMM::AtomClassIndex class3, DuMM::AtomClassIndex class4, int periodicity1, Real amp1InKJ, Real phase1InDegrees, int periodicity2, Real amp2InKJ, Real phase2InDegrees) { defineAmberImproperTorsion(class1, class2, class3, class4, periodicity1,amp1InKJ,phase1InDegrees, periodicity2,amp2InKJ,phase2InDegrees, -1,0.,0.); } void DuMMForceFieldSubsystem::setVdwMixingRule(VdwMixingRule rule) { static const char* MethodName = "setVdwMixingRule"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); mm.vdwMixingRule = rule; } DuMMForceFieldSubsystem::VdwMixingRule DuMMForceFieldSubsystem::getVdwMixingRule() const { static const char* MethodName = "getVdwMixingRule"; const DuMMForceFieldSubsystemRep& mm = getRep(); return mm.vdwMixingRule; } const char* DuMMForceFieldSubsystem::getVdwMixingRuleName(VdwMixingRule rule) const { static const char* MethodName = "getVdwMixingRuleName"; switch(rule) { case WaldmanHagler: return "Waldman-Hagler"; case HalgrenHHG: return "Halgren-HHG"; case Jorgensen: return "Jorgensen"; case LorentzBerthelot: return "Lorentz-Berthelot"; case Kong: return "Kong"; default: SimTK_APIARGCHECK1_ALWAYS(false, "DuMMForceFieldSubsystem", MethodName, "Unknown van der Waals mixing rule %d", (int)rule); }; } void DuMMForceFieldSubsystem::setVdw12ScaleFactor(Real fac) { static const char* MethodName = "setVdw12ScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac && fac <= 1, mm.ApiClassName, MethodName, "van der Waals energy scale factor (%g) for 1-2 bonded atoms was invalid: must be between 0 and 1, inclusive", fac); mm.vdwScale12=fac; } void DuMMForceFieldSubsystem::setVdw13ScaleFactor(Real fac) { static const char* MethodName = "setVdw13ScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac && fac <= 1, mm.ApiClassName, MethodName, "van der Waals energy scale factor (%g) for 1-3 bonded atoms was invalid: must be between 0 and 1, inclusive", fac); mm.vdwScale13=fac; } void DuMMForceFieldSubsystem::setVdw14ScaleFactor(Real fac) { static const char* MethodName = "setVdw14ScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac && fac <= 1, mm.ApiClassName, MethodName, "van der Waals energy scale factor (%g) for 1-4 bonded atoms was invalid: must be between 0 and 1, inclusive", fac); mm.vdwScale14=fac; } void DuMMForceFieldSubsystem::setVdw15ScaleFactor(Real fac) { static const char* MethodName = "setVdw15ScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac && fac <= 1, mm.ApiClassName, MethodName, "van der Waals energy scale factor (%g) for 1-5 bonded atoms was invalid: must be between 0 and 1, inclusive", fac); mm.vdwScale15=fac; } void DuMMForceFieldSubsystem::setCoulomb12ScaleFactor(Real fac) { static const char* MethodName = "setCoulomb12ScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac && fac <= 1, mm.ApiClassName, MethodName, "Coulomb scale factor (%g) for 1-2 bonded atoms was invalid: must be between 0 and 1, inclusive", fac); mm.coulombScale12=fac; } void DuMMForceFieldSubsystem::setCoulomb13ScaleFactor(Real fac) { static const char* MethodName = "setCoulomb13ScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac && fac <= 1, mm.ApiClassName, MethodName, "Coulomb scale factor (%g) for 1-3 bonded atoms was invalid: must be between 0 and 1, inclusive", fac); mm.coulombScale13=fac; } void DuMMForceFieldSubsystem::setCoulomb14ScaleFactor(Real fac) { static const char* MethodName = "setCoulomb14ScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac && fac <= 1, mm.ApiClassName, MethodName, "Coulomb scale factor (%g) for 1-4 bonded atoms was invalid: must be between 0 and 1, inclusive", fac); mm.coulombScale14=fac; } void DuMMForceFieldSubsystem::setCoulomb15ScaleFactor(Real fac) { static const char* MethodName = "setCoulomb15ScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac && fac <= 1, mm.ApiClassName, MethodName, "Coulomb scale factor (%g) for 1-5 bonded atoms was invalid: must be between 0 and 1, inclusive", fac); mm.coulombScale15=fac; } void DuMMForceFieldSubsystem::setVdwGlobalScaleFactor(Real fac) { static const char* MethodName = "setVdwScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac, mm.ApiClassName, MethodName, "Global van der Waals scale factor (%g) was invalid: must be nonnegative", fac); mm.vdwGlobalScaleFactor=fac; } void DuMMForceFieldSubsystem::setCoulombGlobalScaleFactor(Real fac) { static const char* MethodName = "setCoulombScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac, mm.ApiClassName, MethodName, "Global Coulomb scale factor (%g) was invalid: must be nonnegative", fac); mm.coulombGlobalScaleFactor=fac; } void DuMMForceFieldSubsystem::setBondStretchGlobalScaleFactor(Real fac) { static const char* MethodName = "setBondStretchScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac, mm.ApiClassName, MethodName, "Global bond stretch scale factor (%g) was invalid: must be nonnegative", fac); mm.bondStretchGlobalScaleFactor=fac; } void DuMMForceFieldSubsystem::setBondBendGlobalScaleFactor(Real fac) { static const char* MethodName = "setBondBendScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac, mm.ApiClassName, MethodName, "Global bond bend scale factor (%g) was invalid: must be nonnegative", fac); mm.bondBendGlobalScaleFactor=fac; } void DuMMForceFieldSubsystem::setBondTorsionGlobalScaleFactor(Real fac) { static const char* MethodName = "setBondTorsionScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac, mm.ApiClassName, MethodName, "Global bond torsion scale factor (%g) was invalid: must be nonnegative", fac); mm.bondTorsionGlobalScaleFactor=fac; } void DuMMForceFieldSubsystem::setAmberImproperTorsionGlobalScaleFactor(Real fac) { static const char* MethodName = "setAmberImproperTorsionScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac, mm.ApiClassName, MethodName, "Global amber improper torsion scale factor (%g) was invalid: must be nonnegative", fac); mm.amberImproperTorsionGlobalScaleFactor=fac; } void DuMMForceFieldSubsystem::setCustomBondStretchGlobalScaleFactor(Real fac) { static const char* MethodName = "setCustomBondStretchScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac, mm.ApiClassName, MethodName, "Global custom bond stretch scale factor (%g) was invalid: must be nonnegative", fac); mm.customBondStretchGlobalScaleFactor=fac; } void DuMMForceFieldSubsystem::setCustomBondBendGlobalScaleFactor(Real fac) { static const char* MethodName = "setCustomBondBendScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac, mm.ApiClassName, MethodName, "Global custom bond bend scale factor (%g) was invalid: must be nonnegative", fac); mm.customBondBendGlobalScaleFactor=fac; } void DuMMForceFieldSubsystem::setCustomBondTorsionGlobalScaleFactor(Real fac) { static const char* MethodName = "setCustomBondTorsionScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac, mm.ApiClassName, MethodName, "Global custom bond torsion scale factor (%g) was invalid: must be nonnegative", fac); mm.customBondTorsionGlobalScaleFactor=fac; } void DuMMForceFieldSubsystem::setSolventDielectric(Real dielectric) { static const char* MethodName = "setSolventDielectric"; DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(dielectric > 0, mm.ApiClassName, MethodName, "Solvent dielectric (%g) was invalid: must be greater than zero", dielectric); invalidateSubsystemTopologyCache(); mm.gbsaSolventDielectric = dielectric; } void DuMMForceFieldSubsystem::setSoluteDielectric(Real dielectric) { static const char* MethodName = "setSolutetDielectric"; DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(dielectric > 0, mm.ApiClassName, MethodName, "Solute dielectric (%g) was invalid: must be greater than zero", dielectric); invalidateSubsystemTopologyCache(); mm.gbsaSoluteDielectric = dielectric; } Real DuMMForceFieldSubsystem::getSolventDielectric() const { return getRep().gbsaSolventDielectric; } Real DuMMForceFieldSubsystem::getSoluteDielectric() const { return getRep().gbsaSoluteDielectric; } void DuMMForceFieldSubsystem::setGbsaIncludeAceApproximation(bool doInclude) { static const char* MethodName = "setGbsaIncludeAceApproximation"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); mm.gbsaIncludeAceApproximation=doInclude; } void DuMMForceFieldSubsystem::setGbsaGlobalScaleFactor(Real fac) { static const char* MethodName = "setGbsaGlobalScaleFactor"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(0 <= fac, mm.ApiClassName, MethodName, "Global generalized Born scale factor (%g) was invalid: must be nonnegative", fac); mm.gbsaGlobalScaleFactor=fac; } void DuMMForceFieldSubsystem:: clearIncludedNonbondAtomList() { invalidateSubsystemTopologyCache(); InclusionListSpec& inclList = updRep().inclList; inclList.includedNonbondAtoms.clear(); inclList.includedNonbondBodies.clear(); inclList.useDefaultNonbondList = false; // i.e., now there is nothing } void DuMMForceFieldSubsystem:: clearIncludedBondList() { invalidateSubsystemTopologyCache(); InclusionListSpec& inclList = updRep().inclList; inclList.atomsWhoseBondsAreIncluded.clear(); inclList.atomPairsWhoseConnectingBondsAreIncluded.clear(); inclList.bodiesWhoseBondsAreIncluded.clear(); inclList.bodyPairsWhoseConnectingBondsAreIncluded.clear(); inclList.useDefaultBondList = false; // i.e., now there is nothing } void DuMMForceFieldSubsystem:: resetIncludedNonbondAtomListToDefault() { clearIncludedNonbondAtomList(); InclusionListSpec& inclList = updRep().inclList; inclList.useDefaultNonbondList = true; } void DuMMForceFieldSubsystem:: resetIncludedBondListToDefault() { clearIncludedBondList(); InclusionListSpec& inclList = updRep().inclList; inclList.useDefaultBondList = true; } void DuMMForceFieldSubsystem:: includeNonbondAtom(DuMM::AtomIndex atomIx) { invalidateSubsystemTopologyCache(); InclusionListSpec& inclList = updRep().inclList; inclList.useDefaultNonbondList = false; inclList.includedNonbondAtoms.insert(atomIx); // ignores duplicates } void DuMMForceFieldSubsystem:: includeAllNonbondAtomsForOneBody(MobilizedBodyIndex mobodIx) { invalidateSubsystemTopologyCache(); InclusionListSpec& inclList = updRep().inclList; inclList.useDefaultNonbondList = false; inclList.includedNonbondBodies.insert(mobodIx); // ignores duplicates } void DuMMForceFieldSubsystem:: includeAllInterbodyBondsForOneAtom(DuMM::AtomIndex ax) { invalidateSubsystemTopologyCache(); InclusionListSpec& inclList = updRep().inclList; inclList.useDefaultBondList = false; inclList.atomsWhoseBondsAreIncluded.insert(ax); // ignores duplicates } void DuMMForceFieldSubsystem:: includeAllInterbodyBondsWithBothAtoms(DuMM::AtomIndex ax1, DuMM::AtomIndex ax2) { invalidateSubsystemTopologyCache(); InclusionListSpec& inclList = updRep().inclList; inclList.useDefaultBondList = false; inclList.atomPairsWhoseConnectingBondsAreIncluded.insert (AtomIndexPair(ax1,ax2,true)); // canonicalize order; ignore dups } void DuMMForceFieldSubsystem:: includeAllInterbodyBondsWithBothAtoms(DuMM::BondIndex bond) { includeAllInterbodyBondsWithBothAtoms(getBondAtom(bond,0), getBondAtom(bond,1)); } void DuMMForceFieldSubsystem:: includeAllInterbodyBondsForOneBody(MobilizedBodyIndex mobod) { invalidateSubsystemTopologyCache(); InclusionListSpec& inclList = updRep().inclList; inclList.useDefaultBondList = false; inclList.bodiesWhoseBondsAreIncluded.insert(mobod); // ignores dups } void DuMMForceFieldSubsystem:: includeAllInterbodyBondsBetweenTwoBodies (MobilizedBodyIndex mobod1, MobilizedBodyIndex mobod2) { invalidateSubsystemTopologyCache(); InclusionListSpec& inclList = updRep().inclList; inclList.useDefaultBondList = false; inclList.bodyPairsWhoseConnectingBondsAreIncluded .insert(MobodIndexPair(mobod1,mobod2,true)); // canonicalize order } const double DuMMForceFieldSubsystem::getTotalIncludedCharge () { double totalCharge = 0; DuMM::IncludedAtomIndex iax(0); for (int i = 0 ; i < getNumIncludedAtoms (); i++) { totalCharge += getPartialCharge(iax); iax++; } return totalCharge; } const double DuMMForceFieldSubsystem::getPartialCharge (DuMM::AtomIndex aid) { const SimTK::DuMM::ChargedAtomTypeIndex & iax = getRep().atoms[aid].chargedAtomTypeIndex; const ChargedAtomType& myChargedAtomType = getRep().chargedAtomTypes[iax]; return myChargedAtomType.partialCharge; } const double DuMMForceFieldSubsystem::getPartialCharge (DuMM::IncludedAtomIndex iax) { const IncludedAtom& myIncludedAtom = getRep().getIncludedAtom(iax); const ChargedAtomType& myChargedAtomType = getRep().chargedAtomTypes[myIncludedAtom.chargedAtomTypeIndex]; return myChargedAtomType.partialCharge; } const std::string DuMMForceFieldSubsystem::getChargedAtomName (DuMM::IncludedAtomIndex iax) { const IncludedAtom& myIncludedAtom = getRep().getIncludedAtom(iax); const ChargedAtomType& myChargedAtomType = getRep().chargedAtomTypes[myIncludedAtom.chargedAtomTypeIndex]; return myChargedAtomType.name ; } int DuMMForceFieldSubsystem:: getNumIncludedAtoms() const { static const char* MethodName = "getNumIncludedAtoms"; SimTK_STAGECHECK_TOPOLOGY_REALIZED_ALWAYS(subsystemTopologyHasBeenRealized(), MethodName, "Subsystem", "DuMMForceFieldSubsystem"); return getRep().getNumIncludedAtoms(); } DuMM::AtomIndex DuMMForceFieldSubsystem:: getAtomIndexOfIncludedAtom (DuMM::IncludedAtomIndex incAtomIndex) const { static const char* MethodName = "getAtomIndexOfIncludedAtom"; // Don't check in Release mode since this might get called a lot and // presumably we just checked in getNumIncludedAtoms(). SimTK_STAGECHECK_TOPOLOGY_REALIZED(subsystemTopologyHasBeenRealized(), MethodName, "Subsystem", "DuMMForceFieldSubsystem"); return getRep().getAtomIndexOfIncludedAtom(incAtomIndex); } int DuMMForceFieldSubsystem:: getNumNonbondAtoms() const { static const char* MethodName = "getNumNonbondAtoms"; SimTK_STAGECHECK_TOPOLOGY_REALIZED_ALWAYS(subsystemTopologyHasBeenRealized(), MethodName, "Subsystem", "DuMMForceFieldSubsystem"); return getRep().getNumNonbondAtoms(); } DuMM::IncludedAtomIndex DuMMForceFieldSubsystem:: getIncludedAtomIndexOfNonbondAtom (DuMM::NonbondAtomIndex nbAtomIndex) const { static const char* MethodName = "getIncludedAtomIndexOfNonbondAtom"; // Don't check in Release mode since this might get called a lot and // presumably we just checked in getNumNonbondAtoms(). SimTK_STAGECHECK_TOPOLOGY_REALIZED(subsystemTopologyHasBeenRealized(), MethodName, "Subsystem", "DuMMForceFieldSubsystem"); return getRep().getIncludedAtomIndexOfNonbondAtom(nbAtomIndex); } Real DuMMForceFieldSubsystem::getVdwGlobalScaleFactor() const {return getRep().vdwGlobalScaleFactor;} Real DuMMForceFieldSubsystem::getCoulombGlobalScaleFactor() const {return getRep().coulombGlobalScaleFactor;} Real DuMMForceFieldSubsystem::getGbsaGlobalScaleFactor() const {return getRep().gbsaGlobalScaleFactor;} Real DuMMForceFieldSubsystem::getBondStretchGlobalScaleFactor() const {return getRep().bondStretchGlobalScaleFactor;} Real DuMMForceFieldSubsystem::getBondBendGlobalScaleFactor() const {return getRep().bondBendGlobalScaleFactor;} Real DuMMForceFieldSubsystem::getBondTorsionGlobalScaleFactor() const {return getRep().bondTorsionGlobalScaleFactor;} Real DuMMForceFieldSubsystem::getAmberImproperTorsionGlobalScaleFactor() const {return getRep().amberImproperTorsionGlobalScaleFactor;} Real DuMMForceFieldSubsystem::getCustomBondStretchGlobalScaleFactor() const {return getRep().customBondStretchGlobalScaleFactor;} Real DuMMForceFieldSubsystem::getCustomBondBendGlobalScaleFactor() const {return getRep().customBondBendGlobalScaleFactor;} Real DuMMForceFieldSubsystem::getCustomBondTorsionGlobalScaleFactor() const {return getRep().customBondTorsionGlobalScaleFactor;} void DuMMForceFieldSubsystem::setTracing(bool shouldTrace) { updRep().tracing = shouldTrace; } bool DuMMForceFieldSubsystem::getUseMultithreadedComputation() const { return getRep().useMultithreadedComputation; } void DuMMForceFieldSubsystem::setUseMultithreadedComputation(bool use) { invalidateSubsystemTopologyCache(); updRep().useMultithreadedComputation = use; } bool DuMMForceFieldSubsystem::isUsingMultithreadedComputation() const { return getRep().usingMultithreaded; } int DuMMForceFieldSubsystem::getNumThreadsRequested() const { return getRep().numThreadsRequested; } void DuMMForceFieldSubsystem::setNumThreadsRequested(int nThreads) { invalidateSubsystemTopologyCache(); updRep().numThreadsRequested = nThreads > 0 ? nThreads : 0; } int DuMMForceFieldSubsystem::getNumThreadsInUse() const { return getRep().numThreadsInUse; } bool DuMMForceFieldSubsystem::getUseOpenMMAcceleration() const { return getRep().wantOpenMMAcceleration; } void DuMMForceFieldSubsystem::setUseOpenMMAcceleration(bool use) { invalidateSubsystemTopologyCache(); updRep().wantOpenMMAcceleration = use; } bool DuMMForceFieldSubsystem::getAllowOpenMMReference() const { return getRep().allowOpenMMReference; } void DuMMForceFieldSubsystem::setAllowOpenMMReference(bool allow) { invalidateSubsystemTopologyCache(); updRep().allowOpenMMReference = allow; } bool DuMMForceFieldSubsystem::isUsingOpenMM() const { return getRep().usingOpenMM; } std::string DuMMForceFieldSubsystem::getOpenMMPlatformInUse() const { return getRep().openMMPlatformInUse; } DuMM::ClusterIndex DuMMForceFieldSubsystem::createCluster(const char* groupName) { invalidateSubsystemTopologyCache(); // Currently there is no error checking to do. We don't insist on unique group names. return updRep().addCluster(Cluster(groupName)); } DuMM::AtomIndex DuMMForceFieldSubsystem::addAtom(DuMM::ChargedAtomTypeIndex chargedAtomTypeIndex) { static const char* MethodName = "addAtom"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); SimTK_APIARGCHECK1_ALWAYS(mm.isValidChargedAtomType(chargedAtomTypeIndex), mm.ApiClassName, MethodName, "charged atom type %d is not valid", (int) chargedAtomTypeIndex); const DuMM::AtomIndex atomIndex = (const DuMM::AtomIndex)mm.atoms.size(); mm.atoms.push_back(DuMMAtom(chargedAtomTypeIndex, atomIndex)); return atomIndex; } void DuMMForceFieldSubsystem::placeAtomInCluster(DuMM::AtomIndex atomIndex, DuMM::ClusterIndex clusterIndex, const Vec3& stationInNm) { static const char* MethodName = "placeAtomInCluster"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); // Make sure that we've seen both the atomIndex and clusterIndex before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtom(atomIndex), mm.ApiClassName, MethodName, "atom index %d is not valid", (int) atomIndex); SimTK_APIARGCHECK1_ALWAYS(mm.isValidCluster(clusterIndex), mm.ApiClassName, MethodName, "cluster index %d is not valid", (int) clusterIndex); Cluster& cluster = mm.updCluster(clusterIndex); // Make sure that this cluster doesn't already contain this atom, either directly // or recursively through its subclusters. SimTK_APIARGCHECK3_ALWAYS(!cluster.containsAtom(atomIndex), mm.ApiClassName, MethodName, "cluster %d('%s') already contains atom %d", (int) clusterIndex, cluster.name.c_str(), (int) atomIndex); // Add the atom to the cluster. cluster.placeAtom(atomIndex, stationInNm, mm); } void DuMMForceFieldSubsystem::placeClusterInCluster (DuMM::ClusterIndex childClusterIndex, DuMM::ClusterIndex parentClusterIndex, const Transform& placementInNm) { static const char* MethodName = "placeClusterInCluster"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); // Make sure that we've seen both of these clusters before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidCluster(childClusterIndex), mm.ApiClassName, MethodName, "child cluster Index %d is not valid", (int) childClusterIndex); SimTK_APIARGCHECK1_ALWAYS(mm.isValidCluster(parentClusterIndex), mm.ApiClassName, MethodName, "parent cluster Index %d is not valid", (int) parentClusterIndex); Cluster& parent = mm.updCluster(parentClusterIndex); const Cluster& child = mm.getCluster(childClusterIndex); // TODO: for now, make sure the parent is a top-level cluster, meaning that it does // not have any parent clusters (although it can be attached to a body). This restriction // should be relaxed but it is tricky to get all the parents' and ancestors' content // lists updated correctly so I'm deferring that for now (sherm 060928). SimTK_APIARGCHECK2_ALWAYS(parent.isTopLevelCluster(), mm.ApiClassName, MethodName, "parent cluster %d('%s') is not a top-level cluster so you cannot add a child cluster to it now", (int) parentClusterIndex, parent.name.c_str()); // Child must not already be attached to a body. SimTK_APIARGCHECK2_ALWAYS(!child.isAttachedToBody(), mm.ApiClassName, MethodName, "child cluster %d('%s') is already attached to a body so cannot now be placed in another cluster", (int) childClusterIndex, child.name.c_str()); // Make sure that parent cluster doesn't already contain child cluster, either directly // or recursively through its subclusters. SimTK_APIARGCHECK4_ALWAYS(!parent.containsCluster(childClusterIndex), mm.ApiClassName, MethodName, "parent cluster %d('%s') already contains child cluster %d('%s')", (int) parentClusterIndex, parent.name.c_str(), (int) childClusterIndex, child.name.c_str()); // Make sure the new child cluster doesn't contain any atoms which are already in // any of the trees to which the parent cluster is associated. // TODO: for now we need only look at the parent since we know it is top level. DuMM::AtomIndex atomIndex; SimTK_APIARGCHECK5_ALWAYS(!parent.overlapsWithCluster(child, atomIndex), mm.ApiClassName, MethodName, "parent cluster %d('%s') and would-be child cluster %d('%s') both contain atom %d" " so they cannot have a parent/child relationship", (int) parentClusterIndex, parent.name.c_str(), (int) childClusterIndex, child.name.c_str(), (int) atomIndex); // Add the child cluster to the parent. parent.placeCluster(childClusterIndex, placementInNm, mm); } void DuMMForceFieldSubsystem::attachClusterToBody (DuMM::ClusterIndex clusterIndex, MobilizedBodyIndex mobodIx, const Transform& placementInNm) { static const char* MethodName = "attachClusterToBody"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); // Make sure we've seen this cluster before, and that the body number is well formed. SimTK_APIARGCHECK1_ALWAYS(mm.isValidCluster(clusterIndex), mm.ApiClassName, MethodName, "cluster Index %d is not valid", (int) clusterIndex); SimTK_APIARGCHECK1_ALWAYS(mobodIx.isValid(), mm.ApiClassName, MethodName, "body number %d is not valid: must be nonnegative", (int)mobodIx); const Cluster& child = mm.getCluster(clusterIndex); // Child must not already be attached to a body. SimTK_APIARGCHECK3_ALWAYS(!child.isAttachedToBody(), mm.ApiClassName, MethodName, "cluster %d('%s') is already attached to body %d so cannot now be" " attached to a body", (int)clusterIndex, child.name.c_str(), (int)child.getMobodIndex()); // None of the atoms in the child can be attached to any body. DuMM::AtomIndex tempAtomIndex; MobilizedBodyIndex tempBodyIndex; SimTK_APIARGCHECK4_ALWAYS( !child.containsAnyAtomsAttachedToABody(tempAtomIndex,tempBodyIndex,mm), mm.ApiClassName, MethodName, "cluster %d('%s') contains atom %d which is already attached to body %d" " so the cluster cannot now be attached to another body", (int)clusterIndex, child.name.c_str(), (int)tempAtomIndex, (int)tempBodyIndex); // Create an entry for the body if necessary, and its corresponding cluster. DuMMBodyIndex duMMBodyIndex = mm.ensureDuMMBodyEntryExists(mobodIx); Cluster& bodyCluster = mm.updCluster(mm.getDuMMBody(duMMBodyIndex).getClusterIndex()); // Make sure that body cluster doesn't already contain child cluster, either directly // or recursively through its subclusters. SimTK_APIARGCHECK3_ALWAYS(!bodyCluster.containsCluster(clusterIndex), mm.ApiClassName, MethodName, "cluster %d('%s') is already attached (directly or indirectly) to" " body %d", (int)clusterIndex, child.name.c_str(), (int)mobodIx); // OK, attach the cluster to the body's cluster. bodyCluster.placeCluster(clusterIndex, placementInNm, mm); } void DuMMForceFieldSubsystem::attachAtomToBody (DuMM::AtomIndex atomIndex, MobilizedBodyIndex bodyIndex, const Vec3& stationInNm) { static const char* MethodName = "attachAtomToBody"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); // Make sure we've seen this atom before, and that the body number is well formed. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtom(atomIndex), mm.ApiClassName, MethodName, "atom index %d is not valid", (int) atomIndex); SimTK_APIARGCHECK1_ALWAYS(bodyIndex.isValid(), mm.ApiClassName, MethodName, "body number %d is not valid: must be nonnegative", (int)bodyIndex); // The atom must not already be attached to a body, even this one. SimTK_APIARGCHECK2_ALWAYS(!mm.getAtom(atomIndex).isAttachedToBody(), mm.ApiClassName, MethodName, "atom %d is already attached to body %d so cannot now be attached" " to a body", (int) atomIndex, (int)mm.getAtom(atomIndex).getMobodIndex()); // Create an entry for the body if necessary, and its corresponding cluster. DuMMBodyIndex duMMBodyIndex = mm.ensureDuMMBodyEntryExists(bodyIndex); Cluster& bodyCluster = mm.updCluster(mm.getDuMMBody(duMMBodyIndex).getClusterIndex()); // Attach the atom to the body's cluster. bodyCluster.placeAtom(atomIndex, stationInNm, mm); } MassProperties DuMMForceFieldSubsystem::calcClusterMassProperties (DuMM::ClusterIndex clusterIndex, const Transform& placementInNm) const { static const char* MethodName = "calcClusterMassProperties"; const DuMMForceFieldSubsystemRep& mm = getRep(); // Make sure we've seen this cluster before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidCluster(clusterIndex), mm.ApiClassName, MethodName, "cluster Index %d is not valid", (int) clusterIndex); return mm.getCluster(clusterIndex).calcMassProperties(placementInNm, mm); } DuMM::BondIndex DuMMForceFieldSubsystem::addBond(DuMM::AtomIndex atom1Ix, DuMM::AtomIndex atom2Ix) { static const char* MethodName = "addBond"; invalidateSubsystemTopologyCache(); DuMMForceFieldSubsystemRep& mm = updRep(); // Make sure we've seen these atoms before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtom(atom1Ix), mm.ApiClassName, MethodName, "atom1(%d) is not valid", (int) atom1Ix); SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtom(atom2Ix), mm.ApiClassName, MethodName, "atom2(%d) is not valid", (int) atom2Ix); // An atom can't be bonded to itself. SimTK_APIARGCHECK1_ALWAYS(atom1Ix != atom2Ix, mm.ApiClassName, MethodName, "the same atom index (%d) was given for both atoms, which makes no sense", (int) atom1Ix); // Ensure that atom1 < atom2 if (atom1Ix > atom2Ix) std::swap(atom1Ix,atom2Ix); DuMMAtom& a1 = mm.updAtom(atom1Ix); DuMMAtom& a2 = mm.updAtom(atom2Ix); SimTK_APIARGCHECK2_ALWAYS(!a1.isBondedTo(atom2Ix), mm.ApiClassName, MethodName, "atom %d is already bonded to atom %d; you can only do that once", (int) atom1Ix, (int) atom2Ix); mm.bonds.push_back(Bond(atom1Ix,atom2Ix)); a1.bond12.push_back(atom2Ix); a2.bond12.push_back(atom1Ix); return (DuMM::BondIndex)(mm.bonds.size() - 1); } int DuMMForceFieldSubsystem::getNumAtoms() const { return getRep().getNumAtoms(); } int DuMMForceFieldSubsystem::getNumBonds() const { return getRep().getNumBonds(); } // 'which' is 0 or 1 to pick one of the two atoms whose index we return. DuMM::AtomIndex DuMMForceFieldSubsystem::getBondAtom(DuMM::BondIndex bondIx, int which) const { static const char* MethodName = "getBondAtom"; const DuMMForceFieldSubsystemRep& mm = getRep(); // Make sure we've seen this bond before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidBond(bondIx), mm.ApiClassName, MethodName, "bond %d is not valid", (int) bondIx); SimTK_APIARGCHECK1_ALWAYS(which==0 || which==1, mm.ApiClassName, MethodName, "'which' was %d but must be 0 or 1 to choose one of the two atoms", which); return mm.bonds[bondIx].atoms[which]; } // Returned mass is in daltons (g/mol). Real DuMMForceFieldSubsystem::getAtomMass(DuMM::AtomIndex atomIndex) const { static const char* MethodName = "getAtomMass"; const DuMMForceFieldSubsystemRep& mm = getRep(); // Make sure we've seen this atom before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtom(atomIndex), mm.ApiClassName, MethodName, "atom %d is not valid", (int) atomIndex); return Element::getByAtomicNumber(mm.getAtomElementNum(atomIndex))->getMass(); } // Returns the atomic number (number of protons in nucleus). int DuMMForceFieldSubsystem::getAtomElement(DuMM::AtomIndex atomIndex) const { static const char* MethodName = "getAtomElement"; const DuMMForceFieldSubsystemRep& mm = getRep(); // Make sure we've seen this atom before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtom(atomIndex), mm.ApiClassName, MethodName, "atom %d is not valid", (int) atomIndex); return mm.getAtomElementNum(atomIndex); } // Last vestige of Element class that was internal to DuMMForceFieldSubsystem. // I don't want to add a "color" field to the external Element class. // Properly, there should be an ElementColorer class or something. Vec3 DuMMForceFieldSubsystem::getElementDefaultColor(int atomicNumber) const { switch (atomicNumber) { case 1: // hydrogen return Green; case 7: // nitrogen return Blue; case 8: // oxygen return Red; case 15: // phosphorus return Magenta; case 16: // sulfur return Yellow; case 79: // gold return Yellow; default: return Gray; } } Vec3 DuMMForceFieldSubsystem::getAtomDefaultColor(DuMM::AtomIndex atomIndex) const { static const char* MethodName = "getAtomDefaultColor"; const DuMMForceFieldSubsystemRep& mm = getRep(); // Make sure we've seen this atom before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtom(atomIndex), mm.ApiClassName, MethodName, "atom %d is not valid", (int) atomIndex); return getElementDefaultColor(mm.getAtomElementNum(atomIndex)); } // Returned radius is in nm. Real DuMMForceFieldSubsystem::getAtomRadius(DuMM::AtomIndex atomIndex) const { static const char* MethodName = "getAtomRadius"; const DuMMForceFieldSubsystemRep& mm = getRep(); // Make sure we've seen this atom before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtom(atomIndex), mm.ApiClassName, MethodName, "atom %d is not valid", (int) atomIndex); const AtomClass& cl = mm.atomClasses[mm.getAtomClassIndex(atomIndex)]; return cl.vdwRadius; } // Returned station is in nm. Vec3 DuMMForceFieldSubsystem::getAtomStationOnBody(DuMM::AtomIndex atomIndex) const { static const char* MethodName = "getAtomStationOnBody"; const DuMMForceFieldSubsystemRep& mm = getRep(); // Make sure we've seen this atom before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtom(atomIndex), mm.ApiClassName, MethodName, "atom %d is not valid", (int) atomIndex); const DuMMAtom& a = mm.getAtom(atomIndex); // Atom must be attached to a body. SimTK_APIARGCHECK1_ALWAYS(a.isAttachedToBody(), mm.ApiClassName, MethodName, "atom %d is not attached to a body", (int) atomIndex); return a.station_B; } // Returned placement is in nm. Transform DuMMForceFieldSubsystem::getClusterPlacementOnBody(DuMM::ClusterIndex clusterIndex) const { static const char* MethodName = "getClusterPlacementOnBody"; const DuMMForceFieldSubsystemRep& mm = getRep(); // Make sure we've seen this cluster before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidCluster(clusterIndex), mm.ApiClassName, MethodName, "cluster Index %d is not valid", (int) clusterIndex); const Cluster& c = mm.getCluster(clusterIndex); // Cluster must be attached to a body. SimTK_APIARGCHECK2_ALWAYS(c.isAttachedToBody(), mm.ApiClassName, MethodName, "cluster %d('%s') is not attached to a body", (int) clusterIndex, c.name.c_str()); return c.placement_B; } // Returned station is in nm. Vec3 DuMMForceFieldSubsystem::getAtomStationInCluster(DuMM::AtomIndex atomIndex, DuMM::ClusterIndex clusterIndex) const { static const char* MethodName = "getAtomStationInCluster"; const DuMMForceFieldSubsystemRep& mm = getRep(); // Make sure that we've seen both the atomIndex and clusterIndex before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtom(atomIndex), mm.ApiClassName, MethodName, "atom index %d is not valid", (int) atomIndex); SimTK_APIARGCHECK1_ALWAYS(mm.isValidCluster(clusterIndex), mm.ApiClassName, MethodName, "cluster index %d is not valid", (int) clusterIndex); const Cluster& c = mm.getCluster(clusterIndex); const AtomPlacementSet& atoms = c.getAllContainedAtoms(); const AtomPlacementSet::const_iterator ap = atoms.find(AtomPlacement(atomIndex,Vec3(0))); // We're going to be upset of this cluster doesn't contain this atom. SimTK_APIARGCHECK3_ALWAYS(ap != atoms.end(), mm.ApiClassName, MethodName, "cluster %d('%s') does not contain atom %d", (int) clusterIndex, c.name.c_str(), (int) atomIndex); return ap->station; } // Returned placement is in nm. Transform DuMMForceFieldSubsystem::getClusterPlacementInCluster(DuMM::ClusterIndex childClusterIndex, DuMM::ClusterIndex parentClusterIndex) const { static const char* MethodName = "getClusterPlacementInCluster"; const DuMMForceFieldSubsystemRep& mm = getRep(); // Make sure that we've seen both of these clusters before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidCluster(childClusterIndex), mm.ApiClassName, MethodName, "child cluster Index %d is not valid", (int) childClusterIndex); SimTK_APIARGCHECK1_ALWAYS(mm.isValidCluster(parentClusterIndex), mm.ApiClassName, MethodName, "parent cluster Index %d is not valid", (int) parentClusterIndex); const Cluster& parent = mm.getCluster(parentClusterIndex); const Cluster& child = mm.getCluster(childClusterIndex); const ClusterPlacementSet& clusters = parent.getAllContainedClusters(); const ClusterPlacementSet::const_iterator cp = clusters.find(ClusterPlacement(childClusterIndex,Transform())); // We're going to be upset of the parent cluster doesn't contain the child. SimTK_APIARGCHECK4_ALWAYS(cp != clusters.end(), mm.ApiClassName, MethodName, "cluster %d('%s') does not contain cluster %d('%d')", (int) parentClusterIndex, parent.name.c_str(), (int) childClusterIndex, child.name.c_str()); return cp->placement; } MobilizedBodyIndex DuMMForceFieldSubsystem::getAtomBody(DuMM::AtomIndex atomIndex) const { static const char* MethodName = "getAtomBody"; const DuMMForceFieldSubsystemRep& mm = getRep(); // Make sure that we've seen this atomIndex before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidAtom(atomIndex), mm.ApiClassName, MethodName, "atom index %d is not valid", (int) atomIndex); const DuMMAtom& a = mm.getAtom(atomIndex); // Atom must be attached to a body. SimTK_APIARGCHECK1_ALWAYS(a.isAttachedToBody(), mm.ApiClassName, MethodName, "atom %d is not attached to a body", (int) atomIndex); return a.getMobodIndex(); } MobilizedBodyIndex DuMMForceFieldSubsystem::getClusterBody(DuMM::ClusterIndex clusterIndex) const { static const char* MethodName = "getClusterBody"; const DuMMForceFieldSubsystemRep& mm = getRep(); // Make sure that we've seen this atomIndex before. SimTK_APIARGCHECK1_ALWAYS(mm.isValidCluster(clusterIndex), mm.ApiClassName, MethodName, "cluster Index %d is not valid", (int) clusterIndex); const Cluster& c = mm.getCluster(clusterIndex); // Cluster must be attached to a body. SimTK_APIARGCHECK2_ALWAYS(c.isAttachedToBody(), mm.ApiClassName, MethodName, "cluster %d('%s') is not attached to a body", (int) clusterIndex, c.name.c_str()); return c.getMobodIndex(); } void DuMMForceFieldSubsystem::dump() const { return getRep().dump(); } // How many times has the forcefield been evaluated? long long DuMMForceFieldSubsystem::getForceEvaluationCount() const { return getRep().getForceEvaluationCount(); } std::ostream& DuMMForceFieldSubsystemRep::generateBiotypeChargedAtomTypeSelfCode(std::ostream& os) const { std::map<BiotypeIndex, DuMM::ChargedAtomTypeIndex>::const_iterator i; for (i = chargedAtomTypesByBiotype.begin(); i != chargedAtomTypesByBiotype.end(); ++i) { generateBiotypeChargedAtomTypeSelfCode(os, i->first); } return os; } std::ostream& DuMMForceFieldSubsystem::generateBiotypeChargedAtomTypeSelfCode(std::ostream& os) const { return getRep().generateBiotypeChargedAtomTypeSelfCode(os); } void DuMMForceFieldSubsystem::setBiotypeChargedAtomType(DuMM::ChargedAtomTypeIndex chargedAtomTypeIndex, BiotypeIndex biotypeIx) { updRep().setBiotypeChargedAtomType(chargedAtomTypeIndex, biotypeIx); } DuMM::ChargedAtomTypeIndex DuMMForceFieldSubsystem::getBiotypeChargedAtomType(BiotypeIndex biotypeIx) const { return getRep().getBiotypeChargedAtomType(biotypeIx); } void DuMMForceFieldSubsystem::loadAmber99Parameters() { Biotype::initializePopularBiotypes(); populateAmber99Params(*this); } void DuMMForceFieldSubsystem::loadTestMoleculeParameters() { Biotype::initializePopularBiotypes(); // TODO - these hard-coded chargedAtomTypeIndexs are not too cool // TODO - these charges are made up defineChargedAtomType(DuMM::ChargedAtomTypeIndex(5000), "Methane C", DuMM::AtomClassIndex(1), 0.04); defineChargedAtomType(DuMM::ChargedAtomTypeIndex(5001), "Methane H", DuMM::AtomClassIndex(34), -0.01); setBiotypeChargedAtomType(DuMM::ChargedAtomTypeIndex(5000), Biotype::MethaneC().getIndex()); setBiotypeChargedAtomType(DuMM::ChargedAtomTypeIndex(5001), Biotype::MethaneH().getIndex()); defineChargedAtomType(DuMM::ChargedAtomTypeIndex(5002), "Ethane C", DuMM::AtomClassIndex(1), 0.03); defineChargedAtomType(DuMM::ChargedAtomTypeIndex(5003), "Ethane H", DuMM::AtomClassIndex(34), -0.01); setBiotypeChargedAtomType(DuMM::ChargedAtomTypeIndex(5002), Biotype::EthaneC().getIndex()); setBiotypeChargedAtomType(DuMM::ChargedAtomTypeIndex(5003), Biotype::EthaneH().getIndex()); } void DuMMForceFieldSubsystem::populateFromTinkerParameterFile(std::istream& tinkerStream) { ////////////////////////////////////////////////////// // 1) Read Tinker parameter file one line at a time // ////////////////////////////////////////////////////// Real radiusSizeScale = 1.0; // set to 0.5 for diameter parameter sets vs. 1.0 for radius Real radiusTypeScale = 1.0; // set to 2^(1/6) for sigma(R0) vs. 1.0 for Rmin // Bookkeeping to retrieve element and valence during biotype definition std::map<DuMM::AtomClassIndex, int> atomicNumberByAtomClassIndex; std::map<DuMM::AtomClassIndex, int> valenceByAtomClassIndex; std::map<DuMM::ChargedAtomTypeIndex, DuMM::AtomClassIndex> atomClassIdByChargedAtomTypeIndex; std::string tinkerParamFileLine; while( getline( tinkerStream, tinkerParamFileLine ) ) { std::stringstream lineStream(tinkerParamFileLine); // Get the first word on the line of text from the file // Significant words include "atom", "vdw", "bond", etc. String recordType; lineStream >> recordType; // forcefield name if (recordType == "forcefield") { lineStream >> updRep().forcefieldName; } // VDWTYPE [LENNARD-JONES/BUCKINGHAM/BUFFERED-14-7/MM3-HBOND/GAUSSIAN] else if (recordType == "vdwtype") { String vdwType; lineStream >> vdwType; if (vdwType == "LENNARD-JONES") ; // OK else { // DuMMForcefieldSubsystem doesn't know about other vdw models SimTK_THROW1( Exception::Cant,"Parse Exception: Can't use van der Waals model other than LENNARD-JONES" ); } } // RADIUSRULE [ARITHMETIC/GEOMETRIC/CUBIC-MEAN] else if (recordType == "radiusrule") { String rule; lineStream >> rule; if (rule == "ARITHMETIC") setVdwMixingRule(LorentzBerthelot); else if (rule == "GEOMETRIC") setVdwMixingRule(Jorgensen); else if (rule == "CUBIC-MEAN") setVdwMixingRule(HalgrenHHG); else { // DuMMForcefieldSubsystem doesn't know about other vdw models SimTK_THROW1( Exception::Cant,"Parse Exception: Unrecognized radius rule" ); } } // RADIUSTYPE [R-MIN/SIGMA] else if (recordType == "radiustype") { String radiusType; lineStream >> radiusType; if (radiusType == "R-MIN") radiusTypeScale = 1.0; else if (radiusType == "SIGMA") radiusTypeScale = pow(2.0, (1.0/6.0)); } else if (recordType == "radiussize") { String radiusSize; lineStream >> radiusSize; if (radiusSize == "RADIUS") radiusSizeScale = 1.0; else if (radiusSize == "DIAMETER") radiusSizeScale = 0.5; else { SimTK_THROW1( Exception::Cant, "Parse Error: unrecognized radius size" ); } } // EPSILONRULE [GEOMETRIC/ARITHMETIC/HARMONIC/HHG] // TODO - DuMM currently lumps this with RADIUSRULE else if (recordType == "epsilonrule") { String epsilonRule; lineStream >> epsilonRule; if (epsilonRule == "GEOMETRIC") { if (getVdwMixingRule() == LorentzBerthelot) continue; // already geometric else if (getVdwMixingRule() == Jorgensen) continue; // already geometric else setVdwMixingRule(Jorgensen); } else if (epsilonRule == "HHG") { setVdwMixingRule(HalgrenHHG); } else { SimTK_THROW1( Exception::Cant, "Parse Error: unrecognized epsilon rule" ); } } else if (recordType == "vdw-14-scale") { Real vdw14Scale; lineStream >> vdw14Scale; setVdw14ScaleFactor(1.0 / vdw14Scale); } else if (recordType == "chg-14-scale") { Real chg14Scale; lineStream >> chg14Scale; setCoulomb14ScaleFactor(1.0 / chg14Scale); } else if (recordType == "dielectric") { Real dielectric; lineStream >> dielectric; if (dielectric != 1.0) { SimTK_THROW1( Exception::Cant, "Can't use dielectric other than 1.0" ); } } // "atom" records // 'atom 1 14 N "Glycine N" 7 14.010 3' else if (recordType == "atom") { int integer; lineStream >> integer; DuMM::ChargedAtomTypeIndex chargedAtomTypeIndex(integer); lineStream >> integer; DuMM::AtomClassIndex atomClassId(integer); String atomClassName; lineStream >> atomClassName; // Use getline() to get field between quotation marks std::string chargedAtomTypeName; // First try grabs spaces std::getline(lineStream, chargedAtomTypeName, '"'); // Second try grabs string std::getline(lineStream, chargedAtomTypeName, '"'); int elementNumber; lineStream >> elementNumber; Real atomMass; lineStream >> atomMass; int valence; lineStream >> valence; // we don't yet know vdwRadius and vdwWellDepth if (!isValidAtomClass(atomClassId)) { defineIncompleteAtomClass_KA( atomClassId, atomClassName.c_str(), elementNumber, valence); } atomicNumberByAtomClassIndex[atomClassId] = elementNumber; valenceByAtomClassIndex[atomClassId] = valence; // we don't yet know atomic partial charge defineIncompleteChargedAtomType_KA( chargedAtomTypeIndex, chargedAtomTypeName.c_str(), atomClassId); atomClassIdByChargedAtomTypeIndex[chargedAtomTypeIndex] = atomClassId; } // "vdw" records, e.g. // 'vdw 1 1.9080 0.1094' // RecordType AtomClass Radius WellDepth else if (recordType == "vdw") { int integer; lineStream >> integer; DuMM::AtomClassIndex atomClassId(integer); Real radius; lineStream >> radius; radius *= radiusSizeScale; radius *= radiusTypeScale; Real wellDepth; lineStream >> wellDepth; setAtomClassVdwParameters_KA(atomClassId, radius, wellDepth); } // "bond" records // bond stretching parameters // 'bond 1 22 320.0 1.4100' else if (recordType == "bond") { int integer; lineStream >> integer; DuMM::AtomClassIndex atomClassId1(integer); lineStream >> integer; DuMM::AtomClassIndex atomClassId2(integer); Real stiffness; lineStream >> stiffness; Real length; lineStream >> length; if ( isValidAtomClass(atomClassId1) && isValidAtomClass(atomClassId2) ) defineBondStretch_KA(atomClassId1, atomClassId2, stiffness, length); } // "angle" records // angle bending parameters // 'angle 10 1 34 50.00 109.50' else if (recordType == "angle") { int integer; lineStream >> integer; DuMM::AtomClassIndex atomClassId1(integer); lineStream >> integer; DuMM::AtomClassIndex atomClassId2(integer); lineStream >> integer; DuMM::AtomClassIndex atomClassId3(integer); Real stiffness; lineStream >> stiffness; Real angle; lineStream >> angle; defineBondBend_KA(atomClassId1, atomClassId2, atomClassId3, stiffness, angle); } // improper torsions // imptors 1 14 2 24 10.500 180.0 2 else if (recordType == "imptors") { int integer; lineStream >> integer; DuMM::AtomClassIndex atomClassId1(integer); lineStream >> integer; DuMM::AtomClassIndex atomClassId2(integer); lineStream >> integer; DuMM::AtomClassIndex atomClassId3(integer); lineStream >> integer; DuMM::AtomClassIndex atomClassId4(integer); Real amplitudeInKcal; lineStream >> amplitudeInKcal; Real phaseAngleInDegrees; lineStream >> phaseAngleInDegrees; int periodicity; lineStream >> periodicity; defineAmberImproperTorsion_KA (atomClassId1, atomClassId2, atomClassId3, atomClassId4, periodicity, amplitudeInKcal, phaseAngleInDegrees); } // "torsion" records // 'torsion 1 1 1 1 0.200 180.0 1 0.250 180.0 2 0.180 0.0 3' // OR // 'torsion 23 1 1 23 0.144 0.0 3 1.175 0.0 2' // OR // 'torsion 1 1 1 2 0.156 0.0 3' else if (recordType == "torsion") { int integer; lineStream >> integer; DuMM::AtomClassIndex atomClassId1(integer); lineStream >> integer; DuMM::AtomClassIndex atomClassId2(integer); lineStream >> integer; DuMM::AtomClassIndex atomClassId3(integer); lineStream >> integer; DuMM::AtomClassIndex atomClassId4(integer); // figure out how many fields are on this line int numberOfFields = 0; size_t pos = 0; while(pos != String::npos) { pos = tinkerParamFileLine.find_first_not_of(" ", pos); pos = tinkerParamFileLine.find_first_of(" ", pos); ++numberOfFields; } assert(numberOfFields >= 8); Real amplitude1; lineStream >> amplitude1; Real phase1; lineStream >> phase1; int periodicity1; lineStream >> periodicity1; if (numberOfFields == 8) { defineBondTorsion_KA( atomClassId1, atomClassId2, atomClassId3, atomClassId4, periodicity1, amplitude1, phase1 ); continue; } assert(numberOfFields >= 11); Real amplitude2; lineStream >> amplitude2; Real phase2; lineStream >> phase2; int periodicity2; lineStream >> periodicity2; if (numberOfFields == 11) { defineBondTorsion_KA( atomClassId1, atomClassId2, atomClassId3, atomClassId4, periodicity1, amplitude1, phase1, periodicity2, amplitude2, phase2 ); continue; } assert(numberOfFields == 14); Real amplitude3; lineStream >> amplitude3; Real phase3; lineStream >> phase3; int periodicity3; lineStream >> periodicity3; defineBondTorsion_KA( atomClassId1, atomClassId2, atomClassId3, atomClassId4, periodicity1, amplitude1, phase1, periodicity2, amplitude2, phase2, periodicity3, amplitude3, phase3 ); continue; } // atom partial charge records, e.g. // 'charge 1 -0.4157' // RecordType AtomChargedType Charge else if ( recordType == "charge" ) { int integer; lineStream >> integer; DuMM::ChargedAtomTypeIndex chargedAtomTypeIndex(integer); Real charge; lineStream >> charge; setChargedAtomTypeCharge(chargedAtomTypeIndex, charge); } // "biotype" records, e.g. // 'biotype 1 N "Glycine" 1' // RecordType Biotype AtomName ResidueName AtomClass else if ( recordType == "biotype" ) { int integer; lineStream >> integer; TinkerBiotypeIndex tinkerBiotypeIndex(integer); String atomName; lineStream >> atomName; String residueName; // Use getline() to get field between quotation marks // First try grabs spaces std::getline(lineStream, residueName, '"'); // Second try grabs string std::getline(lineStream, residueName, '"'); lineStream >> integer; DuMM::ChargedAtomTypeIndex chargedAtomTypeIndex(integer); // Resolve element and valence DuMM::AtomClassIndex atomClassId = atomClassIdByChargedAtomTypeIndex[chargedAtomTypeIndex]; int atomicNumber = atomicNumberByAtomClassIndex[atomClassId]; int valence = valenceByAtomClassIndex[atomClassId]; // Resolve ordinality // Parse residueName into residueName and context // TODO - include nucleotide nomenclature, if necessary Ordinality::Residue ordinality = Ordinality::Any; // Separate residue name from ordinality indicator // case of "Acetyl N-Terminus" // Handle "N-Terminal GLY" int pos1 = residueName.find("N-Term"); if (pos1 != std::string::npos) { ordinality = Ordinality::Initial; // e.g. "N-Terminal GLY" if (pos1 == 0) residueName.replace(pos1, 11, ""); // e.g. "Acetyl N-Terminus" else residueName.replace(pos1-1, 11, ""); } pos1 = residueName.find("C-Term"); if (pos1 != std::string::npos) { ordinality = Ordinality::Final; // e.g. "C-Terminal GLY" if (pos1 == 0) residueName.replace(pos1, 11, ""); // e.g. "N-MeAmide C-Terminus" else residueName.replace(pos1-1, 11, ""); } // Nucleic acid biotypes, e.g. // "5'-Hydroxyl, RNA" // "5'-Phosphate OS, DNA" pos1 = residueName.find("5'-"); if (pos1 != std::string::npos) { ordinality = Ordinality::Initial; residueName.replace(pos1, 3, ""); // get rid of that annoying wrongly placed atom name in the terminal phosphates pos1 = residueName.find(" OP,"); if (pos1 != std::string::npos) residueName.replace(pos1, 4, ","); pos1 = residueName.find(" OS,"); if (pos1 != std::string::npos) residueName.replace(pos1, 4, ","); pos1 = residueName.find(" P,"); if (pos1 != std::string::npos) residueName.replace(pos1, 3, ","); } pos1 = residueName.find("3'-"); if (pos1 != std::string::npos) { ordinality = Ordinality::Final; residueName.replace(pos1, 3, ""); // get rid of that annoying wrongly placed atom name in the terminal phosphates pos1 = residueName.find(" OP,"); if (pos1 != std::string::npos) residueName.replace(pos1, 4, ","); pos1 = residueName.find(" OS,"); if (pos1 != std::string::npos) residueName.replace(pos1, 4, ","); pos1 = residueName.find(" P,"); if (pos1 != std::string::npos) residueName.replace(pos1, 3, ","); } pos1 = atomName.find("*"); if (pos1 != std::string::npos) atomName[pos1] = '\''; BiotypeIndex biotypeIx; if ( Biotype::exists(residueName.c_str(), atomName.c_str(), ordinality) ) { Biotype& biotype = Biotype::upd( residueName.c_str(), atomName.c_str(), ordinality ); biotypeIx = biotype.getIndex(); biotype.setTinkerBiotypeIndex(tinkerBiotypeIndex); } else biotypeIx = Biotype::defineTinkerBiotype(tinkerBiotypeIndex , Element::getByAtomicNumber(atomicNumber) , valence , residueName.c_str() , atomName.c_str() , ordinality ); setBiotypeChargedAtomType(chargedAtomTypeIndex, biotypeIx); } } }
42.584808
149
0.664008
[ "vector", "model", "transform" ]
48b03782181094367aa8f5b74f99c5f7c853b931
33,479
cpp
C++
Mac/SolunaAlgorithm/SolunaAlgorithm/main.cpp
FrickHazard/SolunaAlgorithm
735feadcc6990853451ea598adda8bf373bc3f21
[ "MIT" ]
null
null
null
Mac/SolunaAlgorithm/SolunaAlgorithm/main.cpp
FrickHazard/SolunaAlgorithm
735feadcc6990853451ea598adda8bf373bc3f21
[ "MIT" ]
null
null
null
Mac/SolunaAlgorithm/SolunaAlgorithm/main.cpp
FrickHazard/SolunaAlgorithm
735feadcc6990853451ea598adda8bf373bc3f21
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <stdio.h> #include <assert.h> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <chrono> // copy of boosts hash_combine template <class T> inline void hash_combine(std::size_t& s, const T& v) { std::hash<T> h; s ^= h(v) + 0x9e3779b9 + (s << 6) + (s >> 2); } enum PieceId { Sun = 0, Moon = 1, ShootingStar = 2, Stars = 3 }; struct PartitionNumber { uint32_t number; uint32_t count; } typedef PieceStack; struct BranchResult { uint32_t leafCount; uint32_t leafVictory; bool guaranteedWin; uint32_t flipMoveCount; } typedef BranchResult; struct GameStateHash { size_t operator()(const std::vector<uint32_t>& gameState) const { size_t hsh = std::hash<uint32_t>{}((uint32_t)gameState.size()); for (uint32_t i = 0; i < gameState.size(); ++i) { // order matters! hash_combine(hsh, gameState[i]); } return hsh; } }; struct PartitionHash { size_t operator()(const std::vector<PartitionNumber>& partition) const { size_t hsh = std::hash<uint32_t>{}((uint32_t)partition.size()); for (uint32_t i = 0; i < partition.size(); ++i) { // order matters! hash_combine(hsh, partition[i].number); hash_combine(hsh, partition[i].count); } return hsh; } }; bool operator == (const std::vector<PartitionNumber>& partition1, const std::vector<PartitionNumber>& partition2) { if (partition1.size() != partition2.size()) return false; for (uint32_t i = 0; i < partition1.size(); ++i) { if (partition1[i].number != partition2[i].number || partition1[i].count != partition2[i].count) return false; } return true; } struct ModuleState { uint32_t COLOR_COUNT; uint32_t PIECE_COUNT; std::vector<std::vector<uint32_t>> allGameStates; std::vector<std::vector<uint32_t>> allMoves; std::vector<BranchResult> allBranchResults; std::vector<uint32_t> initialStates; std::vector<std::vector<PartitionNumber>> allPartitions; std::unordered_map<std::vector<uint32_t>, uint32_t, GameStateHash> gameStateToIndexMap; std::unordered_map<std::vector<PartitionNumber>, uint32_t, PartitionHash> partitionToIdMap; } state; // recursive function, rewrite into iterative, this is the biggest choke point, exponential growth in color count // essentialy constrained orderless combinations void getAllGameStates ( std::vector<std::vector<uint32_t>> & wResult, const std::vector<uint32_t> & optionPieceCount, const uint32_t optionCount, uint32_t optionIndex, const uint32_t & maxItemCount, const uint32_t & maxPieceCount, std::vector<uint32_t> current, uint32_t currentPieceCount ) { for (uint32_t i = optionIndex; i < optionCount; ++i) { uint32_t idPieceCount = optionPieceCount[i]; if (idPieceCount + currentPieceCount > maxPieceCount) continue; std::vector<uint32_t> copy = current; copy.push_back(i); if (currentPieceCount + idPieceCount == maxPieceCount) { wResult.push_back(copy); } else if (copy.size() < maxItemCount) { getAllGameStates(wResult, optionPieceCount, optionCount, i, maxItemCount, maxPieceCount, copy, currentPieceCount + idPieceCount); } } } std::vector<std::vector<PartitionNumber>> nextPartition(std::vector<std::vector<PartitionNumber>> prevPartition, uint32_t n) { std::vector<std::vector<PartitionNumber>> result; for (uint32_t i = 0; i < prevPartition.size(); i++) { std::vector<PartitionNumber> withOne; if (prevPartition[i][0].number != 1) { withOne.push_back({ 1, 1 }); } for (uint32_t j = 0; j < prevPartition[i].size(); j++) { if (j == 1 && prevPartition[i][0].number < prevPartition[i][1].number && prevPartition[i][0].count == 1) { std::vector<PartitionNumber> permutation; if (prevPartition[i][0].number + 1 != prevPartition[i][1].number) { permutation.push_back({ prevPartition[i][0].number + 1, prevPartition[i][0].count }); } for (uint32_t k = 1; k < prevPartition[i].size(); k++) { permutation.push_back(prevPartition[i][k]); if (k == 1 && prevPartition[i][0].number + 1 == prevPartition[i][1].number) { ++permutation[0].count; } } result.push_back(permutation); } withOne.push_back(prevPartition[i][j]); if (j == 0 && prevPartition[i][j].number == 1) ++withOne[0].count; } result.push_back(withOne); } result.push_back({ { n, 1 } }); return result; } void generatePartitionIdMaps ( std::unordered_map<std::vector<PartitionNumber>, uint32_t, PartitionHash> &partitionToIdMap, std::vector<std::vector<PartitionNumber>> &allPartitions, std::vector<uint32_t> & idPieceCounts, const uint32_t PIECE_COUNT ) { partitionToIdMap = std::unordered_map<std::vector<PartitionNumber>, uint32_t, PartitionHash>(); allPartitions = std::vector<std::vector<PartitionNumber>>(); idPieceCounts = std::vector<uint32_t>(); std::vector<std::vector<PartitionNumber>> heightCountPartition; uint32_t partitionId = 0; for (uint32_t i = 1; i <= PIECE_COUNT; ++i) { heightCountPartition = nextPartition(heightCountPartition, i); for (uint32_t j = 0; j < heightCountPartition.size(); ++j) { idPieceCounts.push_back(i); partitionToIdMap.insert({ heightCountPartition[j], partitionId }); allPartitions.push_back(heightCountPartition[j]); ++partitionId; } } } std::vector<PartitionNumber> copyAndApplyPartitionChanges ( const std::vector<PartitionNumber> & partition, std::vector<uint32_t> remove, uint32_t add ) { std::vector<PartitionNumber> result; if (remove.size() == 1) remove.push_back(0); bool notAdded = true; for (uint32_t i = 0; i < partition.size(); i++) { if (remove[0] == partition[i].number || remove[1] == partition[i].number) { if (remove[0] == partition[i].number && remove[1] == partition[i].number) { if (partition[i].count > 2){ result.push_back({ partition[i].number, partition[i].count - 2 }); } } else if (partition[i].count > 1) { result.push_back({ partition[i].number, partition[i].count - 1 }); } } else { if (add == partition[i].number) { result.push_back({ partition[i].number, partition[i].count + 1}); notAdded = false; } else if (notAdded && add < partition[i].number && add != 0) { result.push_back({ add, 1 }); result.push_back(partition[i]); notAdded = false; } else { result.push_back(partition[i]); } } if (i == partition.size() - 1 && notAdded && add > partition[i].number) { result.push_back({ add, 1 }); } } return result; } std::vector<uint32_t> copyAndApplyPartitionIdChanges ( const std::vector<uint32_t> & gameState, // Both of these arrays will never be greater than 2, and always contains at least 1 entry each // comes from the fact a move only effects two pieces std::vector<uint32_t> remove, std::vector<uint32_t> add ) { std::vector<uint32_t> result; result.reserve(gameState.size() + add.size() - remove.size()); if (add.size() > 1 && add[1] < add[0]) std::swap(add[0], add[1]); bool usedRemoves[2] = { false }; bool usedAdds[2] = { false }; for (uint32_t i = 0; i < gameState.size(); i++) { bool addThisNumb = true; if ((!usedRemoves[0] && gameState[i] == remove[0]) || (!usedRemoves[1] && remove.size() > 1 && gameState[i] == remove[1])) { if (!usedRemoves[0] && gameState[i] == remove[0]) { usedRemoves[0] = true; } else { usedRemoves[1] = true; } addThisNumb = false; } if (!usedAdds[0] && gameState[i] > add[0]) { usedAdds[0] = true; result.push_back(add[0]); } if (add.size() > 1 && !usedAdds[1] && gameState[i] > add[1]) { usedAdds[1] = true; result.push_back(add[1]); } if (addThisNumb) result.push_back(gameState[i]); if (i == gameState.size() - 1) { if (!usedAdds[0]) result.push_back(add[0]); if (!usedAdds[1] && add.size() > 1) result.push_back(add[1]); } } return result; } std::vector<uint32_t> getPossibleNextStates ( const std::vector<uint32_t> & gameState, const std::vector<std::vector<PartitionNumber>> & allPartitions, const std::unordered_map<std::vector<PartitionNumber>, uint32_t, PartitionHash>& partitionToIdMap, const std::vector<uint32_t> & pieceCountVec, const std::unordered_map<std::vector<uint32_t>, uint32_t, GameStateHash> & gameStateToIndexMap ) { std::vector<uint32_t> result; std::vector<uint32_t> heightPartitionIds; std::vector<std::vector<PartitionNumber>> heightPartitions; std::vector<uint32_t> heightPartitionCount; // get unique gameStates uint32_t currIdx = 0; for (uint32_t i = 0; i < gameState.size(); ++i) { if (gameState[currIdx] != gameState[i]) { heightPartitionIds.push_back(gameState[currIdx]); heightPartitionCount.push_back(i - currIdx); heightPartitions.push_back(allPartitions[gameState[currIdx]] ); currIdx = i; } if (i == gameState.size() - 1) { heightPartitionIds.push_back(gameState[currIdx]); heightPartitionCount.push_back(i - currIdx + 1); heightPartitions.push_back(allPartitions[gameState[currIdx]]); } } // get new game states for when colors are same for (uint32_t i = 0; i < heightPartitions.size(); ++i) { for (uint32_t it = 0; it < heightPartitions[i].size(); ++it) { PartitionNumber partitionNumb = heightPartitions[i][it]; // If the count of pieces is more than one, we can merge with piece of same height and color if (partitionNumb.count > 1) { std::vector<PartitionNumber> updatedPartition = copyAndApplyPartitionChanges(heightPartitions[i], { partitionNumb.number, partitionNumb.number }, partitionNumb.number + partitionNumb.number); result.push_back(gameStateToIndexMap.at(copyAndApplyPartitionIdChanges(gameState, { heightPartitionIds[i] }, { partitionToIdMap.at(updatedPartition) }))); } // for every other piece of same color, but different height, we consider a symmetric merge of the two pieces for (uint32_t subIt = it; subIt < heightPartitions[i].size(); ++subIt) { if (subIt == it) continue; PartitionNumber partitionNumbOther = heightPartitions[i][subIt]; std::vector<PartitionNumber> updatedPartition = copyAndApplyPartitionChanges(heightPartitions[i], { partitionNumb.number, partitionNumbOther.number },partitionNumb.number + partitionNumbOther.number); result.push_back(gameStateToIndexMap.at(copyAndApplyPartitionIdChanges(gameState, { heightPartitionIds[i] }, { partitionToIdMap.at(updatedPartition) }))); } } } // get new game states when height states are the same for (uint32_t i = 0; i < heightPartitions.size(); ++i) { // if there are equivalent height/piece count partitions, we consider a symmetric merge for every, pair of equal height pieces // we only do this once, even if there are 3 equivelent partitions, as doing it again would be symmetric if (heightPartitionCount[i] > 1) { for (uint32_t it = 0; it < heightPartitions[i].size(); ++it) { PartitionNumber partitionNumb = heightPartitions[i][it]; std::vector<PartitionNumber> updatedPartition1 = copyAndApplyPartitionChanges(heightPartitions[i], { partitionNumb.number }, 0); std::vector<PartitionNumber> updatedPartition2 = copyAndApplyPartitionChanges(heightPartitions[i], { partitionNumb.number }, partitionNumb.number + partitionNumb.number); std::vector<uint32_t> partitionIdsToAdd; if (updatedPartition1.size() > 0) partitionIdsToAdd.push_back(partitionToIdMap.at(updatedPartition1)); if (updatedPartition2.size() > 0) partitionIdsToAdd.push_back(partitionToIdMap.at(updatedPartition2)); result.push_back(gameStateToIndexMap.at(copyAndApplyPartitionIdChanges(gameState, { heightPartitionIds[i], heightPartitionIds[i] }, partitionIdsToAdd))); } } } std::vector<uint32_t> indices = std::vector<uint32_t>(heightPartitions.size(), 0); while (true) { uint32_t minNumb = UINT32_MAX; std::vector<uint32_t> minIndices; minIndices.reserve(indices.size()); for (uint32_t i = 0; i < indices.size(); ++i) { if (indices[i] == heightPartitions[i].size()) continue; if (heightPartitions[i][indices[i]].number < minNumb) { minIndices.clear(); minNumb = heightPartitions[i][indices[i]].number; minIndices.push_back(i); } else if (heightPartitions[i][indices[i]].number == minNumb) { minIndices.push_back(i); } } for (uint32_t i = 0; i < minIndices.size(); ++i) { for (uint32_t j = i + 1; j < minIndices.size(); ++j) { { PartitionNumber partitionNumb = heightPartitions[minIndices[i]][indices[minIndices[i]]]; std::vector<PartitionNumber> updatedPartition1 = copyAndApplyPartitionChanges(heightPartitions[minIndices[i]], { partitionNumb.number }, 0); std::vector<PartitionNumber> updatedPartition2 = copyAndApplyPartitionChanges(heightPartitions[minIndices[j]], { partitionNumb.number }, partitionNumb.number + partitionNumb.number); std::vector<uint32_t> partitionIdsToAdd; if (updatedPartition1.size() > 0) partitionIdsToAdd.push_back(partitionToIdMap.at(updatedPartition1)); if (updatedPartition2.size() > 0) partitionIdsToAdd.push_back(partitionToIdMap.at(updatedPartition2)); result.push_back(gameStateToIndexMap.at(copyAndApplyPartitionIdChanges(gameState, { heightPartitionIds[minIndices[i]], heightPartitionIds[minIndices[j]] }, partitionIdsToAdd))); } { PartitionNumber partitionNumb = heightPartitions[minIndices[i]][indices[minIndices[i]]]; std::vector<PartitionNumber> updatedPartition1 = copyAndApplyPartitionChanges(heightPartitions[minIndices[i]], { partitionNumb.number }, partitionNumb.number + partitionNumb.number); std::vector<PartitionNumber> updatedPartition2 = copyAndApplyPartitionChanges(heightPartitions[minIndices[j]], { partitionNumb.number }, 0); std::vector<uint32_t> partitionIdsToAdd; if (updatedPartition1.size() > 0) partitionIdsToAdd.push_back(partitionToIdMap.at(updatedPartition1)); if (updatedPartition2.size() > 0) partitionIdsToAdd.push_back(partitionToIdMap.at(updatedPartition2)); result.push_back(gameStateToIndexMap.at(copyAndApplyPartitionIdChanges(gameState, { heightPartitionIds[minIndices[i]], heightPartitionIds[minIndices[j]] }, partitionIdsToAdd))); } } ++indices[minIndices[i]]; } if (minIndices.size() == 0) break; } return result; } BranchResult SolunaAlgorithm ( const uint32_t i, const std::vector<std::vector<uint32_t>> & allGameStates, const std::vector<std::vector<uint32_t>> & allMoves, std::vector<BranchResult> & allBranchResults ) { auto cached = allBranchResults[i]; if (!(cached.guaranteedWin == 0 && cached.leafCount == 0 && cached.leafVictory == 0)) { return cached; } const std::vector<uint32_t> & moveStateIndices = allMoves[i]; // leaf node, if no moves you lose if (moveStateIndices.size() == 0) { return { 1, 0, false }; } BranchResult result = { 0, 0, false, false }; uint32_t guaranteedWinChildrenCount = 0; for (uint32_t i =0; i < moveStateIndices.size(); i++) { const BranchResult branchResult = SolunaAlgorithm(moveStateIndices[i], allGameStates, allMoves, allBranchResults); if (!branchResult.guaranteedWin) { result.guaranteedWin = true; ++guaranteedWinChildrenCount; } result.leafCount += branchResult.leafCount; result.leafVictory += (branchResult.leafCount - branchResult.leafVictory); } result.flipMoveCount = result.guaranteedWin ? ((uint32_t)moveStateIndices.size() - guaranteedWinChildrenCount) : 0; allBranchResults[i] = result; return result; } void getAllSymmertricBoardSpaces(uint32_t COLOR_COUNT, uint32_t PIECE_COUNT) { state = {0}; std::unordered_map<std::vector<PartitionNumber>, uint32_t, PartitionHash> partitionToIdMap; std::vector<std::vector<PartitionNumber>> allPartitions; // essentially just the sum of ids std::vector<uint32_t> idPieceCounts; generatePartitionIdMaps(partitionToIdMap, allPartitions, idPieceCounts, PIECE_COUNT); std::vector<uint32_t> initialStates; std::vector<std::vector<uint32_t>> allGameStates; getAllGameStates(allGameStates, idPieceCounts, (uint32_t)allPartitions.size(), 0, COLOR_COUNT, PIECE_COUNT, {}, 0); std::unordered_map<std::vector<uint32_t>, uint32_t, GameStateHash> gameStateToIndexMap; gameStateToIndexMap.reserve(allGameStates.size()); { for (uint32_t i =0; i < allGameStates.size(); ++i) { gameStateToIndexMap.insert({ allGameStates[i], i }); } } // get initial states, { uint32_t i = 0; LOOP: for (;i < allGameStates.size(); ++i) { uint32_t c =0; for (uint32_t j = 0; j < allGameStates[i].size(); ++j) { std::vector<PartitionNumber> & part = allPartitions[allGameStates[i][j]]; if (part.size() != 1 || part[0].number != 1) { ++i; goto LOOP; } c += part[0].count; } if (c == PIECE_COUNT) { initialStates.push_back(i); } } } std::vector<std::vector<uint32_t>> allMoves; allMoves.reserve(allGameStates.size()); for (uint32_t i = 0; i < allGameStates.size(); ++i) { allMoves.push_back(getPossibleNextStates(allGameStates[i], allPartitions, partitionToIdMap, idPieceCounts, gameStateToIndexMap)); } std::vector<BranchResult> allBranchResults = std::vector<BranchResult>(allGameStates.size(), {0}); for (uint32_t i = 0; i < allGameStates.size(); ++i) { SolunaAlgorithm(i, allGameStates, allMoves, allBranchResults); } // TODO fix this copying here! state.COLOR_COUNT = COLOR_COUNT; state.PIECE_COUNT = PIECE_COUNT; state.allGameStates = allGameStates; state.allBranchResults = allBranchResults; state.initialStates = initialStates; state.allPartitions = allPartitions; state.allMoves = allMoves; state.gameStateToIndexMap = gameStateToIndexMap; state.partitionToIdMap = partitionToIdMap; } void partitionMultiSetDiff ( const std::vector<PartitionNumber> & from, const std::vector<PartitionNumber> & to, std::vector<PartitionNumber> & wRemove, std::vector<PartitionNumber> & wAdd ) { uint32_t l = 0, r = 0; while (from.size() != l || to.size() != r) { if (from.size() == l) { wAdd.push_back(to[r]); ++r; } else if (to.size() == r) { wRemove.push_back(from[l]); ++l; } else if (from[l].number != to[r].number) { if (from[l].number < to[r].number) { wRemove.push_back(from[l]); ++l; } else { wAdd.push_back(to[r]); ++r; } } else { if (from[l].count != to[r].count) { if (from[l].count < to[r].count) { wAdd.push_back({ from[l].number, to[r].count - from[l].count }); } else { wRemove.push_back({ from[l].number, from[l].count - to[r].count }); } } ++l; ++r; } } } uint32_t sumPartitionNumber(const std::vector<PartitionNumber> x) { uint32_t sum = 0; for (uint32_t i = 0; i < x.size(); ++i) { sum += x[i].number * x[i].count; } return sum; } struct ChangeDat { PartitionNumber pieceTop; PartitionNumber pieceBottom; uint32_t toPartition; uint32_t fromPartiton; bool samePartition; uint32_t toPartitionNew; uint32_t fromPartitionNew; bool twoChanges; }; uint32_t forward_reconstruction(uint32_t gameId, ChangeDat change) { std::vector<uint32_t> newGame; std::vector<uint32_t> game = state.allGameStates[gameId]; bool appliedTop = false; bool appliedBottom = false; PartitionNumber combinedPiece = {change.pieceTop.number + change.pieceBottom.number, 1}; for (uint32_t i = 0; i < game.size(); ++i) { std::vector<PartitionNumber> partiton; bool topPieceChange = !appliedTop && change.toPartition == game[i]; bool bottomPieceChange = (topPieceChange && change.samePartition) || (!appliedBottom && !topPieceChange && change.fromPartiton == game[i]); bool addedCombinedPiece = false; for (uint32_t j = 0; j < state.allPartitions[game[i]].size(); ++j) { PartitionNumber a = state.allPartitions[game[i]][j]; if (topPieceChange) { if (a.number == change.pieceTop.number) { --a.count; } else if (!addedCombinedPiece && a.number == combinedPiece.number) { ++a.count; addedCombinedPiece = true; } else if (!addedCombinedPiece && a.number > combinedPiece.number) { partiton.push_back(combinedPiece); addedCombinedPiece = true; } } if (bottomPieceChange) { if (a.number == change.pieceBottom.number) { --a.count; } } if (a.count > 0) { partiton.push_back(a); } } if (topPieceChange) appliedTop = true; if (bottomPieceChange) appliedBottom = true; if (topPieceChange && !addedCombinedPiece) { partiton.push_back(combinedPiece); } if (partiton.size() > 0) newGame.push_back(state.partitionToIdMap.at(partiton)); } std::sort(newGame.begin(), newGame.end()); return state.gameStateToIndexMap.at(newGame); } ChangeDat backward_reconstruction(uint32_t gameIdFrom, uint32_t gameIdTo) { std::vector<uint32_t> gameFrom = state.allGameStates[gameIdFrom]; std::vector<uint32_t> gameTo = state.allGameStates[gameIdTo]; // multiset diff, for two sorted ararys std::vector<uint32_t> remove; std::vector<uint32_t> add; uint32_t l = 0, r = 0; while (gameFrom.size() != l || gameTo.size() != r) { if (gameFrom.size() == l) { add.push_back(gameTo[r]); ++r; } else if (gameTo.size() == r) { remove.push_back(gameFrom[l]); ++l; } else if (gameFrom[l] != gameTo[r]) { if (gameFrom[l] < gameTo[r]) { remove.push_back(gameFrom[l]); ++l; } else { add.push_back(gameTo[r]); ++r; } } else { ++l; ++r; } } if (add.size() == 1 && remove.size() == 1) { std::vector<PartitionNumber> a; std::vector<PartitionNumber> b; partitionMultiSetDiff(state.allPartitions[remove[0]], state.allPartitions[add[0]], a, b); return { a[0], ((a.size() == 1) ? a[0] : a[1]), remove[0], remove[0], true, add[0], 0, false }; } else if (add.size() == 1 && remove.size() == 2) { uint32_t sum1 = sumPartitionNumber(state.allPartitions[remove[0]]); uint32_t sum2 = sumPartitionNumber(state.allPartitions[remove[1]]); std::vector<PartitionNumber> a; std::vector<PartitionNumber> b; // if sum1 == sum2 then there must be symmetry, since the piece comes from another color if (sum1 > sum2) { partitionMultiSetDiff(state.allPartitions[remove[0]], state.allPartitions[add[0]], a, b); return { a[0], state.allPartitions[remove[1]][0], remove[0], remove[1], false, add[0], 0, false }; } else { partitionMultiSetDiff(state.allPartitions[remove[1]], state.allPartitions[add[0]], a, b); return { a[0], state.allPartitions[remove[0]][0], remove[1], remove[0], false, add[0], 0, false }; } } else { int sumRemove1 = (int)sumPartitionNumber(state.allPartitions[remove[0]]); int sumRemove2 = (int)sumPartitionNumber(state.allPartitions[remove[1]]); int sumAdd1 = (int)sumPartitionNumber(state.allPartitions[add[0]]); int sumAdd2 = (int)sumPartitionNumber(state.allPartitions[add[1]]); int diff1 = (sumAdd1 - sumRemove1); int diff2 = (sumAdd2 - sumRemove2); std::vector<PartitionNumber> a; std::vector<PartitionNumber> b; std::vector<PartitionNumber> c; std::vector<PartitionNumber> d; partitionMultiSetDiff(state.allPartitions[remove[0]], state.allPartitions[add[0]], a, b); partitionMultiSetDiff(state.allPartitions[remove[1]], state.allPartitions[add[1]], c, d); if ( diff1 != 0 && diff1 == - diff2 && ( (a.size() == 1 && a[0].count == 1 && b.size() == 1 && b[0].count == 1 && d.size() == 0 && c.size() == 1 && c[0].count == 1 ) || (c.size() == 1 && c[0].count == 1 && d.size() == 1 && d[0].count == 1 && b.size() == 0 && a.size() == 1 && a[0].count == 1) ) ) { if (sumAdd1 > sumRemove1) { return { a[0], c[0], remove[0], remove[1], false, add[0], add[1], true }; } else { return { c[0], a[0], remove[1], remove[0], false, add[1], add[0], true }; } } else { a = std::vector<PartitionNumber>(); b = std::vector<PartitionNumber>(); c = std::vector<PartitionNumber>(); d = std::vector<PartitionNumber>(); partitionMultiSetDiff(state.allPartitions[remove[0]], state.allPartitions[add[1]], a, b); partitionMultiSetDiff(state.allPartitions[remove[1]], state.allPartitions[add[0]], c, d); if (sumAdd2 > sumRemove1) { return { a[0], c[0], remove[0], remove[1], false, add[1], add[0], true }; } else { return { c[0], a[0], remove[1], remove[0], false, add[0], add[1], true }; } } } } // API of webassembly #ifdef __cplusplus extern "C" { #endif bool calculateAllGameStates(uint32_t COLOR_COUNT, uint32_t PIECE_COUNT) { auto start = std::chrono::system_clock::now(); getAllSymmertricBoardSpaces(COLOR_COUNT, PIECE_COUNT); auto end = std::chrono::system_clock::now(); auto duration = (end - start); auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(); std::cout << millis << std::endl; return true; } PieceStack * getPartition(uint32_t id) { return state.allPartitions[id].data(); } uint32_t getPartitionCount(uint32_t id){ return (uint32_t)state.allPartitions[id].size(); } uint32_t * getGameState(uint32_t index) { return state.allGameStates[index].data(); } uint32_t getGameStateCount(uint32_t index) { return (uint32_t)state.allGameStates[index].size(); } uint32_t getBoardNextPossibleMovesCount(uint32_t index){ return (uint32_t)state.allMoves[index].size(); } uint32_t * getBoardNextPossibleMoves(uint32_t index) { return state.allMoves[index].data(); } BranchResult * getBoardBranchResult(uint32_t index) { return &state.allBranchResults[index]; } uint32_t * getInitialStates() { return state.initialStates.data(); } uint32_t getInitialStatesCount() { return (uint32_t)state.initialStates.size(); } ChangeDat DAT; ChangeDat * doBackwardReconstruction(uint32_t gameIndex, uint32_t moveGameIndex) { DAT = backward_reconstruction(gameIndex, moveGameIndex); return &DAT; } uint32_t doForwardReconstruction ( uint32_t gameIndex, uint32_t pieceTopNumber, uint32_t pieceTopCount, uint32_t pieceBottomNumber, uint32_t pieceBottomCount, uint32_t toPartition, uint32_t fromPartiton, bool samePartition ) { ChangeDat dat = { { pieceTopNumber, pieceTopCount }, { pieceBottomNumber, pieceBottomCount}, toPartition, fromPartiton, samePartition, 0, 0, false }; return forward_reconstruction(gameIndex, dat); } uint32_t getPartitionId (PartitionNumber *partitionData, uint32_t size) { std::vector<PartitionNumber> a = std::vector<PartitionNumber>(partitionData, partitionData + size); return state.partitionToIdMap.at(a); } #ifdef __cplusplus } #endif int main() { calculateAllGameStates(4, 12); // auto test22 = state.allGameStates[1002]; //// ChangeDat test223 = { //// {1,1}, //// {2,1}, //// //// } // auto aaa = forward_reconstruction(1002, backward_reconstruction(1002, 1007)); // ChangeDat test = { // {1,1}, // {1,1}, // 3, // 5, // false, // 0, // 0, // false // }; doForwardReconstruction(997, 1, 1, 1, 1, 3, 8, false); for (uint32_t i = 0; i < state.allGameStates.size(); ++i) { for (uint32_t j = 0; j < state.allMoves[i].size(); ++j) { if (i == 1002 && state.allMoves[i][j] == 1007) { auto test23 = state.allPartitions[5]; auto test22 = state.allGameStates[1007]; auto aaasdfasdf = 0; } ChangeDat dat = backward_reconstruction(i, state.allMoves[i][j]); assert(doForwardReconstruction(i, dat.pieceTop.number, dat.pieceTop.count, dat.pieceBottom.number, dat.pieceBottom.count, dat.toPartition, dat.fromPartiton, dat.samePartition) == state.allMoves[i][j]); assert(forward_reconstruction(i, dat) == state.allMoves[i][j]); { std::vector<uint32_t> remove; remove.push_back(dat.fromPartiton); if (!dat.samePartition) remove.push_back(dat.toPartition); std::vector<uint32_t> add; add.push_back(dat.toPartitionNew); if (dat.twoChanges) add.push_back(dat.fromPartitionNew); std::vector<uint32_t> newGameState = copyAndApplyPartitionIdChanges(state.allGameStates[i], remove, add); assert(state.gameStateToIndexMap.at(newGameState) == state.allMoves[i][j]); } } } return 0; }
37.281737
216
0.575734
[ "vector" ]
48b5e069d3a9a49cfef795c0ade66ab8163b04f0
8,110
hpp
C++
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/container/detail/pool_resource.hpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/container/detail/pool_resource.hpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/boost/1.69.0-r0/boost_1_69_0/boost/container/detail/pool_resource.hpp
sotaoverride/backup
ca53a10b72295387ef4948a9289cb78ab70bc449
[ "Apache-2.0" ]
null
null
null
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2015-2015. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/container for documentation. // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_CONTAINER_POOL_RESOURCE_HPP #define BOOST_CONTAINER_POOL_RESOURCE_HPP #if defined(_MSC_VER) #pragma once #endif #include <boost/container/detail/block_list.hpp> #include <boost/container/detail/config_begin.hpp> #include <boost/container/detail/workaround.hpp> #include <boost/container/pmr/memory_resource.hpp> #include <boost/container/pmr/pool_options.hpp> #include <cstddef> namespace boost { namespace container { namespace pmr { #if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED) class pool_data_t; static const std::size_t pool_options_minimum_max_blocks_per_chunk = 1u; static const std::size_t pool_options_default_max_blocks_per_chunk = 32u; static const std::size_t pool_options_minimum_largest_required_pool_block = memory_resource::max_align > 2 * sizeof(void*) ? memory_resource::max_align : 2 * sizeof(void*); static const std::size_t pool_options_default_largest_required_pool_block = pool_options_minimum_largest_required_pool_block > 4096u ? pool_options_minimum_largest_required_pool_block : 4096u; #endif // BOOST_CONTAINER_DOXYGEN_INVOKED class pool_resource { typedef block_list_base<> block_list_base_t; pool_options m_options; memory_resource& m_upstream; block_list_base_t m_oversized_list; pool_data_t* m_pool_data; std::size_t m_pool_count; static void priv_limit_option(std::size_t& val, std::size_t min, std::size_t max); static std::size_t priv_pool_index(std::size_t block_size); static std::size_t priv_pool_block(std::size_t index); void priv_fix_options(); void priv_init_pools(); void priv_constructor_body(); public: //! <b>Requires</b>: `upstream` is the address of a valid memory resource. //! //! <b>Effects</b>: Constructs a pool resource object that will obtain //! memory //! from upstream whenever the pool resource is unable to satisfy a memory //! request from its own internal data structures. The resulting object //! will hold a copy of upstream, but will not own the resource to which //! upstream points. [ Note: The intention is that calls to //! upstream->allocate() will be substantially fewer than calls to //! this->allocate() in most cases. - end note The behavior of the pooling //! mechanism is tuned according to the value of the opts argument. //! //! <b>Throws</b>: Nothing unless upstream->allocate() throws. It is //! unspecified if //! or under what conditions this constructor calls upstream->allocate(). pool_resource(const pool_options& opts, memory_resource* upstream) BOOST_NOEXCEPT; //! <b>Effects</b>: Same as //! `pool_resource(pool_options(), get_default_resource())`. pool_resource() BOOST_NOEXCEPT; //! <b>Effects</b>: Same as //! `pool_resource(pool_options(), upstream)`. explicit pool_resource(memory_resource* upstream) BOOST_NOEXCEPT; //! <b>Effects</b>: Same as //! `pool_resource(opts, get_default_resource())`. explicit pool_resource(const pool_options& opts) BOOST_NOEXCEPT; #if !defined(BOOST_NO_CXX11_DELETED_FUNCTIONS) || \ defined(BOOST_CONTAINER_DOXYGEN_INVOKED) pool_resource(const pool_resource&) = delete; pool_resource operator=(const pool_resource&) = delete; #else private: pool_resource(const pool_resource&); pool_resource operator=(const pool_resource&); public: #endif //! <b>Effects</b>: Calls //! `this->release()`. virtual ~pool_resource(); //! <b>Effects</b>: Calls Calls `upstream_resource()->deallocate()` as //! necessary //! to release all allocated memory. [ Note: memory is released back to //! `upstream_resource()` even if deallocate has not been called for some //! of the allocated blocks. - end note ] void release(); //! <b>Returns</b>: The value of the upstream argument provided to the //! constructor of this object. memory_resource* upstream_resource() const; //! <b>Returns</b>: The options that control the pooling behavior of this //! resource. //! The values in the returned struct may differ from those supplied to //! the pool resource constructor in that values of zero will be replaced //! with implementation-defined defaults and sizes may be rounded to //! unspecified granularity. pool_options options() const; public: // public so that [un]synchronized_pool_resource can use them //! <b>Returns</b>: A pointer to allocated storage with a size of at least //! `bytes`. //! The size and alignment of the allocated memory shall meet the //! requirements for a class derived from `memory_resource`. //! //! <b>Effects</b>: If the pool selected for a block of size bytes is unable //! to //! satisfy the memory request from its own internal data structures, it //! will call `upstream_resource()->allocate()` to obtain more memory. If //! `bytes` is larger than that which the largest pool can handle, then //! memory will be allocated using `upstream_resource()->allocate()`. //! //! <b>Throws</b>: Nothing unless `upstream_resource()->allocate()` throws. virtual void* do_allocate(std::size_t bytes, std::size_t alignment); //! <b>Effects</b>: Return the memory at p to the pool. It is unspecified if //! or under //! what circumstances this operation will result in a call to //! `upstream_resource()->deallocate()`. //! //! <b>Throws</b>: Nothing. virtual void do_deallocate(void* p, std::size_t bytes, std::size_t alignment); //! <b>Returns</b>: //! `this == dynamic_cast<const pool_resource*>(&other)`. virtual bool do_is_equal(const memory_resource& other) const BOOST_NOEXCEPT; // Non-standard observers public: //! <b>Returns</b>: The number of pools that will be used in the pool //! resource. //! //! <b>Note</b>: Non-standard extension. std::size_t pool_count() const; //! <b>Returns</b>: The index of the pool that will be used to serve the //! allocation of `bytes`. //! from the pool specified by `pool_index`. Returns `pool_count()` if //! `bytes` is bigger than `options().largest_required_pool_block` (no //! pool will be used to serve this). //! //! <b>Note</b>: Non-standard extension. std::size_t pool_index(std::size_t bytes) const; //! <b>Requires</b>: `pool_idx < pool_index()` //! //! <b>Returns</b>: The number blocks that will be allocated in the next //! chunk //! from the pool specified by `pool_idx`. //! //! <b>Note</b>: Non-standard extension. std::size_t pool_next_blocks_per_chunk(std::size_t pool_idx) const; //! <b>Requires</b>: `pool_idx < pool_index()` //! //! <b>Returns</b>: The number of bytes of the block that the specified //! `pool_idx` pool manages. //! //! <b>Note</b>: Non-standard extension. std::size_t pool_block(std::size_t pool_idx) const; //! <b>Requires</b>: `pool_idx < pool_index()` //! //! <b>Returns</b>: The number of blocks that the specified `pool_idx` pool //! has cached //! and will be served without calling the upstream_allocator. //! //! <b>Note</b>: Non-standard extension. std::size_t pool_cached_blocks(std::size_t pool_idx) const; }; } // namespace pmr } // namespace container } // namespace boost #include <boost/container/detail/config_end.hpp> #endif // BOOST_CONTAINER_POOL_RESOURCE_HPP
38.075117
80
0.661776
[ "object" ]
48bc102af7c156ac3b3abf4bf6019fc244dd52de
8,268
cpp
C++
HomeController/IRController.cpp
Yurik72/ESPHomeController
89561ee27c4e8d847dc1c3d6505dfc6436514a91
[ "MIT" ]
24
2019-03-02T20:21:15.000Z
2022-01-04T18:34:05.000Z
HomeController/IRController.cpp
Yurik72/ESPHomeController
89561ee27c4e8d847dc1c3d6505dfc6436514a91
[ "MIT" ]
null
null
null
HomeController/IRController.cpp
Yurik72/ESPHomeController
89561ee27c4e8d847dc1c3d6505dfc6436514a91
[ "MIT" ]
5
2019-09-20T10:11:22.000Z
2021-12-10T05:12:31.000Z
#include <Arduino.h> #include <ArduinoJson.h> #ifdef ESP32 #include <IRremote.h> #endif #ifdef ESP8266 #include <IRremoteESP8266.h> #include <IRrecv.h> #include <IRutils.h> #endif #include "config.h" #include "RCSwitch.h" #include "IRController.h" //REGISTER_CONTROLLER(RFController) #ifndef DISABLE_IR REGISTER_CONTROLLER_FACTORY(IRController) #endif const size_t bufferSize = JSON_OBJECT_SIZE(5); IRController::IRController() { this->pin = 0; this->pinsend = 0; #ifdef ESP8266 this->pReceiver = NULL; #endif this->store_recdata = true; } String IRController::serializestate() { DynamicJsonDocument jsonBuffer(bufferSize); JsonObject root = jsonBuffer.to<JsonObject>(); root["isReceive"] = this->get_state().isReceive; root["isSend"] = this->get_state().isSend; root["irtoken"] = this->get_state().irtoken; String json; json.reserve(64); serializeJson(root, json); return json; } bool IRController::deserializestate(String jsonstate, CmdSource src) { DynamicJsonDocument jsonBuffer(bufferSize); DeserializationError error = deserializeJson(jsonBuffer, jsonstate); if (error) { DBG_OUTPUT_PORT.print(FPSTR(szParseJsonFailText)); DBG_OUTPUT_PORT.println(this->get_name()); DBG_OUTPUT_PORT.println(error.c_str()); return false; } JsonObject root = jsonBuffer.as<JsonObject>(); IRState newState; //newState.isPressed = root["isPressed"]; // this->AddCommand(newState, Measure, src); //this->set_state(newState); return true; } void IRController::loadconfig(JsonObject& json) { IR::loadconfig(json); pin = json[FPSTR(szPinText)]; pinsend = json["sendpin"]; #ifdef RFCONTROLLER_DEBUG DBG_OUTPUT_PORT.println("RF loadconfig"); #endif load_persist(); } void IRController::getdefaultconfig(JsonObject& json) { json[FPSTR(szPinText)] = pin; json["pinsend"] = pinsend; json[FPSTR(szservice)] = "IRController"; json[FPSTR(szname)] = "IR"; IR::getdefaultconfig(json); } void IRController::setup() { IR::setup(); #ifdef ESP8266 this->pReceiver = new IRrecv(this->pin); this->pReceiver->enableIRIn(); #endif // this->pSwitch = new RCSwitch(); // this->pSwitch->enableReceive(this->pin); //pinMode(pin, INPUT); //digitalWrite(pin, LOW); } void IRController::run() { bool savepersist = false; #ifdef ESP8266 decode_results results; if (pReceiver->decode(&results)) { // print() & println() can't handle printing long longs. (uint64_t) command newcmd; newcmd.mode = IROnReceive; newcmd.state.irtoken = results.value; pReceiver->resume(); // Receive the next value this->AddCommand(newcmd.state, newcmd.mode, srcSelf); savepersist = this->store_recdata; } #endif command cmd; while (commands.Dequeue(&cmd)) { if (this->baseprocesscommands(cmd)) continue; if (cmd.mode == IRSend) { this->irsend(cmd.state); } if (cmd.mode == IRSaveReceive) { this->savepersist(cmd.state); continue; //state not changed } this->set_state(cmd.state); } if (savepersist) { ///will proceed next cycle this->AddCommand(cmd.state, IRSaveReceive, srcSelf); } } void IRController::savepersist(IRState psstate) { #ifdef IRCONTROLLER_DEBUG DBG_OUTPUT_PORT.println("IR savepersist"); #endif bool exist = false; for (int i = 0;i < this->persistdata.GetSize();i++) { if (this->persistdata.GetAt(i).token == psstate.irtoken) { exist = true; break; } } if (!exist) { #ifdef IRCONTROLLER_DEBUG DBG_OUTPUT_PORT.println("RF savepersist to file"); #endif IRData dt(psstate); String uname = String(millis()); strncpy(dt.name, uname.c_str(), IRDATANAME_MAXLEN); this->persistdata.Add(dt); this->saveperisttofile(); } } String IRController::getfilename_data() { String filename = "/"; filename += this->get_name(); filename += "_data.json"; return filename; } void IRController::load_persist() { #ifdef IRCONTROLLER_DEBUG DBG_OUTPUT_PORT.println("IR load_persist"); #endif String filedata = readfile(getfilename_data().c_str()); int capacity = JSON_ARRAY_SIZE(8) + 2 * JSON_OBJECT_SIZE(20) + 262; DynamicJsonDocument jsonBuffer(capacity); DeserializationError error = deserializeJson(jsonBuffer, filedata); if (error) { DBG_OUTPUT_PORT.print("RF load_persist error"); DBG_OUTPUT_PORT.println(error.c_str()); return; } JsonArray arr = jsonBuffer.as<JsonArray>(); for (int i = 0; i < arr.size(); i++) { IRData dt; const char * szName = arr[i][FPSTR(szname)].as<char*>(); strncpy(dt.name, szName, IRDATANAME_MAXLEN); dt.token = arr[i]["token"];; this->persistdata.Add(dt); } #ifdef IRCONTROLLER_DEBUG DBG_OUTPUT_PORT.print("IR persist loaded count->"); DBG_OUTPUT_PORT.println(this->persistdata.GetSize()); #endif } IRData IRController::deserializeIRData(String strdata) { const size_t jsonsize = JSON_OBJECT_SIZE(40); DynamicJsonDocument jsonBuffer(jsonsize); DeserializationError error = deserializeJson(jsonBuffer, strdata); if (error) { DBG_OUTPUT_PORT.print("deserializeIRData error"); DBG_OUTPUT_PORT.println(error.c_str()); IRData empty; return empty; } JsonObject json = jsonBuffer.as<JsonObject>(); return deserializeIRData(json); } IRData IRController::deserializeIRData(JsonObject& json) { IRData dt; const char * szName = json[FPSTR(szname)].as<char*>(); strncpy(dt.name, szName, IRDATANAME_MAXLEN); dt.token = json["token"];; return dt; } String IRController::serializeIRData(IRData data) { const size_t jsonsize = JSON_OBJECT_SIZE(40); DynamicJsonDocument jsonBuffer(jsonsize); JsonObject root = jsonBuffer.to<JsonObject>(); root["token"] = data.token; String json; json.reserve(40); serializeJson(root, json); return json; } String IRController::string_irdata() { const size_t jsonsize = JSON_ARRAY_SIZE(this->persistdata.GetSize() + 1) + this->persistdata.GetSize()*JSON_OBJECT_SIZE(40); DynamicJsonDocument jsonBuffer(jsonsize); JsonArray json = jsonBuffer.to<JsonArray>(); for (uint8_t i = 0; i < this->persistdata.GetSize(); i++) { JsonObject object = json.createNestedObject(); IRData dt = this->persistdata.GetAt(i); object[FPSTR(szname)] = dt.name; object["token"] = dt.token; } String json_str; json_str.reserve(2048); serializeJson(json, json_str); return json_str; } void IRController::saveperisttofile() { #ifdef IRCONTROLLER_DEBUG DBG_OUTPUT_PORT.println("IR saveperisttofile()"); DBG_OUTPUT_PORT.println(getfilename_data()); DBG_OUTPUT_PORT.println(this->string_rfdata()); #endif savefile(getfilename_data().c_str(), this->string_irdata()); } void IRController::irsend(IRState sendstate) { IRState tosend = sendstate; } IRData* IRController::getdata_byname(String& name) { for (int i = 0;i < this->persistdata.GetSize();i++) if (name == this->persistdata.GetAt(i).name) return &this->persistdata.GetAt(i); return NULL; } #if !defined ASYNC_WEBSERVER #if defined(ESP8266) void RFController::setuphandlers(ESP8266WebServer& server) { ESP8266WebServer* _server = &server; #else void RFController::setuphandlers(WebServer& server) { WebServer* _server = &server; #endif } #endif #if defined ASYNC_WEBSERVER void IRController::setuphandlers(AsyncWebServer& server) { String path = "/"; path += this->get_name(); path += String("/get_data"); IRController* self = this; server.on(path.c_str(), HTTP_GET, [self](AsyncWebServerRequest *request) { // DBG_OUTPUT_PORT.println("get modes request"); DBG_OUTPUT_PORT.println(ESP.getFreeHeap()); AsyncWebServerResponse *response = request->beginResponse(200, "application/json", self->string_irdata().c_str()); request->send(response); DBG_OUTPUT_PORT.println(ESP.getFreeHeap()); }); path = "/"; path += this->get_name(); path += String("/send"); server.on(path.c_str(), HTTP_GET, [self](AsyncWebServerRequest *request) { DBG_OUTPUT_PORT.println("IR Controller send"); if (!request->hasArg(FPSTR(szname))) return request->send(500, "text/plain", "BAD ARGS"); String name = request->arg(FPSTR(szname)); IRData* pData = self->getdata_byname(name); if (!pData) return request->send(500, "text/plain", "NOT EXIST"); command cmd; pData->SetState(cmd.state); cmd.state.isSend = true; self->AddCommand(cmd.state, IRSend, srcUserAction); AsyncWebServerResponse *response = request->beginResponse(200, "text/plain", name); request->send(response); }); } #endif
26.415335
125
0.723149
[ "object" ]
48bd887dbdda22aba70e29dbd38051458fa18a7c
7,983
hpp
C++
src/include/class_loader/constant_pool.hpp
claudiosegala/jvm
2e659c3e171283035fbac3ac7590b3afc9a96d9b
[ "MIT" ]
7
2018-04-24T12:15:04.000Z
2020-10-01T07:32:15.000Z
src/include/class_loader/constant_pool.hpp
claudiosegala/jvm
2e659c3e171283035fbac3ac7590b3afc9a96d9b
[ "MIT" ]
11
2018-05-05T18:53:15.000Z
2019-10-25T01:34:41.000Z
src/include/class_loader/constant_pool.hpp
claudiosegala/jvm
2e659c3e171283035fbac3ac7590b3afc9a96d9b
[ "MIT" ]
7
2018-05-05T20:15:47.000Z
2021-04-06T06:22:58.000Z
#pragma once #include "base.hpp" #include "util/reader.hpp" #include "util/JvmException.hpp" namespace jvm { enum CP_TAGS : uint8_t { Class = 7, FieldRef = 9, MethodRef = 10, InterfaceMethodRef = 11, String = 8, Integer = 3, Float = 4, Long = 5, Double = 6, NameAndType = 12, Utf8 = 1, MethodHandle = 15, MethodType = 16, InvokeDynamic = 18 }; class CP_Entry; /** * Stores all JVM constant pool fields. Exposes a set of functions to manipulate the field and print them. */ class ConstantPool : public std::vector<std::shared_ptr<CP_Entry>> { public: /** * Default ConstantPool's constructor */ ConstantPool(); /** * ConstantPool's constructor that calls the method fill, reading all of the cp entries * @param reader a reference to the class file reader * @param cp_count number of elements of the constant pool * @see fill() */ ConstantPool(Reader &reader, size_type cp_count); /** * Default ConstantPool's destructor */ ~ConstantPool(); /** * Fills this ConstantPool with it's entries * @param reader a reference to the class file reader * @param cp_count number of elements of the constant pool */ void fill(Reader &reader, size_type cp_count); /** * Prints this ConstantPool's entries to the console * @param os used to output data */ void printToStream(std::ostream& os); /** * */ CP_Entry* operator[](size_type index) ; bool shouldDebug = false; private: /** * Gets the next entry of the ConstantPool wich must be of the kind of the given tag * @param reader a reference to the class file reader * @param tag an identifyer of the cp_info's kind * @return Pointer to the next CP_Entry according to the given tag * @throw Exception when invalid tag's value */ std::shared_ptr<CP_Entry> getNextEntry(Reader &reader, uint8_t tag); }; /** * Converts entry to CP_Utf8 and prints it to os. * Throws exception if entry is not CP_Utf8 */ std::ostream& operator<< (std::ostream& os, CP_Entry& entry); class CP_Entry { public: virtual ~CP_Entry() = default; virtual CP_TAGS getTag() = 0; virtual void printToStream(std::ostream &os, jvm::ConstantPool &cp) = 0; virtual std::string toString(ConstantPool &cp) = 0; template<class T> T& as() { auto toReturn = dynamic_cast<T*>(this); if (toReturn == nullptr) { throw JvmException("Invalid CP_Entry cast"); } return *toReturn; } }; /** * CP_Class entry to the constant pool */ struct CP_Class final : public CP_Entry { explicit CP_Class(Reader& reader); CP_TAGS getTag() override; void printToStream(std::ostream &os, ConstantPool &cp) override; std::string toString(ConstantPool &cp) override; uint16_t name_index; }; /** * CP_Fieldref entry to the constant pool */ struct CP_Fieldref final : public CP_Entry { explicit CP_Fieldref(Reader& reader); ~CP_Fieldref() override = default; CP_TAGS getTag() override; void printToStream(std::ostream &os, ConstantPool &cp) override; std::string toString(ConstantPool &cp) override; uint16_t class_index; uint16_t name_and_type_index; }; /** * CP_Methodref entry to the constant pool */ struct CP_Methodref final : public CP_Entry { explicit CP_Methodref(Reader& reader); CP_TAGS getTag() override; void printToStream(std::ostream &os, ConstantPool &cp) override; std::string toString(ConstantPool &cp) override; uint16_t class_index; uint16_t name_and_type_index; }; /** * CP_InterfaceMethodref entry to the constant pool */ struct CP_InterfaceMethodref final : public CP_Entry { explicit CP_InterfaceMethodref(Reader& reader); CP_TAGS getTag() override; void printToStream(std::ostream &os, ConstantPool &cp) override; std::string toString(ConstantPool &cp) override; uint16_t class_index; uint16_t name_and_type_index; }; /** * CP_String entry to the constant pool */ struct CP_String final : public CP_Entry { explicit CP_String(Reader& reader); CP_TAGS getTag() override; void printToStream(std::ostream &os, ConstantPool &cp) override; std::string toString(ConstantPool &cp) override; uint16_t string_index; }; /** * CP_Integer entry to the constant pool */ struct CP_Integer final : public CP_Entry { explicit CP_Integer(Reader& reader); CP_TAGS getTag() override; void printToStream(std::ostream &os, ConstantPool &cp) override; std::string toString(ConstantPool &cp) override; uint32_t _bytes; }; /** * CP_Float entry to the constant pool */ struct CP_Float final : public CP_Entry { explicit CP_Float(Reader& reader); CP_TAGS getTag() override; void printToStream(std::ostream &os, ConstantPool &cp) override; std::string toString(ConstantPool &cp) override; uint32_t _bytes; }; /** * CP_Long entry to the constant pool */ struct CP_Long final : public CP_Entry { explicit CP_Long(Reader& reader); CP_TAGS getTag() override; void printToStream(std::ostream &os, ConstantPool &cp) override; std::string toString(ConstantPool &cp) override; uint32_t high_bytes; uint32_t low_bytes; }; /** * CP_Double entry to the constant pool */ struct CP_Double final : public CP_Entry { explicit CP_Double(Reader& reader); CP_TAGS getTag() override; void printToStream(std::ostream &os, ConstantPool &cp) override; std::string toString(ConstantPool &cp) override; uint32_t high_bytes; uint32_t low_bytes; }; /** * CP_NameAnsType entry to the constant pool */ struct CP_NameAndType final : public CP_Entry { explicit CP_NameAndType(Reader& reader); CP_TAGS getTag() override; void printToStream(std::ostream &os, ConstantPool &cp) override; std::string toString(ConstantPool &cp) override; uint16_t name_index; uint16_t descriptor_index; }; /** * CP_Utf8 entry to the constant pool */ struct CP_Utf8 final : public CP_Entry { explicit CP_Utf8(Reader& reader); ~CP_Utf8() override; CP_TAGS getTag() override; void printToStream(std::ostream &os, ConstantPool &cp) override; std::string toString() ; std::string toString(ConstantPool &cp) override; uint16_t _length; uint8_t *_bytes; }; std::ostream& operator<< (std::ostream&, CP_Utf8&); bool operator== (std::string&, CP_Utf8&); bool operator== (CP_Utf8&, std::string&); /** * CP_MethodHandle entry to the constant pool */ struct CP_MethodHandle final : public CP_Entry { explicit CP_MethodHandle(Reader& reader); CP_TAGS getTag() override; void printToStream(std::ostream &os, ConstantPool &cp) override; std::string toString(ConstantPool &cp) override; std::string get_ref(ConstantPool &cp); uint8_t reference_kind; uint16_t reference_index; }; /** * CP_MethodType entry to the constant pool */ struct CP_MethodType final : public CP_Entry { explicit CP_MethodType(Reader& reader); CP_TAGS getTag() override; void printToStream(std::ostream &os, ConstantPool &cp) override; std::string toString(ConstantPool &cp) override; uint16_t descriptor_index; }; /** * CP_InvokeDYnamic entry to the constant pool */ struct CP_InvokeDynamic final : public CP_Entry { explicit CP_InvokeDynamic(Reader& reader); CP_TAGS getTag() override; void printToStream(std::ostream &os, ConstantPool &cp) override; std::string toString(ConstantPool &cp) override; uint16_t bootstrap_method_attr_index; uint16_t name_and_type_index; }; }
22.74359
108
0.662032
[ "vector" ]
48c7ddc89728ab47eecc5fa1dba18bb8e251057e
2,304
ipp
C++
include/geo/sphere.ipp
snsinfu/geo
ec7d35ce07a778864e6818d6ca32ee1eaae4ae5c
[ "BSL-1.0" ]
null
null
null
include/geo/sphere.ipp
snsinfu/geo
ec7d35ce07a778864e6818d6ca32ee1eaae4ae5c
[ "BSL-1.0" ]
null
null
null
include/geo/sphere.ipp
snsinfu/geo
ec7d35ce07a778864e6818d6ca32ee1eaae4ae5c
[ "BSL-1.0" ]
null
null
null
// Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "assert.hpp" #include "box.hpp" #include "sphere.hpp" namespace geo { // Creation ------------------------------------------------------------ template<typename K> constexpr sphere<K>::sphere(point_type const& center, metric_type radius) : center_ {center} , squared_radius_ {radius * radius} { GEO_ASSERT(radius >= 0); } // Attributes ---------------------------------------------------------- template<typename K> constexpr auto sphere<K>::center() const noexcept -> point_type { return center_; } template<typename K> constexpr auto sphere<K>::squared_radius() const noexcept -> metric_type { return squared_radius_; } template<typename K> auto sphere<K>::radius() const noexcept -> metric_type { return K::sqrt(squared_radius_); } // Analytic query ------------------------------------------------------ template<typename K> constexpr auto sphere<K>::potential(point_type const& p) const noexcept -> metric_type { return squared_distance(p, center()) - squared_radius(); } template<typename K> constexpr auto sphere<K>::gradient(point_type const& p) const noexcept -> vector_type { return scalar_type(2) * (p - center()); } template<typename K> constexpr auto sphere<K>::oriented_distance(point_type const& p) const noexcept -> metric_type { return distance(p, center()) - radius(); } template<typename K> constexpr auto sphere<K>::skin_map(point_type const& p) const noexcept -> scaling_type { return scalar_type(1) - radius() / distance(p, center()); } // Basic algorithms -------------------------------------------------------- template<typename K> box<K> bounding_box(sphere<K> const& s) noexcept { vector<K> semi_diagonal; auto const radius = s.radius(); for (auto& e : semi_diagonal) { e = radius; } return box<K>{s.center() - semi_diagonal, s.center() + semi_diagonal}; } }
26.482759
88
0.552517
[ "vector" ]
48ca115bd2d9277878c207e20e0747637ddf2085
1,069
cpp
C++
cannon/graphics/light_collection.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
null
null
null
cannon/graphics/light_collection.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
46
2021-01-12T23:03:52.000Z
2021-10-01T17:29:01.000Z
cannon/graphics/light_collection.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
null
null
null
#include <cannon/graphics/light_collection.hpp> #include <cannon/graphics/shader_program.hpp> using namespace cannon::graphics; void LightCollection::apply(std::shared_ptr<geometry::DrawableGeom> g) const { g->program->set_uniform("num_point_lights", (int)point_lights_.size()); g->program->set_uniform("num_spotlights", (int)spotlights_.size()); for (unsigned int i = 0; i < point_lights_.size(); i++) { point_lights_[i]->apply(g, i); } for (unsigned int i = 0; i < spotlights_.size(); i++) { spotlights_[i]->apply(g, i); } if (directional_light_) directional_light_->apply(g); } void LightCollection::apply(std::shared_ptr<ShaderProgram> s) const { s->set_uniform("num_point_lights", (int)point_lights_.size()); s->set_uniform("num_spotlights", (int)spotlights_.size()); for (unsigned int i = 0; i < point_lights_.size(); i++) { point_lights_[i]->apply(s, i); } for (unsigned int i = 0; i < spotlights_.size(); i++) { spotlights_[i]->apply(s, i); } if (directional_light_) directional_light_->apply(s); }
28.131579
78
0.680075
[ "geometry" ]
48d27d643ee300d812f5e1e5ce7cfa1dff5b6a0b
1,367
hpp
C++
include/ny/wayland/bufferSurface.hpp
nyorain/ny
9349a6f668a9458d3a37b76bb3cd1e5c679d16ad
[ "BSL-1.0" ]
18
2015-12-14T09:04:06.000Z
2021-11-14T20:38:17.000Z
include/ny/wayland/bufferSurface.hpp
nyorain/ny
9349a6f668a9458d3a37b76bb3cd1e5c679d16ad
[ "BSL-1.0" ]
2
2015-06-26T09:26:05.000Z
2019-04-02T09:05:12.000Z
include/ny/wayland/bufferSurface.hpp
nyorain/ny
9349a6f668a9458d3a37b76bb3cd1e5c679d16ad
[ "BSL-1.0" ]
2
2017-08-23T06:04:26.000Z
2019-11-27T01:48:02.000Z
// Copyright (c) 2015-2018 nyorain // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt #pragma once #include <ny/wayland/include.hpp> #include <ny/wayland/windowContext.hpp> #include <ny/bufferSurface.hpp> #include <nytl/vec.hpp> #include <nytl/nonCopyable.hpp> #include <vector> namespace ny { /// Wayland BufferSurface implementation. class WaylandBufferSurface : public nytl::NonCopyable, public BufferSurface { public: WaylandBufferSurface(WaylandWindowContext&); ~WaylandBufferSurface(); BufferGuard buffer() override; void apply(const BufferGuard&) noexcept override; WaylandWindowContext& windowContext() const { return *windowContext_; } const std::vector<wayland::ShmBuffer>& shmBuffers() const { return buffers_; } wayland::ShmBuffer* active() const { return active_; } protected: WaylandWindowContext* windowContext_ {}; std::vector<wayland::ShmBuffer> buffers_; wayland::ShmBuffer* active_ {}; }; /// WaylandWindowContext for a BufferSurface. class WaylandBufferWindowContext : public WaylandWindowContext { public: WaylandBufferWindowContext(WaylandAppContext&, const WaylandWindowSettings& = {}); ~WaylandBufferWindowContext() = default; Surface surface() override; protected: WaylandBufferSurface bufferSurface_; }; } // namespace ny
27.34
83
0.775421
[ "vector" ]
48d3c317dace4da20f87c557d37242959a3c9889
3,799
cpp
C++
resources/ModelImporter.cpp
ibequa/flexo
93b9b1287f33bd3420e33bf4a7bc5961d680b5e1
[ "MIT" ]
null
null
null
resources/ModelImporter.cpp
ibequa/flexo
93b9b1287f33bd3420e33bf4a7bc5961d680b5e1
[ "MIT" ]
null
null
null
resources/ModelImporter.cpp
ibequa/flexo
93b9b1287f33bd3420e33bf4a7bc5961d680b5e1
[ "MIT" ]
null
null
null
// // ModelImporter.cpp // Flexo // // Created by Ilya on 06/05/16. // Copyright © 2016 Flexo. All rights reserved. // #include <assert.h> #include <OpenGL/gltypes.h> #include <assimp/Importer.hpp> #include <assimp/postprocess.h> #include "ModelImporter.hpp" #include "MaterialInfoImported.hpp" #include "DefaultMaterial.hpp" #define copy_v_attr3(v_attr, aiV_attr) v.v_attr[0] = meshAi->aiV_attr[i].x; \ v.v_attr[1] = meshAi->aiV_attr[i].y; \ v.v_attr[2] = meshAi->aiV_attr[i].z #define get_ai_prop(key, out) scene->mMaterials[mat_id]->Get(key, out) #define ai2arr(ai, a) mesh->_materialInfoImported_->a[0] = ai.r; \ mesh->_materialInfoImported_->a[1] = ai.g; \ mesh->_materialInfoImported_->a[2] = ai.b ModelImporter& ModelImporter::instance() { static ModelImporter _modelImporter; return _modelImporter; } const ModelResource& ModelImporter::import(const_str& path) { Assimp::Importer importer; const aiScene* scene = importer.ReadFile(path.c_str(), aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenNormals | aiProcess_OptimizeMeshes); assert (scene && (scene->mFlags != AI_SCENE_FLAGS_INCOMPLETE) && scene->mRootNode); ModelResource& model = addResource(path); processNode(scene->mRootNode, scene, model); return model; } void ModelImporter::processNode(const aiNode* node, const aiScene* scene, ModelResource& model) { for (size_t i = 0; i < node->mNumMeshes; i++) { aiMesh* meshAi = scene->mMeshes[node->mMeshes[i]]; Mesh& mesh = model.addMesh(meshAi->mName.C_Str()); processMesh(meshAi, mesh, scene); } for (GLuint i = 0; i < node->mNumChildren; i++) processNode(node->mChildren[i], scene, model); } void ModelImporter::processMesh(const aiMesh* meshAi, Mesh& mesh, const aiScene* scene) { // VERTEX DATA for (GLuint i = 0; i < meshAi->mNumVertices; i++) { Vertex v; copy_v_attr3(position, mVertices); copy_v_attr3(normal, mNormals); if (meshAi->HasTextureCoords(0)) { v.uv[0] = meshAi->mTextureCoords[0][i].x; v.uv[1] = meshAi->mTextureCoords[0][i].y; } if (meshAi->HasTangentsAndBitangents()) { copy_v_attr3(tangent, mTangents); copy_v_attr3(bitangent, mBitangents); } mesh.addVertex(v); } // // INDICES for (GLuint i = 0; i < meshAi->mNumFaces; i++) { aiFace face = meshAi->mFaces[i]; for (GLuint j = 0; j < face.mNumIndices; j++) mesh.addIndex(face.mIndices[j]); } // // MATERIALS // import colors and textures and pass to default material: addMaterial(DefaultMaterial, "vertsh", "fragsh", imported stuff) /*unsigned int mat_id = meshAi->mMaterialIndex; if (mat_id > 0) { mesh->_materialInfoImported_ = new MaterialInfoImported; aiColor3D aiAmbient, aiDiffuse, aiSpecular, aiEmission, aiTransparent; get_ai_prop(AI_MATKEY_COLOR_AMBIENT, aiAmbient); get_ai_prop(AI_MATKEY_COLOR_DIFFUSE, aiDiffuse); get_ai_prop(AI_MATKEY_COLOR_SPECULAR, aiSpecular); get_ai_prop(AI_MATKEY_COLOR_EMISSIVE, aiEmission); get_ai_prop(AI_MATKEY_COLOR_TRANSPARENT, aiTransparent); get_ai_prop(AI_MATKEY_SHININESS, mesh->_materialInfoImported_->shininess); get_ai_prop(AI_MATKEY_SHININESS_STRENGTH, mesh->_materialInfoImported_->shininessStrength); ai2arr(aiAmbient, ambient); ai2arr(aiDiffuse, diffuse); ai2arr(aiSpecular, specular); ai2arr(aiTransparent, transparent); ai2arr(aiEmission, emission); } */ // }
36.180952
152
0.637273
[ "mesh", "model" ]
48d4b5350aab0a39d59907232849180456b3bdd9
1,139
cpp
C++
Source/FpsFramework/CMagazine.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
3
2019-04-12T15:22:53.000Z
2022-01-05T02:59:56.000Z
Source/FpsFramework/CMagazine.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
null
null
null
Source/FpsFramework/CMagazine.cpp
shanefarris/CoreGameEngine
5bef275d1cd4e84aa059f2f4f9e97bfa2414d000
[ "MIT" ]
2
2019-04-10T22:46:21.000Z
2020-05-27T16:21:37.000Z
#include "CMagazine.h" #include "CProjectile.h" using namespace Core; CMagazine::CMagazine(const CMagazineProfile& Profile, CWeapon* Weapon) : m_Node(nullptr), m_Entity(nullptr), m_Weapon(Weapon), m_Profile(Profile) { m_Count = Profile.Capacity; // TODO: make dynamic (could pick up on the field and half of the rounds were spent) } CMagazine::~CMagazine() { for(auto it = m_Projectiles.begin(); it != m_Projectiles.end(); it++) CORE_DELETE((*it)); m_Projectiles.erase(m_Projectiles.begin(), m_Projectiles.end()); } bool CMagazine::Fire(CPlayer* Player, const Vector3& Direction) { if(m_Count > 0) { //m_Count--; CProjectile* projectile = new CProjectile(m_Profile.ProjectileProfile, m_Weapon); projectile->Shoot(Player, Direction); m_Projectiles.push_back(projectile); return true; } return false; } void CMagazine::RemoveProjectile(CProjectile* Projectile) { auto it = find(m_Projectiles.cbegin(), m_Projectiles.cend(), Projectile); if(it != m_Projectiles.cend()) { m_Projectiles.erase(it); CORE_DELETE(Projectile); } } Vector<CProjectile*>& CMagazine::GetProjectiles() { return m_Projectiles; }
23.244898
113
0.731343
[ "vector" ]
48d6ba4836e46c6742cf024fe734330abbed8fd0
1,367
cpp
C++
test/test-oeconvert.cpp
orbitalVelocity/orbitutils
06ad5ca39c091542a017494e8c6cbbde039d4ac0
[ "MIT" ]
null
null
null
test/test-oeconvert.cpp
orbitalVelocity/orbitutils
06ad5ca39c091542a017494e8c6cbbde039d4ac0
[ "MIT" ]
null
null
null
test/test-oeconvert.cpp
orbitalVelocity/orbitutils
06ad5ca39c091542a017494e8c6cbbde039d4ac0
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include "orbitalelements.h" #include "oeconvert.h" int main() { double grav_param = 2; std::vector<double> rv0(6); rv0[0] = 10; rv0[1] = 2; rv0[2] = 3; rv0[3] = 0.01; rv0[4] = 0.3; rv0[5] = 0.05; OrbitalElements oe0; oe0.sma = 7.04909391142183; oe0.ecc = 0.5561545963072888; oe0.inc = 17.294397104279813 / 180.0 * M_PI; oe0.lan = 300.4342357534433 / 180.0 * M_PI; oe0.aop = 264.641995659073 / 180.0 * M_PI; oe0.tra = 167.0393678503284 / 180.0 * M_PI; OrbitalElements oe = rv2oe(grav_param,rv0); fprintf(stdout,"sma error: %g\n",(oe.sma-oe0.sma)/oe0.sma); fprintf(stdout,"ecc error: %g\n",(oe.ecc-oe0.ecc)/oe0.ecc); fprintf(stdout,"inc error: %g\n",(oe.inc-oe0.inc)/oe0.inc); fprintf(stdout,"lan error: %g\n",(oe.lan-oe0.lan)/oe0.lan); fprintf(stdout,"aop error: %g\n",(oe.aop-oe0.aop)/oe0.aop); fprintf(stdout,"tra error: %g\n",(oe.tra-oe0.tra)/oe0.tra); std::vector<double> rv = oe2rv(grav_param,oe); fprintf(stdout,"rv[0] error: %g\n",(rv[0]-rv0[0])/rv0[0]); fprintf(stdout,"rv[1] error: %g\n",(rv[1]-rv0[1])/rv0[1]); fprintf(stdout,"rv[2] error: %g\n",(rv[2]-rv0[2])/rv0[2]); fprintf(stdout,"rv[3] error: %g\n",(rv[3]-rv0[3])/rv0[3]); fprintf(stdout,"rv[4] error: %g\n",(rv[4]-rv0[4])/rv0[4]); fprintf(stdout,"rv[5] error: %g\n",(rv[5]-rv0[5])/rv0[5]); }
31.790698
62
0.623263
[ "vector" ]
48d6baf1af73cfec388f0afcb95e6cc6ee61e4fd
4,600
hpp
C++
sparta/sparta/statistics/BasicHistogram.hpp
debjyoti0891/map
abdae67964420d7d36255dcbf83e4240a1ef4295
[ "MIT" ]
44
2019-12-13T06:39:13.000Z
2022-03-29T23:09:28.000Z
sparta/sparta/statistics/BasicHistogram.hpp
debjyoti0891/map
abdae67964420d7d36255dcbf83e4240a1ef4295
[ "MIT" ]
222
2020-01-14T21:58:56.000Z
2022-03-31T20:05:12.000Z
sparta/sparta/statistics/BasicHistogram.hpp
debjyoti0891/map
abdae67964420d7d36255dcbf83e4240a1ef4295
[ "MIT" ]
19
2020-01-03T19:03:22.000Z
2022-01-09T08:36:20.000Z
// <BasicHistogram.h> -*- C++ -*- /** * \file BasicHistogram.hpp * \brief A simple histogram with programmable ranges, using sparta::Counters */ #pragma once #include <string> #include <vector> #include <sstream> #include "sparta/statistics/Counter.hpp" namespace sparta { /** * \class BasicHistogram * \tparam BucketT Type contained in the buckets * \tparam ASSERT_ON_UNDERFLOW (default false) true will assert if an underflow is detected * * This class will create sparta::Counters for each "bucket" of BucketT * given in the contructor * * The objects contained in the buckets must follow these rules: * # The object type must be copyable (for initialization) * # The object must respond to the comparison operator== and operator< operator> * * A "bucket" is charged a count if an object being added is less than * the given bucket. Examples: * * \code * sparta::BasicHistogram<int> example_bh(sset_, "example_bh", "Example BasicHistogram", {0,10,20}); * example_bh.addValue(-1); // Will add a charge to the 0 -> 10 bucket * example_bh.addValue( 1); // Will add a charge to the 0 -> 10 bucket * example_bh.addValue(10); // Will add a charge to the 0 -> 10 bucket * example_bh.addValue(11); // Will add a charge to the 10 -> 20 bucket * example_bh.addValue(20); // Will add a charge to the 10 -> 20 bucket * example_bh.addValue(21); // Will add a charge to the 10 -> 20 bucket * \endcode */ template<typename BucketT, bool ASSERT_ON_UNDERFLOW=false> class BasicHistogram { public: /** * \brief Construct a BasicHistogram * \param sset The sparta::StatisticSet this histogram belongs to * \param name The name of thie BasicHistogram * \param desc A useful description * \param buckets one bucket will be created per value (plus one for overflow) - values must be sorted */ BasicHistogram(sparta::StatisticSet &sset, const std::string &name, const std::string &desc, const std::vector<BucketT> &buckets) : bucket_vals_(buckets) { sparta_assert(std::is_sorted(buckets.begin(), buckets.end()), "Buckets must be sorted"); const auto bucket_size = bucket_vals_.size(); ctrs_.reserve(bucket_size); // create one counter per bucket for (unsigned i = 0; i < bucket_size; ++i) { auto &v = bucket_vals_[i]; std::ostringstream os_name; if (v < 0) os_name << name << "_n" << -v; // negative else os_name << name << '_' << v; std::ostringstream os_desc; if (i == 0) { os_desc << desc << " with values less than or equal to " << v; } else { os_desc << desc << " with values greater than " << bucket_vals_[i-1] << " and less than or equal to " << v; } ctrs_.emplace_back(&sset, os_name.str(), os_desc.str(), sparta::Counter::COUNT_NORMAL); } } /// Destroy, non-virtual ~BasicHistogram() {} /** * \brief Charge a bucket where the given val falls * \param val The value to charge * * A "bucket" is charged a count if an object being added is less * than the given bucket. Overflows will go into the last bucket. * Undeflows will either assert or charge to the smallest bucket * (depending on class template parameter ASSERT_ON_UNDERFLOW) */ void addValue(const BucketT &val) { // upper_bound will yield the bucket beyond the one we want auto bucket = std::upper_bound(bucket_vals_.begin(), bucket_vals_.end(), val); // check for underflow (value below first bucket) if (bucket == bucket_vals_.begin()) { sparta_assert(!ASSERT_ON_UNDERFLOW, "Value below first bucket"); ++ctrs_[0]; // put underflow in first bucket return; } //else calculate offset into counter array auto off = bucket - bucket_vals_.begin() - 1; ++ctrs_[off]; } /// Disallow copies/assignment/move BasicHistogram(const BasicHistogram &) = delete; BasicHistogram( BasicHistogram &&) = delete; const BasicHistogram & operator=(const BasicHistogram &) = delete; BasicHistogram & operator=( BasicHistogram &&) = delete; private: // data std::vector<BucketT> bucket_vals_; ///< user-specified buckets std::vector<sparta::Counter> ctrs_; ///< one counter per bucket }; } // namespace sparta
36.220472
123
0.621522
[ "object", "vector" ]
48e328eac0451f2c2519c8277a4d6359312f5af7
8,243
cc
C++
alljoyn/services/time/cpp/src/common/TimeServiceTimerUtility.cc
octoblu/alljoyn
a74003fa25af1d0790468bf781a4d49347ec05c4
[ "ISC" ]
37
2015-01-18T21:27:23.000Z
2018-01-12T00:33:43.000Z
alljoyn/services/time/cpp/src/common/TimeServiceTimerUtility.cc
octoblu/alljoyn
a74003fa25af1d0790468bf781a4d49347ec05c4
[ "ISC" ]
14
2015-02-24T11:44:01.000Z
2020-07-20T18:48:44.000Z
alljoyn/services/time/cpp/src/common/TimeServiceTimerUtility.cc
octoblu/alljoyn
a74003fa25af1d0790468bf781a4d49347ec05c4
[ "ISC" ]
29
2015-01-23T16:40:52.000Z
2019-10-21T12:22:30.000Z
/****************************************************************************** * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ #include "TimeServiceTimerUtility.h" #include <alljoyn/time/LogModule.h> #include <alljoyn/time/TimeServiceTime.h> #include "TimeServiceUtility.h" using namespace ajn; using namespace services; using namespace tsTimerUtility; //Create Timer interface QStatus tsTimerUtility::createInterface(BusAttachment* bus, InterfaceDescription** ptrIfaceDesc) { QStatus status; status = tsUtility::createAJInterface(tsConsts::TIMER_IFACE, false, IFACE_PROP_VERSION, bus, ptrIfaceDesc); if (status != ER_OK) { return status; } (*ptrIfaceDesc)->SetDescriptionLanguage(IFACE_DESCRIPTION_LAGN.c_str()); (*ptrIfaceDesc)->SetDescription(IFACE_DESCRIPTION.c_str()); //Add Interval property status = (*ptrIfaceDesc)->AddProperty(IFACE_PROP_INTERVAL.c_str(), "(uyyq)", PROP_ACCESS_RW); if (status != ER_OK) { return status; } //Add Title property status = (*ptrIfaceDesc)->AddProperty(IFACE_PROP_TITLE.c_str(), "s", PROP_ACCESS_RW); if (status != ER_OK) { return status; } //Add TimeLeft property status = (*ptrIfaceDesc)->AddProperty(IFACE_PROP_TIMELEFT.c_str(), "(uyyq)", PROP_ACCESS_READ); if (status != ER_OK) { return status; } //Add IsRunning property status = (*ptrIfaceDesc)->AddProperty(IFACE_PROP_ISRUNNING.c_str(), "b", PROP_ACCESS_READ); if (status != ER_OK) { return status; } //Add Repeat property status = (*ptrIfaceDesc)->AddProperty(IFACE_PROP_REPEAT.c_str(), "q", PROP_ACCESS_RW); if (status != ER_OK) { return status; } //Add Start method status = (*ptrIfaceDesc)->AddMethod(IFACE_METHOD_START.c_str(), NULL, NULL, NULL); if (status != ER_OK) { return status; } status = (*ptrIfaceDesc)->AddMemberAnnotation(IFACE_METHOD_START.c_str(), org::freedesktop::DBus::AnnotateNoReply, "true"); if (status != ER_OK) { return status; } //Add Pause method status = (*ptrIfaceDesc)->AddMethod(IFACE_METHOD_PAUSE.c_str(), NULL, NULL, NULL); if (status != ER_OK) { return status; } status = (*ptrIfaceDesc)->AddMemberAnnotation(IFACE_METHOD_PAUSE.c_str(), org::freedesktop::DBus::AnnotateNoReply, "true"); if (status != ER_OK) { return status; } //Add Reset method status = (*ptrIfaceDesc)->AddMethod(IFACE_METHOD_RESET.c_str(), NULL, NULL, NULL); if (status != ER_OK) { return status; } //Add Timer Run state changed signal status = (*ptrIfaceDesc)->AddSignal(IFACE_SIG_TIMER_RUNSTATECHANGED.c_str(), "b", NULL); if (status != ER_OK) { return status; } //Add Timer event changed signal status = (*ptrIfaceDesc)->AddSignal(IFACE_SIG_TIMER_EVENT.c_str(), NULL, NULL); if (status != ER_OK) { return status; } //Set description of the TimerEvent signal status = (*ptrIfaceDesc)->SetMemberDescription(IFACE_SIG_TIMER_EVENT.c_str(), IFACE_SIG_TIMER_EVENT_DESC.c_str(), true); if (status != ER_OK) { return status; } (*ptrIfaceDesc)->Activate(); return status; } //Unmarshal Period QStatus tsTimerUtility::unmarshalPeriod(const MsgArg& msgArg, TimeServicePeriod* period) { uint32_t hour; uint8_t minute; uint8_t second; uint16_t millisecond; QStatus status = msgArg.Get("(uyyq)", &hour, &minute, &second, &millisecond); if (status != ER_OK) { QCC_LogError(status, (("Failed to unmarshal interval property"))); return status; } status = period->init(hour, minute, second, millisecond); if (status != ER_OK) { QCC_LogError(status, (("Failed to initialize Period object"))); return status; } return status; } //Marshal Period QStatus tsTimerUtility::marshalPeriod(MsgArg& msgArg, const TimeServicePeriod& period) { QStatus status = msgArg.Set("(uyyq)", period.getHour(), period.getMinute(), period.getSecond(), period.getMillisecond()); if (status != ER_OK) { QCC_LogError(status, (("Failed to marshal Period object"))); return status; } return status; } //Unmarshal title QStatus tsTimerUtility::unmarshalTitle(const MsgArg& msgArg, qcc::String* title) { char* titleStr; QStatus status = msgArg.Get("s", &titleStr); if (status != ER_OK) { QCC_LogError(status, (("Failed to unmarshal Title"))); return status; } title->assign(titleStr); return status; } //Marshal Title QStatus tsTimerUtility::marshalTitle(MsgArg& msgArg, const qcc::String& title) { QStatus status = msgArg.Set("s", title.c_str()); if (status != ER_OK) { QCC_LogError(status, (("Failed to marshal Title"))); return status; } return status; } // Unmarshal IsRunning property QStatus tsTimerUtility::unmarshalBoolean(const MsgArg& msgArg, bool* ret) { QStatus status = msgArg.Get("b", ret); if (status != ER_OK) { QCC_LogError(status, (("Failed to unmarshal IsRunning"))); return status; } return status; } // Marshal IsRunning property QStatus tsTimerUtility::marshalBoolean(MsgArg& msgArg, const bool input) { QStatus status = msgArg.Set("b", input); if (status != ER_OK) { QCC_LogError(status, (("Failed to marshal IsRunning"))); return status; } return status; } // Unmarshal Repeat property QStatus tsTimerUtility::unmarshalRepeat(const MsgArg& msgArg, uint16_t* repeat) { QStatus status = msgArg.Get("q", repeat); if (status != ER_OK) { QCC_LogError(status, (("Failed to unmarshal Repeat"))); return status; } return status; } // Marshal Repeat property QStatus tsTimerUtility::marshalRepeat(MsgArg& msgArg, const uint16_t repeat) { QStatus status = msgArg.Set("q", repeat); if (status != ER_OK) { QCC_LogError(status, (("Failed to marshal Repeat"))); return status; } return status; } //Create Timerfactory interface QStatus tsTimerUtility::createFactoryInterface(BusAttachment* bus, InterfaceDescription** ptrIfaceDesc) { QStatus status; status = tsUtility::createAJInterface(tsConsts::TIMER_FACTORY_IFACE, true, IFACE_FAC_PROP_VERSION, bus, ptrIfaceDesc); if (status != ER_OK) { return status; } status = (*ptrIfaceDesc)->AddMethod(IFACE_FAC_METHOD_NEW_TIMER.c_str(), NULL, "o", "Object Path"); if (status != ER_OK) { return status; } status = (*ptrIfaceDesc)->AddMethod(IFACE_FAC_METHOD_DELETE_TIMER.c_str(), "o", NULL, "Object Path"); if (status != ER_OK) { return status; } (*ptrIfaceDesc)->Activate(); return status; } //Marshal object path QStatus tsTimerUtility::marshalObjectPath(MsgArg& msgArg, const qcc::String& objPath) { QStatus status = msgArg.Set("o", objPath.c_str()); return status; } //Unmarshal object path QStatus tsTimerUtility::unmarshalObjectPath(const MsgArg& msgArg, qcc::String* objPath) { char* objPathChrs; QStatus status = msgArg.Get("o", &objPathChrs); if (status != ER_OK) { QCC_LogError(status, (("Failed to unmarshal Object Path"))); return status; } objPath->assign(objPathChrs); return status; }
24.387574
127
0.652432
[ "object" ]
48e360a927b403f4c8e7ea155b2e0d3a6e492767
7,649
hpp
C++
ppmToBmp.hpp
PhilipNelson5/utils
03446cae6278b8fe1e835b28b6bfaf81ed891db2
[ "MIT" ]
null
null
null
ppmToBmp.hpp
PhilipNelson5/utils
03446cae6278b8fe1e835b28b6bfaf81ed891db2
[ "MIT" ]
null
null
null
ppmToBmp.hpp
PhilipNelson5/utils
03446cae6278b8fe1e835b28b6bfaf81ed891db2
[ "MIT" ]
null
null
null
#ifndef PPM_TO_BMP_HPP #define PPM_TO_BMP_HPP #include <cstdint> #include <fstream> #include <iostream> #include <string> #include <vector> /** * @author Bryan Hansen * @author Erik Falor * @author Philip Nelson * @date 10/9/2017 * * @history * 10/16/17 Fixed padding in generated BMP for non-word aligned sizes * 10/31/17 Fixed BMP files store rows of pixels from bottom-to-top * 09/26/18 Now converts a vector of iteration data * instead of reading from a file. A color_scheme function is * passed in to turn the raw iterations into [r,g,b] colors */ namespace stayOffMyLawn { /** * Writes the standard BMP header to the provided file * @param bmpFile File stream to which the header will be written * @param width The width of the PPM file in pixels * @param height The height of the PPM file in pixels */ void writeBmpHeader(std::ofstream& bmpFile, int width, int height) { // BMP header (14 bytes) // A two character signature to indicate the file is a bitmap file // (typically “BM”). A 32bit unsigned little-endian integer representing the // size of the file itself. A pair of 16bit unsigned little-endian integers // reserved for application specific uses. A 32bit unsigned little-endian // integer representing the offset to where the pixel array starts in the // file. const uint32_t HEADER_SIZE_BYTES = 54; const uint32_t BYTES_PER_PIXEL = 3; uint32_t padBytes = 0; if ((width * BYTES_PER_PIXEL) % sizeof(uint32_t) != 0) { padBytes = sizeof(uint32_t) - ((width * BYTES_PER_PIXEL) % sizeof(uint32_t)); } const uint32_t paddedWidthBytes = (width * BYTES_PER_PIXEL) + padBytes; const uint32_t totalSize = HEADER_SIZE_BYTES + (height * paddedWidthBytes); const char sigOne = 'B'; const char sigTwo = 'M'; const uint16_t reserved = 0; const uint32_t pixelOffset = HEADER_SIZE_BYTES; /* clang-format off */ bmpFile.write(&sigOne, sizeof(uint8_t)); bmpFile.write(&sigTwo, sizeof(uint8_t)); bmpFile.write( reinterpret_cast<const char*>(&totalSize), sizeof(uint32_t)); bmpFile.write( reinterpret_cast<const char*>(&reserved), sizeof(uint16_t)); bmpFile.write( reinterpret_cast<const char*>(&reserved), sizeof(uint16_t)); bmpFile.write( reinterpret_cast<const char*>(&pixelOffset), sizeof(uint32_t)); /* clang-format on */ } /** * Writes the BMP image header to the provided file * @param bmpFile File stream to which image header will be written * @param width The width of the PPM file in pixels * @param height The height of the PPM file in pixels */ void writeBmpImageHeader(std::ofstream& bmpFile, int width, int height) { // Image header (40 bytes) // biSize 4 Header Size - Must be at least 40 // biWidth 4 Image width in pixels // biHeight 4 Image height in pixels // biPlanes 2 Must be 1 // biBitCount 2 Bits per pixel - 1, 4, 8, 16, 24, or 32 // biCompression 4 Compression type (0 = uncompressed) // biSizeImage 4 Image Size - may be zero for uncompressed images // biXPelsPerMeter 4 Preferred resolution in pixels per meter // biYPelsPerMeter 4 Preferred resolution in pixels per meter // biClrUsed 4 Number Color Map entries that are actually used // biClrImportant 4 Number of significant colors const uint32_t headerSizeBytes = 40; const uint16_t planes = 1; const uint16_t bitsPerPixel = 24; const uint32_t compression = 0; const uint32_t imageSize = 0; const uint32_t preferredResolution = 0; const uint32_t colorMapEntries = 0; const uint32_t significantColors = 0; /* clang-format off */ bmpFile.write(reinterpret_cast<const char*>(&headerSizeBytes), sizeof(uint32_t)); bmpFile.write(reinterpret_cast<const char*>(&width), sizeof(uint32_t)); bmpFile.write(reinterpret_cast<const char*>(&height), sizeof(uint32_t)); bmpFile.write(reinterpret_cast<const char*>(&planes), sizeof(uint16_t)); bmpFile.write(reinterpret_cast<const char*>(&bitsPerPixel), sizeof(uint16_t)); bmpFile.write(reinterpret_cast<const char*>(&compression), sizeof(uint32_t)); bmpFile.write(reinterpret_cast<const char*>(&imageSize), sizeof(uint32_t)); bmpFile.write(reinterpret_cast<const char*>(&preferredResolution), sizeof(uint32_t)); bmpFile.write(reinterpret_cast<const char*>(&preferredResolution), sizeof(uint32_t)); bmpFile.write(reinterpret_cast<const char*>(&colorMapEntries), sizeof(uint32_t)); bmpFile.write(reinterpret_cast<const char*>(&significantColors), sizeof(uint32_t)); /* clang-format on */ } /** * Writes all pixels from the PPM file (ascii) into the BMP file (binary) * @param ppmBuffer File stream from which ascii pixels will be read * @param bmpFile File stream to which binary pixels will be written * @param width The width of the PPM file in pixels * @param height The height of the PPM file in pixels */ template<typename F> bool writePixels(const std::vector<int>& ppmBuffer, std::ofstream& bmpFile, int width, int height, F color_scheme) { // Write pixels to BMP file (24 bits per pixel), padding each row to be // 4-byte divisible The BMP image is stored bottom-to-top, so we have to // wrote the rows backwards relative to the PPM image char** map = new char*[height]; const uint32_t BYTES_PER_PIXEL = 3; uint32_t padBytes = 0; if ((width * BYTES_PER_PIXEL) % sizeof(uint32_t) != 0) padBytes = sizeof(uint32_t) - ((width * BYTES_PER_PIXEL) % sizeof(uint32_t)); // Copy the top of the PPM into the bottom of the bitmap auto ppmIt = begin(ppmBuffer); for (int row = height - 1; row >= 0; --row) { map[row] = new char[width * BYTES_PER_PIXEL + padBytes]; auto col = 0u; for (; col < width * BYTES_PER_PIXEL; col += 3) { auto [red, green, blue] = color_scheme(*ppmIt++); map[row][col + 0] = (char)blue; map[row][col + 1] = (char)green; map[row][col + 2] = (char)red; } // Pad if needed const uint8_t padData = 0x00; for (auto pad = 0u; pad < padBytes; ++pad) map[row][col++] = (char)padData; } // Write the bitmap out to the bmpFile for (int row = 0; row < height; ++row) { bmpFile.write(map[row], width * BYTES_PER_PIXEL + padBytes); delete[] map[row]; } delete[] map; return true; } } // namespace stayOffMyLawn /** * Program converts an vector of iteration data into a 24-bit BMP file * @param ppmBuffer buffer of pixel information * @param ppmWidth width of the image in pixels * @param ppmHeight height of the image in pixels * @param color_scheme std::tuple<int, int, int>(int) function * @param bmpFileName name of the bmp image to write * @return true on success, false on failure */ template<typename F> bool ppmToBmp(const std::vector<int>& ppmBuffer, uint32_t ppmWidth, uint32_t ppmHeight, F color_scheme, std::string bmpFileName) { std::cout << "Writing " << bmpFileName << "...\n"; // Read out PPM header to get size information std::ofstream bmpFile(bmpFileName.c_str(), std::ios::binary); if (ppmBuffer.size() == ppmWidth * ppmHeight) { stayOffMyLawn::writeBmpHeader(bmpFile, ppmWidth, ppmHeight); stayOffMyLawn::writeBmpImageHeader(bmpFile, ppmWidth, ppmHeight); if (stayOffMyLawn::writePixels( ppmBuffer, bmpFile, ppmWidth, ppmHeight, color_scheme)) { std::cout << "Success!" << std::endl; return true; } } bmpFile.close(); return false; } #endif
35.412037
89
0.681135
[ "vector" ]
48e551a89d8b2a92823d986e979f6cc492af2c78
9,018
cpp
C++
cpp/typer.cpp
nilern/brmh
db69e8ae0303eca6311db6871cace84517bd1124
[ "MIT" ]
1
2021-12-27T12:39:37.000Z
2021-12-27T12:39:37.000Z
cpp/typer.cpp
nilern/brmh
db69e8ae0303eca6311db6871cace84517bd1124
[ "MIT" ]
null
null
null
cpp/typer.cpp
nilern/brmh
db69e8ae0303eca6311db6871cace84517bd1124
[ "MIT" ]
null
null
null
#include <cstring> #include "type.hpp" #include "ast.hpp" #include "typeenv.hpp" #include "fast.hpp" namespace brmh { // # Program fast::Program ast::Program::check(Names& names, type::Types& types) { fast::Program program; TypeEnv env(names, types); for (auto def : defs) { def->declare(env); } for (auto def : defs) { program.push_toplevel(def->check(program, env)); } return program; } // # Defs void ast::FunDef::declare(TypeEnv &env) { env.declare(name, env.uv()); } fast::Def* ast::FunDef::check(fast::Program& program, TypeEnv& parent_env) { auto const binding = parent_env.find(name).value(); Name const unique_name = binding.first; TypeEnv env = parent_env.push_frame(); std::vector<fast::Pat*> new_params; std::vector<type::Type*> domain; for (Pat const* param : params) { fast::Pat* const new_param = param->type_of(program, env); new_params.push_back(new_param); domain.push_back(new_param->type); } fast::Expr* typed_body = body->check(program, env, codomain); binding.second->unify(env.types().fn(std::move(domain), codomain), span); return program.fun_def(span, unique_name, std::move(new_params), codomain, typed_body); } // # Expressions fast::Expr* type_block(fast::Program& program, TypeEnv& env, std::vector<ast::Stmt*> const& stmts, std::size_t i, ast::Expr const* body, std::span<fast::Stmt*> typed_stmts) { if (i < stmts.size()) { auto stmt_env = stmts[i]->check(program, env); typed_stmts[i] = stmt_env.first; return type_block(program, stmt_env.second, stmts, i + 1, body, typed_stmts); } else { return body->type_of(program, env); } } fast::Expr* ast::Block::type_of(fast::Program& program, TypeEnv& env) const { if (stmts.size() > 0) { std::span<fast::Stmt*> typed_stmts = program.stmts(stmts.size()); auto typed_body = type_block(program, env, stmts, 0, body, typed_stmts); return program.block(span, typed_body->type, std::move(typed_stmts), typed_body); } else { return body->type_of(program, env); } } fast::Expr* ast::If::type_of(fast::Program& program, TypeEnv& env) const { fast::Expr* const typed_cond = cond->check(program, env, env.types().get_bool()); fast::Expr* const typed_conseq = conseq->type_of(program, env); type::Type* const type = typed_conseq->type; fast::Expr* const typed_alt = alt->check(program, env, type); // TODO: treat branch types equally return program.if_(span, type, typed_cond, typed_conseq, typed_alt); } fast::Expr* ast::Call::type_of(fast::Program &program, TypeEnv &env) const { std::size_t arity = args.size(); std::vector<type::Type*> domain; domain.reserve(arity); for (std::size_t i = 0; i < args.size(); ++i) { domain.push_back(env.uv()); } auto const codomain = env.uv(); auto const callee_type = env.types().fn(std::move(domain), codomain); fast::Expr* const typed_callee = callee->check(program, env, callee_type); std::span<fast::Expr*> typed_args = program.args(arity); for (std::size_t i = 0; i < arity; ++i) { typed_args[i] = args[i]->check(program, env, callee_type->domain[i]); } return program.call(span, codomain, typed_callee, typed_args); } fast::Expr* ast::PrimApp::type_of(fast::Program& program, TypeEnv& env) const { switch (op) { case ast::PrimApp::Op::ADD_W_I64: case ast::PrimApp::Op::SUB_W_I64: case ast::PrimApp::Op::MUL_W_I64: { // FIXME: Brittle '2':s: if (args.size() != 2) { throw type::PrimArgcError(span, 2, args.size()); } std::array<fast::Expr*, 2> typed_args; for (std::size_t i = 0; i < 2; ++i) { typed_args[i] = args[i]->check(program, env, env.types().get_i64()); } switch (op) { case ast::PrimApp::Op::ADD_W_I64: return program.add_w_i64(span, env.types().get_i64(), typed_args); case ast::PrimApp::Op::SUB_W_I64: return program.sub_w_i64(span, env.types().get_i64(), typed_args); case ast::PrimApp::Op::MUL_W_I64: return program.mul_w_i64(span, env.types().get_i64(), typed_args); default: assert(false); // unreachable } } case ast::PrimApp::Op::EQ_I64: { // FIXME: Brittle '2':s: if (args.size() != 2) { throw type::PrimArgcError(span, 2, args.size()); } std::array<fast::Expr*, 2> typed_args; for (std::size_t i = 0; i < 2; ++i) { typed_args[i] = args[i]->check(program, env, env.types().get_i64()); } return program.eq_i64(span, env.types().get_bool(), typed_args); } default: assert(false); // unreachable } } fast::Expr* ast::Bool::type_of(fast::Program& program, TypeEnv& env) const { return program.const_bool(span, env.types().get_bool(), value); } fast::Expr* ast::Int::type_of(fast::Program& program, TypeEnv& env) const { return program.const_i64(span, env.types().get_i64(), digits, strlen(digits)); } fast::Expr* ast::Id::type_of(fast::Program& program, TypeEnv& env) const { std::optional<std::pair<Name, type::Type*>> opt_binder = env.find(name); if (opt_binder) { return program.id(span, opt_binder->second, opt_binder->first); } else { throw type::UnboundError(span); } } fast::Expr* ast::Expr::check(fast::Program& program, TypeEnv& env, type::Type* type) const { fast::Expr* expr = type_of(program, env); expr->type->unify(type, span); return expr; } // # Patterns fast::Pat* ast::Pat::check(fast::Program& program, TypeEnv& env, type::Type* type) const { auto const pat = type_of(program, env); pat->type->unify(type, span); return pat; } fast::Pat* ast::IdPat::type_of(fast::Program& program, TypeEnv& env) const { auto const type = env.uv(); Name const unique_name = env.declare(name, type); return program.id_pat(span, type, unique_name); } fast::Pat* ast::AnnPat::type_of(fast::Program& program, TypeEnv& env) const { return pat->check(program, env, type); } // # Statements std::pair<fast::Stmt*, TypeEnv> ast::Val::check(fast::Program& program, TypeEnv& parent_env) const { TypeEnv env = parent_env.push_frame(); fast::Expr* const typed_val_expr = val_expr->type_of(program, env); auto const typed_pat = pat->check(program, env, typed_val_expr->type); auto const stmt = program.val(span, typed_pat, typed_val_expr); return {stmt, std::move(env)}; } // # Unification void type::Type::unify(Type* other, Span span) { Type* found_this = find(); Type* found_other = other->find(); if (found_this != found_other) { found_this->unifyFounds(found_other, span); } } void type::Uv::unifyFoundUvs(type::Uv* uv, Span) { uv->union_(this); } void type::Type::unifyFoundUvs(type::Uv* uv, Span span) { occurs_check(uv, span); uv->set(this); } void type::Uv::unifyFoundFns(FnType* other, Span span) { other->unifyFoundUvs(this, span); } void type::Uv::unifyFoundBools(Bool* other, Span span) { other->unifyFoundUvs(this, span); } void type::Uv::unifyFoundI64s(I64* other, Span span) { other->unifyFoundUvs(this, span); } void type::FnType::unifyFoundFns(type::FnType* other, Span span) { auto dom = domain.begin(); auto other_dom = other->domain.begin(); for (;; ++dom, ++other_dom) { if (dom != domain.end()) { if (other_dom != other->domain.end()) { (*other_dom)->unify(*dom, span); } else { throw type::UnificationError(span, other, this); } } else { if (other_dom == other->domain.end()) { break; } else { throw type::UnificationError(span, other, this); } } } codomain->unify(other->codomain, span); } void type::Type::unifyFoundFns(type::FnType* other, Span span) { throw type::UnificationError(span, other, this); } void type::Bool::unifyFoundBools(Bool*, Span) {} void type::Type::unifyFoundBools(Bool* other, Span span) { throw type::UnificationError(span, other, this); } void type::I64::unifyFoundI64s(I64*, Span) {} void type::Type::unifyFoundI64s(I64* other, Span span) { throw type::UnificationError(span, other, this); } // ## Occurs Check void type::Type::occurs_check(Uv *uv, Span span) const { if (this == uv) { throw type::OccursError(span, uv, this); } else { occurs_check_children(uv, span); } } void type::Uv::occurs_check_children(Uv* uv, Span span) const { parent_.iter([&] (Type const* parent) { parent->occurs_check(uv, span); }); } void type::FnType::occurs_check_children(Uv* uv, Span span) const { for (Type const* dom : domain) { dom->occurs_check(uv, span); } codomain->occurs_check(uv, span); } void type::Type::occurs_check_children(Uv*, Span) const {} } // namespace brmh
31.642105
115
0.625305
[ "vector" ]
48ee9819cbc1dc023f3510981f2092042c298c4c
92,737
cc
C++
EnergyPlus/BranchNodeConnections.cc
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
null
null
null
EnergyPlus/BranchNodeConnections.cc
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
1
2020-07-08T13:32:09.000Z
2020-07-08T13:32:09.000Z
EnergyPlus/BranchNodeConnections.cc
yurigabrich/EnergyPlusShadow
396ca83aa82b842e6b177ba35c91b3f481dfbbf9
[ "BSD-3-Clause" ]
null
null
null
// EnergyPlus, Copyright (c) 1996-2018, The Board of Trustees of the University of Illinois, // The Regents of the University of California, through Lawrence Berkeley National Laboratory // (subject to receipt of any required approvals from the U.S. Dept. of Energy), Oak Ridge // National Laboratory, managed by UT-Battelle, Alliance for Sustainable Energy, LLC, and other // contributors. All rights reserved. // // NOTICE: This Software was developed under funding from the U.S. Department of Energy and the // U.S. Government consequently retains certain rights. As such, the U.S. Government has been // granted for itself and others acting on its behalf a paid-up, nonexclusive, irrevocable, // worldwide license in the Software to reproduce, distribute copies to the public, prepare // derivative works, and perform publicly and display publicly, and to permit others to do so. // // Redistribution and use in source and binary forms, with or without modification, are permitted // provided that the following conditions are met: // // (1) Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // (2) Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // // (3) Neither the name of the University of California, Lawrence Berkeley National Laboratory, // the University of Illinois, U.S. Dept. of Energy nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // (4) Use of EnergyPlus(TM) Name. If Licensee (i) distributes the software in stand-alone form // without changes from the version obtained under this License, or (ii) Licensee makes a // reference solely to the software portion of its product, Licensee must refer to the // software as "EnergyPlus version X" software, where "X" is the version number Licensee // obtained under this License and may not use a different name for the software. Except as // specifically required in this Section (4), Licensee shall not use in a company name, a // product name, in advertising, publicity, or other promotional activities any name, trade // name, trademark, logo, or other designation of "EnergyPlus", "E+", "e+" or confusingly // similar designation, without the U.S. Department of Energy's prior written consent. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ObjexxFCL Headers #include <ObjexxFCL/Array.functions.hh> #include <ObjexxFCL/Fmath.hh> #include <ObjexxFCL/member.functions.hh> #include <ObjexxFCL/string.functions.hh> // EnergyPlus Headers #include <BranchNodeConnections.hh> #include <DataBranchNodeConnections.hh> #include <DataGlobals.hh> #include <DataLoopNode.hh> #include <General.hh> #include <UtilityRoutines.hh> namespace EnergyPlus { namespace BranchNodeConnections { // Module containing the routines dealing with the Branch/Node Connections (CompSets, etc) // MODULE INFORMATION: // AUTHOR Linda Lawrie // DATE WRITTEN May 2005 // PURPOSE OF THIS MODULE: // This module encapsulates the connection data necessary for some of the checks // needed in the branch-node data // Using/Aliasing using DataGlobals::OutputFileDebug; using namespace DataLoopNode; using namespace DataBranchNodeConnections; // Data // MODULE PARAMETER DEFINITIONS: static std::string const BlankString; // Functions void RegisterNodeConnection(int const NodeNumber, // Number for this Node std::string const &NodeName, // Name of this Node std::string const &ObjectType, // Type of object this Node is connected to (e.g. Chiller:Electric) std::string const &ObjectName, // Name of object this Node is connected to (e.g. MyChiller) std::string const &ConnectionType, // Connection Type for this Node (must be valid) int const FluidStream, // Count on Fluid Streams bool const IsParent, // True when node is a parent node bool &errFlag, // Will be True if errors already detected or if errors found here Optional_string_const InputFieldName // Input Field Name ) { // SUBROUTINE INFORMATION: // AUTHOR Linda K. Lawrie // DATE WRITTEN February 2004 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // This subroutine registers a node connection in the Node Connection data structure. This // structure is intended to help with HVAC diagramming as well as validation of nodes. // SUBROUTINE PARAMETER DEFINITIONS: static std::string const RoutineName("RegisterNodeConnection: "); // SUBROUTINE LOCAL VARIABLE DECLARATIONS: bool ErrorsFoundHere; int Count; bool MakeNew; int Found; ErrorsFoundHere = false; if (!IsValidConnectionType(ConnectionType)) { ShowSevereError(RoutineName + "Invalid ConnectionType=" + ConnectionType); ShowContinueError("Occurs for Node=" + NodeName + ", ObjectType=" + ObjectType + ", ObjectName=" + ObjectName); ErrorsFoundHere = true; } MakeNew = true; for (Count = 1; Count <= NumOfNodeConnections; ++Count) { if (NodeConnections(Count).NodeNumber != NodeNumber) continue; if (!UtilityRoutines::SameString(NodeConnections(Count).ObjectType, ObjectType)) continue; if (!UtilityRoutines::SameString(NodeConnections(Count).ObjectName, ObjectName)) continue; if (!UtilityRoutines::SameString(NodeConnections(Count).ConnectionType, ConnectionType)) continue; if (NodeConnections(Count).FluidStream != FluidStream) continue; if ((NodeConnections(Count).ObjectIsParent && !IsParent) || (!NodeConnections(Count).ObjectIsParent && IsParent)) { ShowSevereError(RoutineName + "Node registered for both Parent and \"not\" Parent"); ShowContinueError("Occurs for Node=" + NodeName + ", ObjectType=" + ObjectType + ", ObjectName=" + ObjectName); ErrorsFoundHere = true; } MakeNew = false; } if (MakeNew) { ++NumOfNodeConnections; if (NumOfNodeConnections > 1 && NumOfNodeConnections > MaxNumOfNodeConnections) { NodeConnections.redimension(MaxNumOfNodeConnections += NodeConnectionAlloc); } else if (NumOfNodeConnections == 1) { NodeConnections.allocate(NodeConnectionAlloc); MaxNumOfNodeConnections = NodeConnectionAlloc; } NodeConnections(NumOfNodeConnections).NodeNumber = NodeNumber; NodeConnections(NumOfNodeConnections).NodeName = NodeName; NodeConnections(NumOfNodeConnections).ObjectType = UtilityRoutines::MakeUPPERCase(ObjectType); NodeConnections(NumOfNodeConnections).ObjectName = ObjectName; NodeConnections(NumOfNodeConnections).ConnectionType = ConnectionType; NodeConnections(NumOfNodeConnections).FluidStream = FluidStream; NodeConnections(NumOfNodeConnections).ObjectIsParent = IsParent; } if (has_prefixi(ObjectType, "AirTerminal:")) { if (present(InputFieldName)) { ++NumOfAirTerminalNodes; if (NumOfAirTerminalNodes > 1 && NumOfAirTerminalNodes > MaxNumOfAirTerminalNodes) { AirTerminalNodeConnections.redimension(MaxNumOfAirTerminalNodes += EqNodeConnectionAlloc); } else if (NumOfAirTerminalNodes == 1) { AirTerminalNodeConnections.allocate(EqNodeConnectionAlloc); MaxNumOfAirTerminalNodes = EqNodeConnectionAlloc; } // Check out AirTerminal inlet/outlet nodes Found = UtilityRoutines::FindItemInList(NodeName, AirTerminalNodeConnections, &EqNodeConnectionDef::NodeName, NumOfAirTerminalNodes - 1); if (Found != 0) { // Nodename already used ShowSevereError(RoutineName + ObjectType + "=\"" + ObjectName + "\" node name duplicated."); ShowContinueError("NodeName=\"" + NodeName + "\", entered as type=" + ConnectionType); ShowContinueError("In Field=" + InputFieldName()); ShowContinueError("Already used in " + AirTerminalNodeConnections(Found).ObjectType + "=\"" + AirTerminalNodeConnections(Found).ObjectName + "\"."); ShowContinueError(" as type=" + AirTerminalNodeConnections(Found).ConnectionType + ", In Field=" + AirTerminalNodeConnections(Found).InputFieldName); ErrorsFoundHere = true; } else { AirTerminalNodeConnections(NumOfAirTerminalNodes).NodeName = NodeName; AirTerminalNodeConnections(NumOfAirTerminalNodes).ObjectType = ObjectType; AirTerminalNodeConnections(NumOfAirTerminalNodes).ObjectName = ObjectName; AirTerminalNodeConnections(NumOfAirTerminalNodes).ConnectionType = ConnectionType; AirTerminalNodeConnections(NumOfAirTerminalNodes).InputFieldName = InputFieldName; } } else { ShowSevereError(RoutineName + ObjectType + ", Developer Error: Input Field Name not included."); ShowContinueError("Node names not checked for duplication."); } } if (ErrorsFoundHere) { errFlag = true; } } void OverrideNodeConnectionType(int const NodeNumber, // Number for this Node std::string const &NodeName, // Name of this Node std::string const &ObjectType, // Type of object this Node is connected to (e.g. Chiller:Electric) std::string const &ObjectName, // Name of object this Node is connected to (e.g. MyChiller) std::string const &ConnectionType, // Connection Type for this Node (must be valid) int const FluidStream, // Count on Fluid Streams bool const IsParent, // True when node is a parent node bool &errFlag // Will be True if errors already detected or if errors found here ) { // SUBROUTINE INFORMATION: // AUTHOR M. J. Witte // DATE WRITTEN June 2016 // PURPOSE: // This subroutine modifies an existing node connection in the Node Connection data structure. This // structure is intended to help with HVAC diagramming as well as validation of nodes. This function // is a based on RegisterNodeConnection. static std::string const RoutineName("ModifyNodeConnectionType: "); if (!IsValidConnectionType(ConnectionType)) { ShowSevereError(RoutineName + "Invalid ConnectionType=" + ConnectionType); ShowContinueError("Occurs for Node=" + NodeName + ", ObjectType=" + ObjectType + ", ObjectName=" + ObjectName); errFlag = true; } int Found = 0; for (int Count = 1; Count <= NumOfNodeConnections; ++Count) { if (NodeConnections(Count).NodeNumber != NodeNumber) continue; if (!UtilityRoutines::SameString(NodeConnections(Count).ObjectType, ObjectType)) continue; if (!UtilityRoutines::SameString(NodeConnections(Count).ObjectName, ObjectName)) continue; if (NodeConnections(Count).FluidStream != FluidStream) continue; if ((NodeConnections(Count).ObjectIsParent != IsParent)) continue; Found = Count; break; } if (Found > 0) { NodeConnections(Found).ConnectionType = ConnectionType; } else { ShowSevereError(RoutineName + "Existing node connection not found."); ShowContinueError("Occurs for Node=" + NodeName + ", ObjectType=" + ObjectType + ", ObjectName=" + ObjectName); errFlag = true; } } bool IsValidConnectionType(std::string const &ConnectionType) { // FUNCTION INFORMATION: // AUTHOR Linda K. Lawrie // DATE WRITTEN August 2003 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This function determines if a connection type is valid. // METHODOLOGY EMPLOYED: // na // REFERENCES: // na // USE STATEMENTS: // na // Return value bool IsValid; // Locals // FUNCTION ARGUMENT DEFINITIONS: // FUNCTION PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS // na // DERIVED TYPE DEFINITIONS // na // FUNCTION LOCAL VARIABLE DECLARATIONS: int Count; IsValid = false; for (Count = 1; Count <= NumValidConnectionTypes; ++Count) { if (ConnectionType != ValidConnectionTypes(Count)) continue; IsValid = true; break; } return IsValid; } void CheckNodeConnections(bool &ErrorsFound) { // SUBROUTINE INFORMATION: // AUTHOR Linda Lawrie // DATE WRITTEN March 2004 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // This subroutine processes the node connection data structure looking at: // 1. In the NodeConnections list, for any node which appears as a sensor or an // actuator, the same node must also appear in the connections list at least once // as a node type which is not sensor or actuator or outsideair. // 2. In the NodeConnections list, for any node which appears as a setpoint, the // same node must also appear in the connections list at least once as a node type // which is not a setpoint or outsideair. // 3. Every ZoneInlet must appear as an outlet from something, otherwise it will // do nothing. // 4. Every ZoneExhaust must appear as an inlet to something, // otherwise it will do nothing. // 5. Every inlet node should match either an Outlet, ZoneReturn, ZoneExhaust, ReliefAir, // or OutsideAir node. // With the current data structure, when checking inlets: // a) If an InletNode's object is AirLoopHVAC, CondenserLoop, or PlantLoop, then skip the test. // b) If an InletNode's object is not one of the above types, it is valid if the // same node name appears as an INLET to an AirLoopHVAC, CondenserLoop, or PlantLoop. // 6. Any given node can only be an inlet once in the list of Non-Parent Node Connections // 7. Any given node can only be an outlet once in the list of Non-Parent Node Connections // 8. non-parent outlet nodes -- must never be an outlet more than once // 9. nodes of type OutsideAirReference must be registered as NodeConnectionType_OutsideAir // 10. fluid streams cannot have multiple inlet/outlet nodes on same component // 11. zone nodes may not be used as anything else except as a setpoint, sensor or actuator node // METHODOLOGY EMPLOYED: // Needs description, as appropriate. // Using/Aliasing using General::RoundSigDigits; // SUBROUTINE LOCAL VARIABLE DECLARATIONS: int Loop1; int Loop2; bool IsValid; bool IsInlet; bool IsOutlet; bool MatchedAtLeastOne; int ErrorCounter; int Object; int StartConnect; int EndConnect; Array1D_int FluidStreamInletCount; Array1D_int FluidStreamOutletCount; Array1D_int NodeObjects; Array1D_bool FluidStreamCounts; int NumObjects; int MaxFluidStream; ErrorCounter = 0; // Check 1 -- check sensor and actuator nodes for (Loop1 = 1; Loop1 <= NumOfNodeConnections; ++Loop1) { if (NodeConnections(Loop1).ConnectionType != ValidConnectionTypes(NodeConnectionType_Sensor)) continue; IsValid = false; for (Loop2 = 1; Loop2 <= NumOfNodeConnections; ++Loop2) { if (Loop1 == Loop2) continue; if (NodeConnections(Loop1).NodeNumber != NodeConnections(Loop2).NodeNumber) continue; if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_Actuator)) continue; if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_Sensor)) continue; IsValid = true; } if (!IsValid) { ShowSevereError("Node Connection Error, Node=\"" + NodeConnections(Loop1).NodeName + "\", Sensor node did not find a matching node of appropriate type (other than Actuator or Sensor)."); ShowContinueError("Reference Object=" + NodeConnections(Loop1).ObjectType + ", Name=" + NodeConnections(Loop1).ObjectName); ++ErrorCounter; ErrorsFound = true; } } for (Loop1 = 1; Loop1 <= NumOfNodeConnections; ++Loop1) { if (NodeConnections(Loop1).ConnectionType != ValidConnectionTypes(NodeConnectionType_Actuator)) continue; IsValid = false; for (Loop2 = 1; Loop2 <= NumOfNodeConnections; ++Loop2) { if (Loop1 == Loop2) continue; if (NodeConnections(Loop1).NodeNumber != NodeConnections(Loop2).NodeNumber) continue; if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_Actuator)) continue; if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_Sensor)) continue; if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_OutsideAir)) continue; IsValid = true; } if (!IsValid) { ShowSevereError("Node Connection Error, Node=\"" + NodeConnections(Loop1).NodeName + "\", Actuator node did not find a matching node of appropriate type (other than Actuator, Sensor, OutsideAir)."); ShowContinueError("Reference Object=" + NodeConnections(Loop1).ObjectType + ", Name=" + NodeConnections(Loop1).ObjectName); ++ErrorCounter; ErrorsFound = true; } } // Check 2 -- setpoint nodes // Check 2a -- setpoint node must also be an inlet or an outlet (CR8212) for (Loop1 = 1; Loop1 <= NumOfNodeConnections; ++Loop1) { if (NodeConnections(Loop1).ConnectionType != ValidConnectionTypes(NodeConnectionType_SetPoint)) continue; IsValid = false; IsInlet = false; IsOutlet = false; for (Loop2 = 1; Loop2 <= NumOfNodeConnections; ++Loop2) { if (Loop1 == Loop2) continue; if (NodeConnections(Loop1).NodeNumber != NodeConnections(Loop2).NodeNumber) continue; if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_SetPoint)) continue; if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_OutsideAir)) continue; if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_Inlet)) IsInlet = true; if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_Outlet)) IsOutlet = true; IsValid = true; } if (!IsValid) { ShowSevereError("Node Connection Error, Node=\"" + NodeConnections(Loop1).NodeName + "\", Setpoint node did not find a matching node of appropriate type (other than Setpoint, OutsideAir)."); ShowContinueError("Reference Object=" + NodeConnections(Loop1).ObjectType + ", Name=" + NodeConnections(Loop1).ObjectName); ++ErrorCounter; ErrorsFound = true; } if (!IsInlet && !IsOutlet) { ShowSevereError("Node Connection Error, Node=\"" + NodeConnections(Loop1).NodeName + "\", Setpoint node did not find a matching node of type Inlet or Outlet."); ShowContinueError("It appears this node is not part of the HVAC system."); ShowContinueError("Reference Object=" + NodeConnections(Loop1).ObjectType + ", Name=" + NodeConnections(Loop1).ObjectName); ++ErrorCounter; // ErrorsFound=.TRUE. } } // Check 2a -- setpoint node must also be an inlet or an outlet (CR8212) // DO Loop1=1,NumOfNodeConnections // IF (NodeConnections(Loop1)%ConnectionType /= ValidConnectionTypes(NodeConnectionType_SetPoint)) CYCLE // IsValid=.FALSE. // IsInlet=.FALSE. // IsOutlet=.FALSE. // DO Loop2=1, NumOfNodeConnections // IF (Loop1 == Loop2) CYCLE // IF (NodeConnections(Loop1)%NodeNumber /= NodeConnections(Loop2)%NodeNumber) CYCLE // IF (NodeConnections(Loop2)%ConnectionType == ValidConnectionTypes(NodeConnectionType_Inlet)) IsInlet=.TRUE. // IF (NodeConnections(Loop2)%ConnectionType == ValidConnectionTypes(NodeConnectionType_Outlet)) IsOutlet=.TRUE. // IF (IsInlet .or. IsOutlet) EXIT // ENDDO // IF (.not. IsInlet .and. .not. IsOutlet) THEN // CALL ShowSevereError('Node Connection Error, Node="'//TRIM(NodeConnections(Loop1)%NodeName)// & // '", Setpoint node did not find a matching node of type Inlet or Outlet.') // CALL ShowContinueError('It appears this node is not part of the HVAC system.') // CALL ShowContinueError('Reference Object='//TRIM(NodeConnections(Loop1)%ObjectType)// & // ', Name='//TRIM(NodeConnections(Loop1)%ObjectName)) // ErrorCounter=ErrorCounter+1 // ErrorsFound=.TRUE. // ENDIF // ENDDO // Check 3 -- zone inlet nodes -- must be an outlet somewhere for (Loop1 = 1; Loop1 <= NumOfNodeConnections; ++Loop1) { if (NodeConnections(Loop1).ConnectionType != ValidConnectionTypes(NodeConnectionType_ZoneInlet)) continue; IsValid = false; for (Loop2 = 1; Loop2 <= NumOfNodeConnections; ++Loop2) { if (Loop1 == Loop2) continue; if (NodeConnections(Loop1).NodeNumber != NodeConnections(Loop2).NodeNumber) continue; if (NodeConnections(Loop2).ConnectionType != ValidConnectionTypes(NodeConnectionType_Outlet)) continue; IsValid = true; } if (!IsValid) { ShowSevereError("Node Connection Error, Node=\"" + NodeConnections(Loop1).NodeName + "\", ZoneInlet node did not find an outlet node."); ShowContinueError("Reference Object=" + NodeConnections(Loop1).ObjectType + ", Name=" + NodeConnections(Loop1).ObjectName); ++ErrorCounter; // ErrorsFound=.TRUE. } } // Check 4 -- zone exhaust nodes -- must be an inlet somewhere for (Loop1 = 1; Loop1 <= NumOfNodeConnections; ++Loop1) { if (NodeConnections(Loop1).ConnectionType != ValidConnectionTypes(NodeConnectionType_ZoneExhaust)) continue; IsValid = false; for (Loop2 = 1; Loop2 <= NumOfNodeConnections; ++Loop2) { if (Loop1 == Loop2) continue; if (NodeConnections(Loop1).NodeNumber != NodeConnections(Loop2).NodeNumber) continue; if (NodeConnections(Loop2).ConnectionType != ValidConnectionTypes(NodeConnectionType_Inlet)) continue; IsValid = true; } if (!IsValid) { ShowSevereError("Node Connection Error, Node=\"" + NodeConnections(Loop1).NodeName + "\", ZoneExhaust node did not find a matching inlet node."); ShowContinueError("Reference Object=" + NodeConnections(Loop1).ObjectType + ", Name=" + NodeConnections(Loop1).ObjectName); ++ErrorCounter; // ErrorsFound=.TRUE. } } // Check 5 -- return plenum induced air outlet nodes -- must be an inlet somewhere for (Loop1 = 1; Loop1 <= NumOfNodeConnections; ++Loop1) { if (NodeConnections(Loop1).ConnectionType != ValidConnectionTypes(NodeConnectionType_InducedAir)) continue; IsValid = false; for (Loop2 = 1; Loop2 <= NumOfNodeConnections; ++Loop2) { if (Loop1 == Loop2) continue; if (NodeConnections(Loop1).NodeNumber != NodeConnections(Loop2).NodeNumber) continue; if (NodeConnections(Loop2).ConnectionType != ValidConnectionTypes(NodeConnectionType_Inlet)) continue; IsValid = true; } if (!IsValid) { ShowSevereError("Node Connection Error, Node=\"" + NodeConnections(Loop1).NodeName + "\", Return plenum induced air outlet node did not find a matching inlet node."); ShowContinueError("Reference Object=" + NodeConnections(Loop1).ObjectType + ", Name=" + NodeConnections(Loop1).ObjectName); ++ErrorCounter; ErrorsFound = true; } } // Check 6 -- every inlet should have a matching outlet, zonereturn, zoneexhaust, induced air, reliefair or outsideair // a) If an InletNode's object is AirLoopHVAC, CondenserLoop, or PlantLoop, then skip the test. // b) If an InletNode's object is not one of the above types, it is valid if the // same node name appears as an INLET to an AirLoopHVAC, CondenserLoop, or PlantLoop. for (Loop1 = 1; Loop1 <= NumOfNodeConnections; ++Loop1) { if (NodeConnections(Loop1).ConnectionType != ValidConnectionTypes(NodeConnectionType_Inlet)) continue; if (NodeConnections(Loop1).ObjectType == "AIRLOOPHVAC" || NodeConnections(Loop1).ObjectType == "CONDENSERLOOP" || NodeConnections(Loop1).ObjectType == "PLANTLOOP") continue; IsValid = false; MatchedAtLeastOne = false; for (Loop2 = 1; Loop2 <= NumOfNodeConnections; ++Loop2) { if (Loop1 == Loop2) continue; if (NodeConnections(Loop1).NodeNumber != NodeConnections(Loop2).NodeNumber) continue; if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_Outlet) || NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_ZoneReturn) || NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_ZoneExhaust) || NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_InducedAir) || NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_ReliefAir) || NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_OutsideAir)) { MatchedAtLeastOne = true; continue; } if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_Inlet) && (NodeConnections(Loop2).ObjectType == "AIRLOOPHVAC" || NodeConnections(Loop2).ObjectType == "CONDENSERLOOP" || NodeConnections(Loop2).ObjectType == "PLANTLOOP")) { MatchedAtLeastOne = true; continue; } IsValid = false; } if (!IsValid && !MatchedAtLeastOne) { ShowSevereError("Node Connection Error, Node=\"" + NodeConnections(Loop1).NodeName + "\", Inlet node did not find an appropriate matching \"outlet\" node."); ShowContinueError("If this is an outdoor air inlet node, it must be listed in an OutdoorAir:Node or OutdoorAir:NodeList object."); ShowContinueError("Reference Object=" + NodeConnections(Loop1).ObjectType + ", Name=" + NodeConnections(Loop1).ObjectName); ++ErrorCounter; // ErrorsFound=.TRUE. } } // Check 7 -- non-parent inlet nodes -- must never be an inlet more than once for (Loop1 = 1; Loop1 <= NumOfNodeConnections; ++Loop1) { // Only non-parent node connections if (NodeConnections(Loop1).ObjectIsParent) continue; if (NodeConnections(Loop1).ConnectionType != ValidConnectionTypes(NodeConnectionType_Inlet)) continue; for (Loop2 = Loop1; Loop2 <= NumOfNodeConnections; ++Loop2) { if (Loop1 == Loop2) continue; if (NodeConnections(Loop2).ObjectIsParent) continue; if (NodeConnections(Loop2).ConnectionType != ValidConnectionTypes(NodeConnectionType_Inlet)) continue; if (NodeConnections(Loop2).NodeNumber == NodeConnections(Loop1).NodeNumber) { ShowSevereError("Node Connection Error, Node=\"" + NodeConnections(Loop1).NodeName + "\", The same node appears as a non-parent Inlet node more than once."); ShowContinueError("Reference Object=" + NodeConnections(Loop1).ObjectType + ", Name=" + NodeConnections(Loop1).ObjectName); ShowContinueError("Reference Object=" + NodeConnections(Loop2).ObjectType + ", Name=" + NodeConnections(Loop2).ObjectName); ++ErrorCounter; // ErrorsFound=.TRUE. break; } } } // Check 8 -- non-parent outlet nodes -- must never be an outlet more than once for (Loop1 = 1; Loop1 <= NumOfNodeConnections; ++Loop1) { // Only non-parent node connections if (NodeConnections(Loop1).ObjectIsParent) continue; if (NodeConnections(Loop1).ConnectionType != ValidConnectionTypes(NodeConnectionType_Outlet)) continue; // Skip if DIRECT AIR, because it only has one node which is an outlet, so it dupes the outlet which feeds it if (NodeConnections(Loop1).ObjectType == "AIRTERMINAL:SINGLEDUCT:UNCONTROLLED") continue; IsValid = true; for (Loop2 = Loop1; Loop2 <= NumOfNodeConnections; ++Loop2) { if (Loop1 == Loop2) continue; if (NodeConnections(Loop2).ObjectIsParent) continue; if (NodeConnections(Loop2).ConnectionType != ValidConnectionTypes(NodeConnectionType_Outlet)) continue; // Skip if DIRECT AIR, because it only has one node which is an outlet, so it dupes the outlet which feeds it if (NodeConnections(Loop2).ObjectType == "AIRTERMINAL:SINGLEDUCT:UNCONTROLLED") continue; if (NodeConnections(Loop2).NodeNumber == NodeConnections(Loop1).NodeNumber) { // Skip if one of the ShowSevereError("Node Connection Error, Node=\"" + NodeConnections(Loop1).NodeName + "\", The same node appears as a non-parent Outlet node more than once."); ShowContinueError("Reference Object=" + NodeConnections(Loop1).ObjectType + ", Name=" + NodeConnections(Loop1).ObjectName); ShowContinueError("Reference Object=" + NodeConnections(Loop2).ObjectType + ", Name=" + NodeConnections(Loop2).ObjectName); ++ErrorCounter; // ErrorsFound=.TRUE. break; } } } // Check 9 -- nodes of type OutsideAirReference must be registered as NodeConnectionType_OutsideAir for (Loop1 = 1; Loop1 <= NumOfNodeConnections; ++Loop1) { if (NodeConnections(Loop1).ConnectionType != ValidConnectionTypes(NodeConnectionType_OutsideAirReference)) continue; IsValid = false; for (Loop2 = 1; Loop2 <= NumOfNodeConnections; ++Loop2) { if (Loop1 == Loop2) continue; if (NodeConnections(Loop1).NodeNumber != NodeConnections(Loop2).NodeNumber) continue; if (NodeConnections(Loop2).ConnectionType != ValidConnectionTypes(NodeConnectionType_OutsideAir)) continue; IsValid = true; break; } if (!IsValid) { ShowSevereError("Node Connection Error, Node=\"" + NodeConnections(Loop1).NodeName + "\", Outdoor Air Reference did not find an appropriate \"outdoor air\" node."); ShowContinueError("This node must be listed in an OutdoorAir:Node or OutdoorAir:NodeList object in order to set its conditions."); ShowContinueError("Reference Object=" + NodeConnections(Loop1).ObjectType + ", Name=" + NodeConnections(Loop1).ObjectName); ++ErrorCounter; // ErrorsFound=.TRUE. } } // Check 10 -- fluid streams cannot have multiple inlet/outlet nodes on same component // can have multiple inlets with one outlet or vice versa but cannot have multiple both inlet and outlet if (NumOfNodeConnections > 0) { MaxFluidStream = maxval(NodeConnections, &NodeConnectionDef::FluidStream); FluidStreamInletCount.allocate(MaxFluidStream); FluidStreamOutletCount.allocate(MaxFluidStream); FluidStreamCounts.allocate(MaxFluidStream); NodeObjects.allocate(NumOfNodeConnections); FluidStreamInletCount = 0; FluidStreamOutletCount = 0; NodeObjects = 0; FluidStreamCounts = false; // Following code relies on node connections for single object type/name being grouped together Object = 1; StartConnect = 1; EndConnect = 0; NumObjects = 2; NodeObjects(1) = 1; while (Object < NumOfNodeConnections) { if (NodeConnections(Object).ObjectType != NodeConnections(Object + 1).ObjectType || NodeConnections(Object).ObjectName != NodeConnections(Object + 1).ObjectName) { EndConnect = Object + 1; NodeObjects(NumObjects) = EndConnect; if (Object + 1 < NumOfNodeConnections) ++NumObjects; } ++Object; } // NodeObjects now contains each consecutive object... for (Object = 1; Object <= NumObjects - 1; ++Object) { IsValid = true; FluidStreamInletCount = 0; FluidStreamOutletCount = 0; FluidStreamCounts = false; Loop1 = NodeObjects(Object); if (NumOfNodeConnections < 2) continue; if (NodeConnections(Loop1).ObjectIsParent) continue; if (NodeConnections(Loop1).ConnectionType == ValidConnectionTypes(NodeConnectionType_Inlet)) ++FluidStreamInletCount(NodeConnections(Loop1).FluidStream); if (NodeConnections(Loop1).ConnectionType == ValidConnectionTypes(NodeConnectionType_Outlet)) ++FluidStreamOutletCount(NodeConnections(Loop1).FluidStream); for (Loop2 = Loop1 + 1; Loop2 <= NodeObjects(Object + 1) - 1; ++Loop2) { if (NodeConnections(Loop2).ObjectIsParent) continue; if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_Inlet)) ++FluidStreamInletCount(NodeConnections(Loop2).FluidStream); if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_Outlet)) ++FluidStreamOutletCount(NodeConnections(Loop2).FluidStream); } for (Loop2 = 1; Loop2 <= MaxFluidStream; ++Loop2) { if (FluidStreamInletCount(Loop2) > 1 && FluidStreamOutletCount(Loop2) > 1) { IsValid = false; FluidStreamCounts(Loop2) = true; } } if (!IsValid) { ShowSevereError("(Developer) Node Connection Error, Object=" + NodeConnections(Loop1).ObjectType + ':' + NodeConnections(Loop1).ObjectName); ShowContinueError("Object has multiple connections on both inlet and outlet fluid streams."); for (Loop2 = 1; Loop2 <= MaxFluidStream; ++Loop2) { if (FluidStreamCounts(Loop2)) ShowContinueError("...occurs in Fluid Stream [" + RoundSigDigits(Loop2) + "]."); } ++ErrorCounter; ErrorsFound = true; } } FluidStreamInletCount.deallocate(); FluidStreamOutletCount.deallocate(); FluidStreamCounts.deallocate(); NodeObjects.deallocate(); } // Check 11 - zone nodes may not be used as anything else except as a setpoint, sensor or actuator node for (Loop1 = 1; Loop1 <= NumOfNodeConnections; ++Loop1) { if (NodeConnections(Loop1).ConnectionType != ValidConnectionTypes(NodeConnectionType_ZoneNode)) continue; IsValid = true; for (Loop2 = Loop1; Loop2 <= NumOfNodeConnections; ++Loop2) { if (Loop1 == Loop2) continue; if (NodeConnections(Loop1).NodeName == NodeConnections(Loop2).NodeName) { if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_Sensor)) continue; if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_Actuator)) continue; if (NodeConnections(Loop2).ConnectionType == ValidConnectionTypes(NodeConnectionType_SetPoint)) continue; ShowSevereError("Node Connection Error, Node Name=\"" + NodeConnections(Loop1).NodeName + "\", The same zone node appears more than once."); ShowContinueError("Reference Object=" + NodeConnections(Loop1).ObjectType + ", Object Name=" + NodeConnections(Loop1).ObjectName); ShowContinueError("Reference Object=" + NodeConnections(Loop2).ObjectType + ", Object Name=" + NodeConnections(Loop2).ObjectName); ++ErrorCounter; ErrorsFound = true; } } } NumNodeConnectionErrors += ErrorCounter; } bool IsParentObject(std::string const &ComponentType, std::string const &ComponentName) { // FUNCTION INFORMATION: // AUTHOR Linda Lawrie // DATE WRITTEN May 2005 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This routine determines if a component name is a parent node. // METHODOLOGY EMPLOYED: // Traverses CompSet structure. // REFERENCES: // na // USE STATEMENTS: // na // Return value bool IsParent; // True if this combination is a parent // Locals // FUNCTION ARGUMENT DEFINITIONS: // FUNCTION PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // FUNCTION LOCAL VARIABLE DECLARATIONS: int Loop; IsParent = false; for (Loop = 1; Loop <= NumOfNodeConnections; ++Loop) { if (NodeConnections(Loop).ObjectType == ComponentType && NodeConnections(Loop).ObjectName == ComponentName) { if (NodeConnections(Loop).ObjectIsParent) { IsParent = true; } break; } } if (!IsParent) { IsParent = IsParentObjectCompSet(ComponentType, ComponentName); } return IsParent; } int WhichParentSet(std::string const &ComponentType, std::string const &ComponentName) { // FUNCTION INFORMATION: // AUTHOR Linda Lawrie // DATE WRITTEN May 2005 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This routine determines which parent node list (number) for a given component name // and type. // METHODOLOGY EMPLOYED: // Traverses CompSet structure. // REFERENCES: // na // USE STATEMENTS: // na // Return value int WhichOne; // Locals // FUNCTION ARGUMENT DEFINITIONS: // FUNCTION PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // FUNCTION LOCAL VARIABLE DECLARATIONS: int Loop; WhichOne = 0; for (Loop = 1; Loop <= NumOfActualParents; ++Loop) { if (ParentNodeList(Loop).CType == ComponentType && ParentNodeList(Loop).CName == ComponentName) { WhichOne = Loop; break; } } return WhichOne; } void GetParentData(std::string const &ComponentType, std::string const &ComponentName, std::string &InletNodeName, int &InletNodeNum, std::string &OutletNodeName, int &OutletNodeNum, bool &ErrorsFound) { // SUBROUTINE INFORMATION: // AUTHOR Linda Lawrie // DATE WRITTEN May 2005 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // This routine gets node data for a given Parent Component Type and Name Name. // METHODOLOGY EMPLOYED: // Traverses CompSet structure. // SUBROUTINE LOCAL VARIABLE DECLARATIONS: // INTEGER Loop bool ErrInObject; int Which; InletNodeName = BlankString; InletNodeNum = 0; OutletNodeName = BlankString; OutletNodeNum = 0; ErrInObject = false; Which = WhichParentSet(ComponentType, ComponentName); if (Which != 0) { InletNodeName = ParentNodeList(Which).InletNodeName; OutletNodeName = ParentNodeList(Which).OutletNodeName; // Get Node Numbers InletNodeNum = UtilityRoutines::FindItemInList(InletNodeName, NodeID({1, NumOfNodes}), NumOfNodes); OutletNodeNum = UtilityRoutines::FindItemInList(OutletNodeName, NodeID({1, NumOfNodes}), NumOfNodes); // IF (InletNodeNum == 0 .and. ComponentType /= 'ZONEHVAC:AIRDISTRIBUTIONUNIT') THEN // CALL ShowWarningError('GetParentData: Component Type='//TRIM(ComponentType)// & // ', Component Name='//TRIM(ComponentName)) // CALL ShowContinueError('..Inlet Node Name, not found='//TRIM(InletNodeName)) //! ErrInObject=.TRUE. // ENDIF // IF (OutletNodeNum == 0) THEN // CALL ShowWarningError('GetParentData: Component Type='//TRIM(ComponentType)// & // ', Component Name='//TRIM(ComponentName)) // CALL ShowContinueError('..Outlet Node Name, not found='//TRIM(OutletNodeName)) //! ErrInObject=.TRUE. // ENDIF } else if (IsParentObjectCompSet(ComponentType, ComponentName)) { Which = WhichCompSet(ComponentType, ComponentName); if (Which != 0) { InletNodeName = CompSets(Which).InletNodeName; OutletNodeName = CompSets(Which).OutletNodeName; InletNodeNum = UtilityRoutines::FindItemInList(InletNodeName, NodeID({1, NumOfNodes}), NumOfNodes); OutletNodeNum = UtilityRoutines::FindItemInList(OutletNodeName, NodeID({1, NumOfNodes}), NumOfNodes); // IF (InletNodeNum == 0 .and. ComponentType /= 'ZONEHVAC:AIRDISTRIBUTIONUNIT') THEN // CALL ShowWarningError('GetParentData: Component Type='//TRIM(ComponentType)// & // ', Component Name='//TRIM(ComponentName)) // CALL ShowContinueError('..Inlet Node Name, not found='//TRIM(InletNodeName)) // ! ErrInObject=.TRUE. // ENDIF // IF (OutletNodeNum == 0) THEN // CALL ShowWarningError('GetParentData: Component Type='//TRIM(ComponentType)// & // ', Component Name='//TRIM(ComponentName)) // CALL ShowContinueError('..Outlet Node Name, not found='//TRIM(OutletNodeName)) // ! ErrInObject=.TRUE. // ENDIF } else { ErrInObject = true; ShowWarningError("GetParentData: Component Type=" + ComponentType + ", Component Name=" + ComponentName + " not found."); } } else { ErrInObject = true; ShowWarningError("GetParentData: Component Type=" + ComponentType + ", Component Name=" + ComponentName + " not found."); } if (ErrInObject) ErrorsFound = true; } bool IsParentObjectCompSet(std::string const &ComponentType, std::string const &ComponentName) { // FUNCTION INFORMATION: // AUTHOR Linda Lawrie // DATE WRITTEN May 2005 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This routine determines if a component name is a parent node. // METHODOLOGY EMPLOYED: // Traverses CompSet structure. // REFERENCES: // na // USE STATEMENTS: // na // Return value bool IsParent; // True if this combination is a parent // Locals // FUNCTION ARGUMENT DEFINITIONS: // FUNCTION PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // FUNCTION LOCAL VARIABLE DECLARATIONS: int Loop; IsParent = false; for (Loop = 1; Loop <= NumCompSets; ++Loop) { if (CompSets(Loop).ParentCType == ComponentType && CompSets(Loop).ParentCName == ComponentName) { IsParent = true; break; } } return IsParent; } int WhichCompSet(std::string const &ComponentType, std::string const &ComponentName) { // FUNCTION INFORMATION: // AUTHOR Linda Lawrie // DATE WRITTEN May 2005 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This routine determines which comp set (number) for a given component name // and type. // METHODOLOGY EMPLOYED: // Traverses CompSet structure. // REFERENCES: // na // USE STATEMENTS: // na // Return value int WhichOne; // Locals // FUNCTION ARGUMENT DEFINITIONS: // FUNCTION PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // FUNCTION LOCAL VARIABLE DECLARATIONS: int Loop; WhichOne = 0; for (Loop = 1; Loop <= NumCompSets; ++Loop) { if (CompSets(Loop).CType == ComponentType && CompSets(Loop).CName == ComponentName) { WhichOne = Loop; break; } } return WhichOne; } int WhichParentCompSet(std::string const &ComponentType, std::string const &ComponentName) { // FUNCTION INFORMATION: // AUTHOR Linda Lawrie // DATE WRITTEN May 2005 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This routine determines which comp set (number) for a given component name // and type. // METHODOLOGY EMPLOYED: // Traverses CompSet structure. // REFERENCES: // na // USE STATEMENTS: // na // Return value int WhichOne; // Locals // FUNCTION ARGUMENT DEFINITIONS: // FUNCTION PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // FUNCTION LOCAL VARIABLE DECLARATIONS: int Loop; WhichOne = 0; for (Loop = 1; Loop <= NumCompSets; ++Loop) { if (CompSets(Loop).ParentCType == ComponentType && CompSets(Loop).ParentCName == ComponentName) { WhichOne = Loop; break; } } return WhichOne; } int GetNumChildren(std::string const &ComponentType, std::string const &ComponentName) { // FUNCTION INFORMATION: // AUTHOR Linda Lawrie // DATE WRITTEN May 2005 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This routine counts the number of children for a parent Component Set. // METHODOLOGY EMPLOYED: // Traverses CompSet structure. // REFERENCES: // na // USE STATEMENTS: // na // Return value int NumChildren; // Locals // FUNCTION ARGUMENT DEFINITIONS: // FUNCTION PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS: // na // DERIVED TYPE DEFINITIONS: // na // FUNCTION LOCAL VARIABLE DECLARATIONS: int Loop; NumChildren = 0; if (IsParentObject(ComponentType, ComponentName)) { for (Loop = 1; Loop <= NumCompSets; ++Loop) { if (CompSets(Loop).ParentCType == ComponentType && CompSets(Loop).ParentCName == ComponentName) { ++NumChildren; } } } return NumChildren; } void GetComponentData(std::string const &ComponentType, std::string const &ComponentName, bool &IsParent, int &NumInlets, Array1D_string &InletNodeNames, Array1D_int &InletNodeNums, Array1D_int &InletFluidStreams, int &NumOutlets, Array1D_string &OutletNodeNames, Array1D_int &OutletNodeNums, Array1D_int &OutletFluidStreams, bool &ErrorsFound) { // SUBROUTINE INFORMATION: // AUTHOR Linda Lawrie // DATE WRITTEN May 2005 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // This routine gets data for a given Component Type and Name Name. // METHODOLOGY EMPLOYED: // Traverses CompSet structure. // SUBROUTINE LOCAL VARIABLE DECLARATIONS: // INTEGER Loop bool ErrInObject; int Which; // unused1109 LOGICAL FoundObject if (allocated(InletNodeNames)) InletNodeNames.deallocate(); if (allocated(InletNodeNums)) InletNodeNums.deallocate(); if (allocated(InletFluidStreams)) InletFluidStreams.deallocate(); if (allocated(OutletNodeNames)) OutletNodeNames.deallocate(); if (allocated(OutletNodeNums)) OutletNodeNums.deallocate(); if (allocated(OutletFluidStreams)) OutletFluidStreams.deallocate(); NumInlets = 0; NumOutlets = 0; // FoundObject=.FALSE. IsParent = false; for (Which = 1; Which <= NumOfNodeConnections; ++Which) { if (NodeConnections(Which).ObjectType != ComponentType || NodeConnections(Which).ObjectName != ComponentName) continue; // FoundObject=.TRUE. if (NodeConnections(Which).ObjectIsParent) IsParent = true; if (UtilityRoutines::SameString(NodeConnections(Which).ConnectionType, "Inlet")) ++NumInlets; if (UtilityRoutines::SameString(NodeConnections(Which).ConnectionType, "Outlet")) ++NumOutlets; } InletNodeNames.allocate(NumInlets); InletNodeNums.allocate(NumInlets); InletFluidStreams.allocate(NumInlets); OutletNodeNames.allocate(NumOutlets); OutletNodeNums.allocate(NumOutlets); OutletFluidStreams.allocate(NumOutlets); InletNodeNames = BlankString; InletNodeNums = 0; InletFluidStreams = 0; OutletNodeNames = BlankString; OutletNodeNums = 0; OutletFluidStreams = 0; NumInlets = 0; NumOutlets = 0; ErrInObject = false; // IF (IsParentObject(ComponentType,ComponentName)) THEN // IsParent=.TRUE. // ENDIF for (Which = 1; Which <= NumOfNodeConnections; ++Which) { if (NodeConnections(Which).ObjectType != ComponentType || NodeConnections(Which).ObjectName != ComponentName) continue; if (UtilityRoutines::SameString(NodeConnections(Which).ConnectionType, "Inlet")) { ++NumInlets; InletNodeNames(NumInlets) = NodeConnections(Which).NodeName; InletNodeNums(NumInlets) = NodeConnections(Which).NodeNumber; InletFluidStreams(NumInlets) = NodeConnections(Which).FluidStream; } if (UtilityRoutines::SameString(NodeConnections(Which).ConnectionType, "Outlet")) { ++NumOutlets; OutletNodeNames(NumOutlets) = NodeConnections(Which).NodeName; OutletNodeNums(NumOutlets) = NodeConnections(Which).NodeNumber; OutletFluidStreams(NumOutlets) = NodeConnections(Which).FluidStream; } } if (ErrInObject) { ShowWarningError("GetComponentData: Component Type=" + ComponentType + ", Component Name=" + ComponentName + " not found."); } if (ErrInObject) ErrorsFound = true; } void GetChildrenData(std::string const &ComponentType, std::string const &ComponentName, int &NumChildren, Array1S_string ChildrenCType, Array1S_string ChildrenCName, Array1S_string InletNodeName, Array1S_int InletNodeNum, Array1S_string OutletNodeName, Array1S_int OutletNodeNum, bool &ErrorsFound) { // SUBROUTINE INFORMATION: // AUTHOR Linda Lawrie // DATE WRITTEN May 2005 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // This routine gets children data for given parent node. // METHODOLOGY EMPLOYED: // Traverses CompSet structure. // SUBROUTINE LOCAL VARIABLE DECLARATIONS: Array1D_string ChildCType; Array1D_string ChildCName; Array1D_string ChildInNodeName; Array1D_string ChildOutNodeName; Array1D_int ChildInNodeNum; Array1D_int ChildOutNodeNum; int Loop; int CountNum; bool ErrInObject; std::string MatchNodeName; std::string ParentInletNodeName; std::string ParentOutletNodeName; int ParentInletNodeNum; int ParentOutletNodeNum; // unused1109 LOGICAL Matched int CountMatchLoop; ChildrenCType = BlankString; ChildrenCName = BlankString; InletNodeName = BlankString; InletNodeNum = 0; OutletNodeName = BlankString; OutletNodeNum = 0; ErrInObject = false; if (IsParentObject(ComponentType, ComponentName)) { NumChildren = GetNumChildren(ComponentType, ComponentName); if (NumChildren == 0) { ShowWarningError("GetChildrenData: Parent Node has no children, node=" + ComponentType + ':' + ComponentName); } else { GetParentData( ComponentType, ComponentName, ParentInletNodeName, ParentInletNodeNum, ParentOutletNodeName, ParentOutletNodeNum, ErrInObject); ChildCType.allocate(NumChildren); ChildCName.allocate(NumChildren); ChildInNodeName.allocate(NumChildren); ChildOutNodeName.allocate(NumChildren); ChildInNodeNum.allocate(NumChildren); ChildOutNodeNum.allocate(NumChildren); ChildCType = BlankString; ChildCName = BlankString; ChildInNodeName = BlankString; ChildOutNodeName = BlankString; ChildInNodeNum = 0; ChildOutNodeNum = 0; CountNum = 0; for (Loop = 1; Loop <= NumCompSets; ++Loop) { if (CompSets(Loop).ParentCType == ComponentType && CompSets(Loop).ParentCName == ComponentName) { ++CountNum; ChildCType(CountNum) = CompSets(Loop).CType; ChildCName(CountNum) = CompSets(Loop).CName; ChildInNodeName(CountNum) = CompSets(Loop).InletNodeName; ChildOutNodeName(CountNum) = CompSets(Loop).OutletNodeName; // Get Node Numbers ChildInNodeNum(CountNum) = UtilityRoutines::FindItemInList(ChildInNodeName(CountNum), NodeID({1, NumOfNodes}), NumOfNodes); // IF (ChildInNodeNum(CountNum) == 0) THEN // CALL ShowSevereError('GetChildrenData: Inlet Node not previously assigned, Node='// & // TRIM(ChildInNodeName(CountNum))) // CALL ShowContinueError('..Component='//TRIM(ChildCType(CountNum))//':'//TRIM(ChildCName(CountNum))) // CALL ShowContinueError('..Parent Object='//TRIM(ComponentType)//':'//TRIM(ComponentName)) // ErrInObject=.TRUE. // ENDIF ChildOutNodeNum(CountNum) = UtilityRoutines::FindItemInList(ChildOutNodeName(CountNum), NodeID({1, NumOfNodes}), NumOfNodes); // IF (ChildOutNodeNum(CountNum) == 0) THEN // CALL ShowSevereError('GetChildrenData: Outlet Node not previously assigned, Node='// & // TRIM(ChildOutNodeName(CountNum))) // CALL ShowContinueError('..Component='//TRIM(ChildCType(CountNum))//':'//TRIM(ChildCName(CountNum))) // CALL ShowContinueError('..Parent Object='//TRIM(ComponentType)//':'//TRIM(ComponentName)) // ErrInObject=.TRUE. // ENDIF } } if (CountNum != NumChildren) { ShowSevereError("GetChildrenData: Counted nodes not equal to GetNumChildren count"); ErrInObject = true; } else { // Children arrays built. Now "sort" for flow connection order(?) MatchNodeName = ParentInletNodeName; CountNum = 0; CountMatchLoop = 0; while (CountMatchLoop < NumChildren) { ++CountMatchLoop; // Matched=.FALSE. for (Loop = 1; Loop <= NumChildren; ++Loop) { if (ChildInNodeName(Loop) == MatchNodeName) { ++CountNum; ChildrenCType(CountNum) = ChildCType(Loop); ChildrenCName(CountNum) = ChildCName(Loop); InletNodeName(CountNum) = ChildInNodeName(Loop); InletNodeNum(CountNum) = ChildInNodeNum(Loop); OutletNodeName(CountNum) = ChildOutNodeName(Loop); OutletNodeNum(CountNum) = ChildOutNodeNum(Loop); ChildInNodeName(Loop).clear(); // So it won't match anymore // Matched=.TRUE. MatchNodeName = ChildOutNodeName(Loop); break; } } // IF (.not. Matched .and. MatchNodeName /= blank) THEN // IF (CountMatchLoop > 1) THEN // CALL ShowSevereError('GetChildrenData: Sorting for flow connection order..'// & // 'Required Child Node, not matched. Expected Inlet Node='// & // TRIM(MatchNodeName)) // ELSE // CALL ShowSevereError('GetChildrenData: Sorting for 1st node in flow connection order..'// & // 'Required Child Node, not matched. Expected Inlet Node='// & // TRIM(MatchNodeName)) // ENDIF // CALL ShowContinueError('..Parent Object='//TRIM(ComponentType)//':'//TRIM(ComponentName)) // ErrInObject=.TRUE. // ENDIF } if (MatchNodeName != ParentOutletNodeName) { for (Loop = 1; Loop <= NumChildren; ++Loop) { if (ChildInNodeName(Loop).empty()) continue; if (ChildOutNodeName(Loop) == ParentOutletNodeName) break; // CALL ShowSevereError('GetChildrenData: Sorting for flow connection order..'// & // 'Required Child Node, not matched. Expected (Last) Outlet Node='// & // TRIM(MatchNodeName)) // CALL ShowContinueError('..does not match Parent Outlet Node='//TRIM(ParentOutletNodeName)) // CALL ShowContinueError('..Parent Object='//TRIM(ComponentType)//':'//TRIM(ComponentName)) break; // ErrInObject=.TRUE. } } for (Loop = 1; Loop <= NumChildren; ++Loop) { if (ChildInNodeName(Loop).empty()) continue; ++CountNum; ChildrenCType(CountNum) = ChildCType(Loop); ChildrenCName(CountNum) = ChildCName(Loop); InletNodeName(CountNum) = ChildInNodeName(Loop); InletNodeNum(CountNum) = ChildInNodeNum(Loop); OutletNodeName(CountNum) = ChildOutNodeName(Loop); OutletNodeNum(CountNum) = ChildOutNodeNum(Loop); } ChildCType.deallocate(); ChildCName.deallocate(); ChildInNodeName.deallocate(); ChildOutNodeName.deallocate(); ChildInNodeNum.deallocate(); ChildOutNodeNum.deallocate(); } } } else { ShowSevereError("GetChildrenData: Requested Children Data for non Parent Node=" + ComponentType + ':' + ComponentName); ErrInObject = true; } if (ErrInObject) ErrorsFound = true; } void SetUpCompSets(std::string const &ParentType, // Parent Object Type std::string const &ParentName, // Parent Object Name std::string const &CompType, // Component Type std::string const &CompName, // Component Name std::string const &InletNode, // Inlet Node Name std::string const &OutletNode, // Outlet Node Name Optional_string_const Description // Description ) { // SUBROUTINE INFORMATION: // AUTHOR Linda Lawrie // DATE WRITTEN November 2001 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // This subroutine sets up "Component Sets" as input in the branch // lists. These can be used later to verify that the proper names and // inlet/outlet nodes have been input. This routine assumes that identical // "CompSets" cannot be used in multiple places and issues a warning if they are. // This subroutine also // SUBROUTINE LOCAL VARIABLE DECLARATIONS: std::string CompTypeUC; // Component type in upper case std::string ParentTypeUC; // Parent component type in upper case int Count; int Count2; int Found; int Found2; // Object Data ParentTypeUC = UtilityRoutines::MakeUPPERCase(ParentType); CompTypeUC = UtilityRoutines::MakeUPPERCase(CompType); Found = 0; // See if Component-Nodes set is already there - should be unique // Try to fill in blanks (passed in as undefined for (Count = 1; Count <= NumCompSets; ++Count) { // IF (CompTypeUC /= CompSets(Count)%CType .or. CompName /= CompSets(Count)%CName) CYCLE if (CompName != CompSets(Count).CName) continue; if (CompTypeUC != "UNDEFINED") { if (CompTypeUC != CompSets(Count).CType) continue; } // Component name matches, component type matches or is undefined if (InletNode != "UNDEFINED") { if (CompSets(Count).InletNodeName != "UNDEFINED") { if (InletNode != CompSets(Count).InletNodeName) continue; } } if (OutletNode != "UNDEFINED") { if (CompSets(Count).OutletNodeName != "UNDEFINED") { if (OutletNode != CompSets(Count).OutletNodeName) continue; } } // See if something undefined and set here if (CompSets(Count).ParentCType == "UNDEFINED" && CompSets(Count).ParentCName == "UNDEFINED") { // Assume this is a further definition for this compset CompSets(Count).ParentCType = ParentTypeUC; CompSets(Count).ParentCName = ParentName; if (present(Description)) CompSets(Count).Description = Description; Found = Count; break; } } if (Found == 0) { for (Count = 1; Count <= NumCompSets; ++Count) { Found = 0; // Test if inlet node has been used before as an inlet node // If the matching node name does not belong to the parent object, then error // For example a fan may share the same inlet node as the furnace object which is its parent if (InletNode != CompSets(Count).InletNodeName) { continue; // If parent type is "UNDEFINED" then no error } else if ((ParentTypeUC == "UNDEFINED") || (CompSets(Count).ParentCType == "UNDEFINED")) { // If node name is "UNDEFINED" then no error } else if (InletNode != "UNDEFINED") { // If the matching node name does not belong to the parent or child object, then error // For example a fan may share the same inlet node as the furnace object which is its parent if ((ParentTypeUC == CompSets(Count).CType) && (ParentName == CompSets(Count).CName)) { // OK - The duplicate inlet node belongs to this component's parent } else if ((CompTypeUC == CompSets(Count).ParentCType) && (CompName == CompSets(Count).ParentCName)) { // OK - The duplicate inlet node belongs to a child of this component } else { // Due to possibility of grandparents or more, if the matching node name // belongs to a component that appears as a parent, then OK Found2 = 0; for (Count2 = 1; Count2 <= NumCompSets; ++Count2) { if ((CompSets(Count).CType == CompSets(Count2).ParentCType) && (CompSets(Count).CName == CompSets(Count2).ParentCName)) Found2 = 1; if ((CompTypeUC == CompSets(Count2).ParentCType) && (CompName == CompSets(Count2).ParentCName)) Found2 = 1; } if (Found2 == 0) { ShowWarningError("Node used as an inlet more than once: " + InletNode); ShowContinueError(" Used by : " + CompSets(Count).ParentCType + ", name=" + CompSets(Count).ParentCName); ShowContinueError(" as inlet for: " + CompSets(Count).CType + ", name=" + CompSets(Count).CName); ShowContinueError(" and by : " + ParentTypeUC + ", name=" + ParentName); ShowContinueError(" as inlet for: " + CompTypeUC + ", name=" + CompName); } } } // Test if outlet node has been used before as an outlet node // If the matching node name does not belong to the parent or child object, then error // For example a fan may share the same outlet node as the furnace object which is its parent if (OutletNode != CompSets(Count).OutletNodeName) { continue; // If parent type is "UNDEFINED" then no error } else if ((ParentTypeUC == "UNDEFINED") || (CompSets(Count).ParentCType == "UNDEFINED")) { // If node name is "UNDEFINED" then no error } else if (OutletNode != "UNDEFINED") { if ((ParentTypeUC == CompSets(Count).CType) && (ParentName == CompSets(Count).CName)) { // OK - The duplicate outlet node belongs to this component's parent } else if ((CompTypeUC == CompSets(Count).ParentCType) && (CompName == CompSets(Count).ParentCName)) { // OK - The duplicate outlet node belongs to a child of this component } else { // Due to possibility of grandparents or more, if the matching node name // belongs to a component that appears as a parent, then OK Found2 = 0; for (Count2 = 1; Count2 <= NumCompSets; ++Count2) { if ((CompSets(Count).CType == CompSets(Count2).ParentCType) && (CompSets(Count).CName == CompSets(Count2).ParentCName)) Found2 = 1; if ((CompTypeUC == CompSets(Count2).ParentCType) && (CompName == CompSets(Count2).ParentCName)) Found2 = 1; } // This rule is violated by dual duct units, so let it pass if ((Found2 == 0) && (!has_prefixi(CompSets(Count).CType, "AirTerminal:DualDuct:")) && (!has_prefixi(CompTypeUC, "AirTerminal:DualDuct:"))) { ShowWarningError("Node used as an outlet more than once: " + OutletNode); ShowContinueError(" Used by : " + CompSets(Count).ParentCType + ", name=" + CompSets(Count).ParentCName); ShowContinueError(" as outlet for: " + CompSets(Count).CType + ", name=" + CompSets(Count).CName); ShowContinueError(" and by : " + ParentTypeUC + ", name=" + ParentName); ShowContinueError(" as outlet for: " + CompTypeUC + ", name=" + CompName); } } } if (CompTypeUC != CompSets(Count).CType && CompTypeUC != "UNDEFINED") continue; if (CompName != CompSets(Count).CName) continue; Found = Count; break; } } if (Found == 0) { CompSets.redimension(++NumCompSets); CompSets(NumCompSets).ParentCType = ParentTypeUC; CompSets(NumCompSets).ParentCName = ParentName; CompSets(NumCompSets).CType = CompTypeUC; CompSets(NumCompSets).CName = CompName; CompSets(NumCompSets).InletNodeName = UtilityRoutines::MakeUPPERCase(InletNode); // TODO: Fix this.... CompSets(NumCompSets).OutletNodeName = UtilityRoutines::MakeUPPERCase(OutletNode); // TODO: Fix this.... if (present(Description)) { CompSets(NumCompSets).Description = Description; } else { CompSets(NumCompSets).Description = "UNDEFINED"; } } } void TestInletOutletNodes(bool &EP_UNUSED(ErrorsFound)) { // SUBROUTINE INFORMATION: // AUTHOR Linda Lawrie // DATE WRITTEN November 2001 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // This subroutine tests the branches to see if a duplicate inlet node // exists under a different name in the sequence; likewise for outlet. // METHODOLOGY EMPLOYED: // na // REFERENCES: // na // USE STATEMENTS: // na // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // SUBROUTINE PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS // na // DERIVED TYPE DEFINITIONS // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: int Count; int Other; Array1D_bool AlreadyNoted; // Test component sets created by branches AlreadyNoted.dimension(NumCompSets, false); for (Count = 1; Count <= NumCompSets; ++Count) { for (Other = 1; Other <= NumCompSets; ++Other) { if (Count == Other) continue; if (CompSets(Count).InletNodeName != CompSets(Other).InletNodeName) continue; if (AlreadyNoted(Count)) continue; // All other values must match if (CompSets(Count).CType != CompSets(Other).CType || CompSets(Count).CName != CompSets(Other).CName || CompSets(Count).OutletNodeName != CompSets(Other).OutletNodeName) { AlreadyNoted(Other) = true; ShowWarningError("Node used as an inlet more than once: " + CompSets(Count).InletNodeName); ShowContinueError(" Used by : " + CompSets(Count).ParentCType + ", name=" + CompSets(Count).ParentCName); ShowContinueError(" as inlet for: " + CompSets(Count).CType + ", name=" + CompSets(Count).CName); ShowContinueError(" and by : " + CompSets(Other).ParentCType + ", name=" + CompSets(Other).ParentCName); ShowContinueError(" as inlet for: " + CompSets(Other).CType + ", name=" + CompSets(Other).CName); // ErrorsFound=.TRUE. } } } AlreadyNoted = false; for (Count = 1; Count <= NumCompSets; ++Count) { for (Other = 1; Other <= NumCompSets; ++Other) { if (Count == Other) continue; if (CompSets(Count).OutletNodeName != CompSets(Other).OutletNodeName) continue; if (AlreadyNoted(Count)) continue; // All other values must match if (CompSets(Count).CType != CompSets(Other).CType || CompSets(Count).CName != CompSets(Other).CName || CompSets(Count).InletNodeName != CompSets(Other).InletNodeName) { AlreadyNoted(Other) = true; ShowWarningError("Node used as an outlet more than once: " + CompSets(Count).OutletNodeName); ShowContinueError(" Used by : " + CompSets(Count).ParentCType + ", name=" + CompSets(Count).ParentCName); ShowContinueError(" as outlet for: " + CompSets(Count).CType + ", name=" + CompSets(Count).CName); ShowContinueError(" and by : " + CompSets(Other).ParentCType + ", name=" + CompSets(Other).ParentCName); ShowContinueError(" as outlet for: " + CompSets(Other).CType + ", name=" + CompSets(Other).CName); // ErrorsFound=.TRUE. } } } AlreadyNoted.deallocate(); } void TestCompSet(std::string const &CompType, // Component Type std::string const &CompName, // Component Name std::string const &InletNode, // Inlet Node Name std::string const &OutletNode, // Outlet Node Name std::string const &Description // Description of Node Pair (for warning message) ) { // SUBROUTINE INFORMATION: // AUTHOR Linda K. Lawrie // DATE WRITTEN November 2001 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // Register a child component in the CompSets data structure. // NOTE: This function was originally designed to test the stored "Component Sets" to // see if there was one of this combination in there. Thus the name "TestCompSet". // However, this was based on a false assumption that input would always be gotten // first for the parent object, then for the child object. But this is often not the // case. Ultimately, the name of this function should be changed or it should be merged // into SetUpCompSets. // Until then, this function does the following: // a) Search CompSets for this combination of component type, component name, // inlet node and outlet node. If component type/name match and the existing // node names are UNDEFINED, this compset is assumed to be a match. // b) If found, fill in any missing data such as node names or node description // c) If not found, call SetUpCompSets (with parent type and name UNDEFINED) // to add a new item in the CompSets array // FUNCTION LOCAL VARIABLE DECLARATIONS: int Count; int Found; std::string CompTypeUC; // Component type in upper case CompTypeUC = UtilityRoutines::MakeUPPERCase(CompType); // See if Already there Found = 0; for (Count = 1; Count <= NumCompSets; ++Count) { if ((CompTypeUC != CompSets(Count).CType) && (CompSets(Count).CType != "UNDEFINED")) continue; if (CompName != CompSets(Count).CName) continue; if ((InletNode != CompSets(Count).InletNodeName) && (CompSets(Count).InletNodeName != "UNDEFINED") && (InletNode != "UNDEFINED")) continue; if ((OutletNode != CompSets(Count).OutletNodeName) && (CompSets(Count).OutletNodeName != "UNDEFINED") && (OutletNode != "UNDEFINED")) continue; Found = Count; break; } if (Found == 0) { SetUpCompSets("UNDEFINED", "UNDEFINED", CompType, CompName, InletNode, OutletNode, Description); } else { // Fill in node names and component type for previously undefined values: // If the parent object did not specify a component type or inlet or outlet node, then that value // is UNDEFINED in CompSets. When a component calls TestCompSet, the comp type and inlet and // outlet nodes are known, so they can be filled in for future reference. if (CompSets(Found).CType == "UNDEFINED") CompSets(Found).CType = CompTypeUC; if (CompSets(Found).InletNodeName == "UNDEFINED") CompSets(Found).InletNodeName = InletNode; if (CompSets(Found).OutletNodeName == "UNDEFINED") CompSets(Found).OutletNodeName = OutletNode; if (CompSets(Found).Description == "UNDEFINED") CompSets(Found).Description = Description; } } void TestCompSetInletOutletNodes(bool &ErrorsFound) { // SUBROUTINE INFORMATION: // AUTHOR Linda Lawrie // DATE WRITTEN March 2008 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS SUBROUTINE: // This subroutine tests the comp sets to see if a duplicate comp name // exists under a different set of inlet/outlet nodes. // METHODOLOGY EMPLOYED: // na // REFERENCES: // na // USE STATEMENTS: // na // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // SUBROUTINE PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS // na // DERIVED TYPE DEFINITIONS // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: int Count; int Other; Array1D_bool AlreadyNoted; // Test component sets created by branches AlreadyNoted.dimension(NumCompSets, false); for (Count = 1; Count <= NumCompSets; ++Count) { for (Other = 1; Other <= NumCompSets; ++Other) { if (Count == Other) continue; if (CompSets(Count).CType == "SOLARCOLLECTOR:UNGLAZEDTRANSPIRED") continue; if (CompSets(Count).CType != CompSets(Other).CType || CompSets(Count).CName != CompSets(Other).CName) continue; if (CompSets(Count).Description != CompSets(Other).Description) { if (CompSets(Count).Description != "UNDEFINED" && CompSets(Other).Description != "UNDEFINED") continue; } if (CompSets(Count).InletNodeName == CompSets(Other).InletNodeName) continue; if (CompSets(Count).OutletNodeName == CompSets(Other).OutletNodeName) continue; if (AlreadyNoted(Count)) continue; // All other values must match AlreadyNoted(Other) = true; ShowSevereError("Same component name and type has differing Node Names."); ShowContinueError(" Component: " + CompSets(Count).CType + ", name=" + CompSets(Count).CName); ShowContinueError(" Nodes, inlet: " + CompSets(Count).InletNodeName + ", outlet: " + CompSets(Count).OutletNodeName); ShowContinueError(" & Nodes, inlet: " + CompSets(Other).InletNodeName + ", outlet: " + CompSets(Other).OutletNodeName); ShowContinueError(" Node Types: " + CompSets(Count).Description + " & " + CompSets(Other).Description); ErrorsFound = true; } } // AlreadyNoted=.FALSE. // DO Count=1,NumCompSets // DO Other=1,NumCompSets // IF (Count == Other) CYCLE // IF (CompSets(Count)%InletNodeName /= CompSets(Other)%InletNodeName) CYCLE // IF (AlreadyNoted(Count)) CYCLE // ! All other values must match // IF (CompSets(Count)%ParentCType == 'BRANCH' .or. CompSets(Other)%ParentCType == 'BRANCH') CYCLE // IF (CompSets(Count)%Description /= CompSets(Other)%Description) CYCLE // IF (CompSets(Count)%CType == CompSets(Other)%CType) THEN // AlreadyNoted(Other)=.TRUE. // CALL ShowWarningError('Node used as an inlet more than once: '//TRIM(CompSets(Count)%InletNodeName)) // CALL ShowContinueError(' Used by : '//TRIM(CompSets(Count)%ParentCType)// & // ', name='//TRIM(CompSets(Count)%ParentCName)) // CALL ShowContinueError(' as inlet for: '//TRIM(CompSets(Count)%CType)//', name='//TRIM(CompSets(Count)%CName)) // CALL ShowContinueError(' and by : '//TRIM(CompSets(Other)%ParentCType)// & // ', name='//TRIM(CompSets(Other)%ParentCName)) // CALL ShowContinueError(' as inlet for: '//TRIM(CompSets(Other)%CType)//', name='//TRIM(CompSets(Other)%CName)) // ErrorsFound=.TRUE. // ENDIF // ENDDO // ENDDO // AlreadyNoted=.FALSE. // DO Count=1,NumCompSets // DO Other=1,NumCompSets // IF (Count == Other) CYCLE // IF (CompSets(Count)%OutletNodeName /= CompSets(Other)%OutletNodeName) CYCLE // IF (AlreadyNoted(Count)) CYCLE // ! All other values must match // IF (CompSets(Count)%ParentCType == 'BRANCH' .or. CompSets(Other)%ParentCType == 'BRANCH') CYCLE // IF (CompSets(Count)%Description /= CompSets(Other)%Description) CYCLE // IF (CompSets(Count)%CType /= CompSets(Other)%CType) THEN // AlreadyNoted(Other)=.TRUE. // CALL ShowWarningError('Node used as an outlet more than once: '//TRIM(CompSets(Count)%OutletNodeName)) // CALL ShowContinueError(' Used by : '//TRIM(CompSets(Count)%ParentCType)// & // ', name='//TRIM(CompSets(Count)%ParentCName)) // CALL ShowContinueError(' as outlet for: '//TRIM(CompSets(Count)%CType)//', name='//TRIM(CompSets(Count)%CName)) // CALL ShowContinueError(' and by : '//TRIM(CompSets(Other)%ParentCType)// & // ', name='//TRIM(CompSets(Other)%ParentCName)) // CALL ShowContinueError(' as outlet for: '//TRIM(CompSets(Other)%CType)//', name='//TRIM(CompSets(Other)%CName)) // ErrorsFound=.TRUE. // ENDIF // ENDDO // ENDDO AlreadyNoted.deallocate(); } void GetNodeConnectionType(int const NodeNumber, Array1D_int &NodeConnectType, bool &errFlag) { // FUNCTION INFORMATION: // AUTHOR Lixing Gu // DATE WRITTEN Jan 2007 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This function provides a connection type with given node number // FUNCTION LOCAL VARIABLE DECLARATIONS: int NodeConnectIndex; int NumInList; Array1D_int ListArray; if (allocated(NodeConnectType)) NodeConnectType.deallocate(); FindAllNodeNumbersInList(NodeNumber, NodeConnections, NumOfNodeConnections, NumInList, ListArray); NodeConnectType.allocate(NumInList); if (NumInList > 0) { for (NodeConnectIndex = 1; NodeConnectIndex <= NumInList; ++NodeConnectIndex) { NodeConnectType(NodeConnectIndex) = UtilityRoutines::FindItemInList( NodeConnections(ListArray(NodeConnectIndex)).ConnectionType, ValidConnectionTypes, NumValidConnectionTypes); } } else { if (NodeNumber > 0) { ShowWarningError("Node not found = " + NodeID(NodeNumber) + '.'); } else { ShowWarningError("Invalid node number passed = 0."); } errFlag = true; } } void FindAllNodeNumbersInList(int const WhichNumber, Array1<DataBranchNodeConnections::NodeConnectionDef> const &NodeConnections, int const NumItems, int &CountOfItems, // Number of items found Array1D_int &AllNumbersInList // Index array to all numbers found ) { // FUNCTION INFORMATION: // AUTHOR R. Raustad // DATE WRITTEN January 2007 // MODIFIED na // RE-ENGINEERED na // PURPOSE OF THIS FUNCTION: // This function looks up a number(integer) in a similar list of // items and returns the index of the item in the list, if // found. // METHODOLOGY EMPLOYED: // na // REFERENCES: // na // USE STATEMENTS: // na // Locals // SUBROUTINE ARGUMENT DEFINITIONS: // SUBROUTINE PARAMETER DEFINITIONS: // na // INTERFACE BLOCK SPECIFICATIONS // na // DERIVED TYPE DEFINITIONS // na // SUBROUTINE LOCAL VARIABLE DECLARATIONS: int Count; // Counter for DO loops CountOfItems = 0; if (allocated(AllNumbersInList)) AllNumbersInList.deallocate(); for (Count = 1; Count <= NumItems; ++Count) { if (WhichNumber == NodeConnections(Count).NodeNumber) { ++CountOfItems; } } if (CountOfItems > 0) { AllNumbersInList.dimension(CountOfItems, 0); CountOfItems = 0; for (Count = 1; Count <= NumItems; ++Count) { if (WhichNumber == NodeConnections(Count).NodeNumber) { ++CountOfItems; AllNumbersInList(CountOfItems) = Count; } } } } } // namespace BranchNodeConnections } // namespace EnergyPlus
48.91192
150
0.569956
[ "object" ]
48ef59d75d53ac1a60e9f1841efdd59d5299017a
24,686
cpp
C++
data-server/src/range/lock.cpp
gengdaomi/sharkstore
1b490176846d2da98ceca07a69b6c35646567a28
[ "Apache-2.0" ]
1
2021-08-11T02:31:52.000Z
2021-08-11T02:31:52.000Z
data-server/src/range/lock.cpp
gengdaomi/sharkstore
1b490176846d2da98ceca07a69b6c35646567a28
[ "Apache-2.0" ]
null
null
null
data-server/src/range/lock.cpp
gengdaomi/sharkstore
1b490176846d2da98ceca07a69b6c35646567a28
[ "Apache-2.0" ]
null
null
null
#include "range.h" #include "base/util.h" #include "server/range_server.h" #include "range_logger.h" namespace sharkstore { namespace dataserver { namespace range { namespace lock { void EncodeKey(std::string* buf, uint64_t tableId, const std::string* key) { assert(buf != nullptr && buf->length() == 0); buf->push_back(static_cast<char>(1)); EncodeUint64Ascending(buf, tableId); // column 1 assert(buf->length() == 9); EncodeBytesAscending(buf, key->c_str(), key->length()); } bool DecodeKey(std::string& key, const std::string& buf) { assert(buf.length() > 9); size_t offset; for (offset = 9; offset < buf.length();) { if (!DecodeBytesAscending(buf, offset, &key)) { return false; } } return true; } void EncodeValue(std::string* buf, int64_t version, const kvrpcpb::LockValue& lock_value, //const std::string* value, const std::string* extend) { assert(buf != nullptr); std::string value = lock_value.SerializeAsString(); EncodeIntValue(buf, 2, version); EncodeBytesValue(buf, 3, value.c_str(), value.length()); EncodeBytesValue(buf, 4, extend->c_str(), extend->length()); } bool DecodeValue(int64_t* version, kvrpcpb::LockValue* lock_value, std::string* extend, std::string& buf) { assert(buf.length() != 0); std::string value; size_t offset = 0; if (!DecodeIntValue(buf, offset, version)) return false; if (!DecodeBytesValue(buf, offset, &value)) return false; if (!DecodeBytesValue(buf, offset, extend)) return false; if (!lock_value->ParseFromString(value)) return false; return true; } } // namespace lock using namespace sharkstore::monitor; kvrpcpb::LockValue *Range::LockGet(const std::string &key) { RANGE_LOG_DEBUG("lock get: key[%s]", EncodeToHexString(key).c_str()); std::string val; if (!store_->Get(key, &val).ok()) { FLOG_WARN("lock get: no key[%s]", EncodeToHexString(key).c_str()); return nullptr; } RANGE_LOG_DEBUG("lock get ok: key[%s] val[%s]", EncodeToHexString(key).c_str(), EncodeToHexString(val).c_str()); auto ret = new kvrpcpb::LockValue; int64_t version = 0; // not used std::string extend(""); // not used if (!lock::DecodeValue(&version, ret, &extend, val)) { RANGE_LOG_WARN("lock get: decode value failed, key[%s]", EncodeToHexString(key).c_str()); return nullptr; } if (ret->delete_time() > 0 && ret->delete_time() <= getticks()) { RANGE_LOG_WARN("key[%s] deteled at time %ld", EncodeToHexString(key).c_str(), ret->delete_time()); return nullptr; } /*if (getticks() - ret->update_time() > DEFAULT_LOCK_DELETE_TIME_MILLSEC) { FLOG_WARN("key[%s] deteled last update time %ld > 3s", EncodeToHexString(key).c_str(), ret->update_time()); return nullptr; }*/ RANGE_LOG_DEBUG("lock get parse: key[%s] val[%s]", EncodeToHexString(key).c_str(), ret->DebugString().c_str()); return ret; } void Range::Lock(common::ProtoMessage *msg, kvrpcpb::DsLockRequest &req) { RANGE_LOG_DEBUG("lock request: %s", req.DebugString().c_str()); context_->Statistics()->PushTime(HistogramType::kQWait, get_micro_second() - msg->begin_time); std::string encode_key; lock::EncodeKey(&encode_key, meta_.GetTableID(), &req.req().key()); //req.mutable_req()->set_key(encode_key); //auto& key = req.req().key(); errorpb::Error *err = nullptr; do { if (!VerifyLeader(err)) { RANGE_LOG_WARN("Lock error: %s", err->message().c_str()); break; } if (!KeyInRange(encode_key, err)) { RANGE_LOG_WARN("Lock error: %s", err->message().c_str()); break; } auto epoch = req.header().range_epoch(); if (!EpochIsEqual(epoch, err)) { RANGE_LOG_WARN("Lock error: %s", err->message().c_str()); break; } auto ret = SubmitCmd(msg, req.header(), [&req](raft_cmdpb::Command &cmd) { cmd.set_cmd_type(raft_cmdpb::CmdType::Lock); cmd.set_allocated_lock_req(req.release_req()); }); if (!ret.ok()) { RANGE_LOG_ERROR("Lock raft submit error: %s", ret.ToString().c_str()); err = RaftFailError(); } } while (false); if (err != nullptr) { auto resp = new kvrpcpb::DsLockResponse; SendError(msg, req.header(), resp, err); } } Status Range::ApplyLock(const raft_cmdpb::Command &cmd) { RANGE_LOG_DEBUG("apply lock: %s", cmd.DebugString().c_str()); Status ret; errorpb::Error *err = nullptr; auto atime = get_micro_second(); auto req = cmd.lock_req(); auto resp = new (kvrpcpb::DsLockResponse); do { auto &epoch = cmd.verify_epoch(); if (!EpochIsEqual(epoch, err)) { RANGE_LOG_WARN("ApplyLock error: %s", err->message().c_str()); resp->mutable_resp()->set_code(LOCK_EPOCH_ERROR); resp->mutable_resp()->set_error(err->message()); break; } std::string encode_key; lock::EncodeKey(&encode_key, meta_.GetTableID(), &req.key()); auto val = LockGet(encode_key); // 允许相同id的重复执行lock if (val != nullptr) { if (req.value().id() != val->id()) { RANGE_LOG_WARN("ApplyLock error: lock [%s] is existed", req.key().c_str()); resp->mutable_resp()->set_code(LOCK_EXISTED); resp->mutable_resp()->set_error("already locked"); resp->mutable_resp()->set_value(val->value()); resp->mutable_resp()->set_update_time(val->update_time()); break; } } auto btime = get_micro_second(); req.mutable_value()->set_update_time(getticks()); if (req.value().delete_time() != 0) { req.mutable_value()->set_delete_time(req.value().delete_time() + getticks()); } std::string value_buf; int64_t version = 0; std::string extend(""); lock::EncodeValue(&value_buf, version, req.value(), &extend); ret = store_->Put(encode_key, value_buf); context_->Statistics()->PushTime(HistogramType::kQWait, get_micro_second() - btime); if (!ret.ok()) { RANGE_LOG_ERROR("ApplyLock failed, code:%d, msg:%s", ret.code(), ret.ToString().c_str()); resp->mutable_resp()->set_code(LOCK_STORE_FAILED); resp->mutable_resp()->set_error("lock failed"); break; } if (cmd.cmd_id().node_id() == node_id_) { auto len = encode_key.size() + req.value().ByteSizeLong(); CheckSplit(len); } delete val; RANGE_LOG_INFO("ApplyLock: lock [%s] is locked by %s", req.key().c_str(), req.value().by().c_str()); } while (false); if (cmd.cmd_id().node_id() == node_id_) { ReplySubmit(cmd, resp, err, atime); } else if (err != nullptr) { delete err; } return ret; } void Range::LockUpdate(common::ProtoMessage *msg, kvrpcpb::DsLockUpdateRequest &req) { RANGE_LOG_DEBUG("lock update: %s", req.DebugString().c_str()); context_->Statistics()->PushTime(HistogramType::kQWait, get_micro_second() - msg->begin_time); std::string encode_key; lock::EncodeKey(&encode_key, meta_.GetTableID(), &req.req().key()); //req.mutable_req()->set_key(encode_key); //auto &key = req.req().key(); errorpb::Error *err = nullptr; do { if (!VerifyLeader(err)) { RANGE_LOG_WARN("LockUpdate error: %s", err->message().c_str()); break; } if (!KeyInRange(encode_key, err)) { RANGE_LOG_WARN("LockUpdate error: %s", err->message().c_str()); break; } auto epoch = req.header().range_epoch(); if (!EpochIsEqual(epoch, err)) { RANGE_LOG_WARN("LockUpdate error: %s", err->message().c_str()); break; } auto ret = SubmitCmd(msg, req.header(), [&req](raft_cmdpb::Command &cmd) { cmd.set_cmd_type(raft_cmdpb::CmdType::LockUpdate); cmd.set_allocated_lock_update_req(req.release_req()); }); if (!ret.ok()) { RANGE_LOG_ERROR("LockUpdate raft submit error: %s", ret.ToString().c_str()); err = RaftFailError(); } } while (false); if (err != nullptr) { auto resp = new kvrpcpb::DsLockUpdateResponse; SendError(msg, req.header(), resp, err); } } Status Range::ApplyLockUpdate(const raft_cmdpb::Command &cmd) { RANGE_LOG_DEBUG("apply lock update: %s", cmd.DebugString().c_str()); Status ret; errorpb::Error *err = nullptr; auto atime = get_micro_second(); auto &req = cmd.lock_update_req(); auto resp = new (kvrpcpb::DsLockUpdateResponse); do { auto &epoch = cmd.verify_epoch(); if (!EpochIsEqual(epoch, err)) { RANGE_LOG_WARN("ApplyLockUpdate error: %s", err->message().c_str()); resp->mutable_resp()->set_code(LOCK_EPOCH_ERROR); resp->mutable_resp()->set_error(err->message()); break; } std::string encode_key; lock::EncodeKey(&encode_key, meta_.GetTableID(), &req.key()); auto val = LockGet(encode_key); if (val == nullptr) { RANGE_LOG_WARN("ApplyLockUpdate error: lock [%s] is not existed", req.key().c_str()); resp->mutable_resp()->set_code(LOCK_NOT_EXIST); resp->mutable_resp()->set_error("not exist"); break; } if (req.id() != val->id()) { RANGE_LOG_WARN("ApplyLockUpdate error: lock [%s] can not update with id " "%s != %s", req.key().c_str(), req.id().c_str(), val->id().c_str()); resp->mutable_resp()->set_code(LOCK_ID_MISMATCHED); resp->mutable_resp()->set_error("wrong id: " + val->id()); resp->mutable_resp()->set_value(val->value()); resp->mutable_resp()->set_update_time(val->update_time()); break; } val->set_update_time(getticks() + req.update_time()); if (req.update_value().size() != 0) { val->set_value(req.update_value()); } auto btime = get_micro_second(); std::string value_buf; int64_t version = 0; std::string extend(""); val->set_value(req.update_value()); val->set_update_time(req.update_time()); val->set_by(req.by()); lock::EncodeValue(&value_buf, version, *val, &extend); ret = store_->Put(encode_key, value_buf); context_->Statistics()->PushTime(HistogramType::kQWait, get_micro_second() - btime); if (!ret.ok()) { RANGE_LOG_ERROR("ApplyLockUpdate failed, code:%d, msg:%s", ret.code(), ret.ToString().c_str()); resp->mutable_resp()->set_code(LOCK_STORE_FAILED); resp->mutable_resp()->set_error("lock update failed"); break; } if (cmd.cmd_id().node_id() == node_id_) { auto len = encode_key.size() + req.ByteSizeLong(); CheckSplit(len); } delete val; RANGE_LOG_INFO("ApplyLockUpdate: lock [%s] is update", req.key().c_str()); } while (false); if (cmd.cmd_id().node_id() == node_id_) { ReplySubmit(cmd, resp, err, atime); } else if (err != nullptr) { delete err; } return ret; } void Range::Unlock(common::ProtoMessage *msg, kvrpcpb::DsUnlockRequest &req) { RANGE_LOG_DEBUG("unlock: %s", req.DebugString().c_str()); context_->Statistics()->PushTime(HistogramType::kQWait, get_micro_second() - msg->begin_time); std::string encode_key; lock::EncodeKey(&encode_key, meta_.GetTableID(), &req.req().key()); //req.mutable_req()->set_key(encode_key); //auto &key = req.req().key(); errorpb::Error *err = nullptr; do { if (!VerifyLeader(err)) { break; } if (!KeyInRange(encode_key, err)) { break; } auto ret = SubmitCmd(msg, req.header(), [&req](raft_cmdpb::Command &cmd) { cmd.set_cmd_type(raft_cmdpb::CmdType::Unlock); cmd.set_allocated_unlock_req(req.release_req()); }); if (!ret.ok()) { RANGE_LOG_ERROR("Unlock raft submit error: %s", ret.ToString().c_str()); err = RaftFailError(); } } while (false); if (err != nullptr) { RANGE_LOG_WARN("Unlock error: %s", err->message().c_str()); auto resp = new kvrpcpb::DsUnlockResponse; SendError(msg, req.header(), resp, err); } return; } Status Range::ApplyUnlock(const raft_cmdpb::Command &cmd) { RANGE_LOG_DEBUG("apply unlock: %s", cmd.DebugString().c_str()); Status ret; errorpb::Error *err = nullptr; auto atime = get_micro_second(); auto &req = cmd.unlock_req(); auto resp = new (kvrpcpb::DsUnlockResponse); do { auto &epoch = cmd.verify_epoch(); if (!EpochIsEqual(epoch, err)) { RANGE_LOG_WARN("ApplyUnlock error: %s", err->message().c_str()); resp->mutable_resp()->set_code(LOCK_EPOCH_ERROR); resp->mutable_resp()->set_error(err->message()); break; } std::string encode_key; lock::EncodeKey(&encode_key, meta_.GetTableID(), &req.key()); auto val = LockGet(encode_key); if (val == nullptr) { RANGE_LOG_WARN("ApplyUnlock error: lock [%s] is not existed", req.key().c_str()); resp->mutable_resp()->set_code(LOCK_NOT_EXIST); resp->mutable_resp()->set_error("not exist"); break; } if (req.id() != val->id()) { RANGE_LOG_WARN("ApplyUnlock error: lock [%s] not locked with id %s", req.key().c_str(), req.id().c_str()); resp->mutable_resp()->set_code(LOCK_ID_MISMATCHED); resp->mutable_resp()->set_error("wrong id: " + val->id()); resp->mutable_resp()->set_value(val->value()); resp->mutable_resp()->set_update_time(val->update_time()); break; } auto btime = get_micro_second(); ret = store_->Delete(encode_key); context_->Statistics()->PushTime(HistogramType::kQWait, get_micro_second() - btime); if (!ret.ok()) { RANGE_LOG_ERROR("ApplyUnlock failed, code:%d, msg:%s", ret.code(), ret.ToString().c_str()); resp->mutable_resp()->set_code(LOCK_STORE_FAILED); resp->mutable_resp()->set_error("unlock failed"); resp->mutable_resp()->set_value(val->value()); resp->mutable_resp()->set_update_time(val->update_time()); break; } delete val; RANGE_LOG_INFO("ApplyUnlock: lock [%s] is unlock by %s", EncodeToHexString(req.key()).c_str(), req.by().c_str()); std::string decode_key = req.key(); //std::string decode_key; //auto decode_ret = lock::DecodeKey(decode_key, req.key()); //if (!decode_ret) { // FLOG_ERROR("ApplyUnlock decode lock key [%s] failed", EncodeToHexString(req.key()).c_str()); //} std::string err_msg; watchpb::WatchKeyValue watch_kv; watch_kv.add_key(decode_key); auto retCnt = WatchNotify(watchpb::DELETE, watch_kv, watch_kv.version(), err_msg); if (retCnt < 0) { RANGE_LOG_ERROR("ApplyUnlock WatchNotify failed, ret:%d, msg:%s", retCnt, err_msg.c_str()); } else { RANGE_LOG_DEBUG("ApplyUnlock WatchNotify success, count:%d, msg:%s", retCnt, err_msg.c_str()); } } while (false); if (cmd.cmd_id().node_id() == node_id_) { ReplySubmit(cmd, resp, err, atime); } else if (err != nullptr) { delete err; } return ret; } void Range::UnlockForce(common::ProtoMessage *msg, kvrpcpb::DsUnlockForceRequest &req) { RANGE_LOG_DEBUG("unlock force: %s", req.DebugString().c_str()); context_->Statistics()->PushTime(HistogramType::kQWait, get_micro_second() - msg->begin_time); std::string encode_key; lock::EncodeKey(&encode_key, meta_.GetTableID(), &req.req().key()); //req.mutable_req()->set_key(encode_key); //auto &key = req.req().key(); errorpb::Error *err = nullptr; do { if (!VerifyLeader(err)) { break; } if (!KeyInRange(encode_key, err)) { break; } auto ret = SubmitCmd(msg, req.header(), [&req](raft_cmdpb::Command &cmd) { cmd.set_cmd_type(raft_cmdpb::CmdType::UnlockForce); cmd.set_allocated_unlock_force_req(req.release_req()); }); if (!ret.ok()) { RANGE_LOG_ERROR("UnlockForce raft submit error: %s", ret.ToString().c_str()); err = RaftFailError(); } } while (false); if (err != nullptr) { RANGE_LOG_WARN("UnlockForce error: %s", err->message().c_str()); auto resp = new kvrpcpb::DsUnlockForceResponse; SendError(msg, req.header(), resp, err); } } Status Range::ApplyUnlockForce(const raft_cmdpb::Command &cmd) { RANGE_LOG_DEBUG("apply unlock force: %s", cmd.DebugString().c_str()); Status ret; errorpb::Error *err = nullptr; auto atime = get_micro_second(); auto &req = cmd.unlock_force_req(); auto resp = new (kvrpcpb::DsUnlockForceResponse); do { auto &epoch = cmd.verify_epoch(); if (!EpochIsEqual(epoch, err)) { FLOG_WARN("Range %" PRIu64 " UnlockForce error: %s", id_, err->message().c_str()); resp->mutable_resp()->set_code(LOCK_EPOCH_ERROR); resp->mutable_resp()->set_error(err->message()); break; } std::string encode_key; lock::EncodeKey(&encode_key, meta_.GetTableID(), &req.key()); auto val = LockGet(encode_key); if (val == nullptr) { FLOG_WARN("Range %" PRIu64 " ApplyUnlockForce error: lock [%s] is not existed", id_, req.key().c_str()); resp->mutable_resp()->set_code(LOCK_NOT_EXIST); resp->mutable_resp()->set_error("not exist"); break; } auto btime = get_micro_second(); ret = store_->Delete(encode_key); context_->Statistics()->PushTime(HistogramType::kQWait, get_micro_second() - btime); if (!ret.ok()) { RANGE_LOG_ERROR("ApplyForceUnlock failed, code:%d, msg:%s", ret.code(), ret.ToString().c_str()); resp->mutable_resp()->set_code(LOCK_STORE_FAILED); resp->mutable_resp()->set_error("force unlock failed"); resp->mutable_resp()->set_value(val->value()); resp->mutable_resp()->set_update_time(val->update_time()); break; } delete val; RANGE_LOG_INFO("ApplyForceUnlock: lock [%s] is unlock by %s", EncodeToHexString(req.key()).c_str(), req.by().c_str()); std::string decode_key = req.key(); //std::string decode_key; //auto decode_ret = lock::DecodeKey(decode_key, req.key()); //if (!decode_ret) { // FLOG_ERROR("ApplyUnlockForce decode lock key [%s] failed", EncodeToHexString(req.key()).c_str()); //} std::string err_msg; watchpb::WatchKeyValue watch_kv; watch_kv.add_key(decode_key); auto retCnt = WatchNotify(watchpb::DELETE, watch_kv, watch_kv.version(), err_msg); if (retCnt < 0) { FLOG_ERROR("ApplyUnlockForce WatchNotify failed, ret:%d, msg:%s", retCnt, err_msg.c_str()); } else { FLOG_DEBUG("ApplyUnlockForce WatchNotify success, count:%d, msg:%s", retCnt, err_msg.c_str()); } } while (false); if (cmd.cmd_id().node_id() == node_id_) { ReplySubmit(cmd, resp, err, atime); } else if (err != nullptr) { delete err; } return ret; } void Range::LockWatch(common::ProtoMessage *msg, watchpb::DsWatchRequest& req) { errorpb::Error *err = nullptr; if (req.req().kv().key_size() != 1) { RANGE_LOG_INFO("LockWatch: kv key size[%d] != 1", req.req().kv().key_size()); err = new errorpb::Error; err->set_message("key list length != 1"); auto resp = new watchpb::DsWatchResponse; resp->mutable_resp()->set_code(LOCK_PARAMETER_ERROR); SendError(msg, req.header(), resp, err); return; } std::string encode_key; lock::EncodeKey(&encode_key, meta_.GetTableID(), &req.req().kv().key(0)); RANGE_LOG_INFO("LockWatch: lock watch key[%s] encode[%s]", req.req().kv().key(0).c_str(), EncodeToHexString(encode_key).c_str()); do { if (!VerifyLeader(err)) { break; } if (!KeyInRange(encode_key, err)) { break; } auto val = LockGet(encode_key); if (val == nullptr) { FLOG_WARN("LockWatch error: lock encode key [%s] is not existed", EncodeToHexString(encode_key).c_str()); //err = new errorpb::Error; //err->set_message("lock is not existed"); auto resp = new watchpb::DsWatchResponse; resp->mutable_resp()->set_code(LOCK_NOT_EXIST); SendError(msg, req.header(), resp, err); return; } std::vector<watch::Key*> keys; keys.push_back(new watch::Key(req.req().kv().key(0))); //int64_t expireTime = (req.req().longpull() > 0)?getticks() + req.req().longpull():msg->expire_time; int64_t expireTime = (req.req().longpull() > 0)?get_micro_second() + req.req().longpull()*1000:msg->expire_time*1000; auto w_ptr = std::make_shared<watch::Watcher>(meta_.GetTableID(), keys, 0, expireTime, msg); auto w_code = context_->WatchServer()->AddKeyWatcher(w_ptr, store_.get()); if (w_code != watch::WATCH_OK) { FLOG_WARN("LockWatch error: lock [%s] add key watcher failed", EncodeToHexString(encode_key).c_str()); err = new errorpb::Error; err->set_message("add key watcher failed"); break; } } while (false); if (err != nullptr) { FLOG_WARN("range[%" PRIu64 "] LockWatch error: %s", id_, err->message().c_str()); auto resp = new watchpb::DsWatchResponse; SendError(msg, req.header(), resp, err); } } void Range::LockScan(common::ProtoMessage *msg, kvrpcpb::DsLockScanRequest &req) { FLOG_DEBUG("lock scan: %s", req.DebugString().c_str()); context_->Statistics()->PushTime(HistogramType::kQWait, get_micro_second() - msg->begin_time); errorpb::Error *err = nullptr; auto ds_resp = new kvrpcpb::DsLockScanResponse; auto start = std::max(req.req().start(), start_key_); auto limit = std::min(req.req().limit(), meta_.GetEndKey()); std::unique_ptr<storage::Iterator> iterator(store_->NewIterator(start, limit)); int max_count = checkMaxCount(static_cast<int64_t >(req.req().count())); auto resp = ds_resp->mutable_resp(); uint64_t count = 0; uint64_t total_size = 0; for (int i = 0; iterator->Valid() && i < max_count; ++i) { auto kv = resp->add_info(); FLOG_DEBUG("scan key: %s", iterator->key().c_str()); kv->set_key(std::move(iterator->key())); kv->mutable_value()->ParseFromString(iterator->value()); count++; total_size += iterator->key().length()+iterator->value().length(); iterator->Next(); } if (resp->info_size() > 0) { auto lastIdx = resp->info_size()-1; auto lastInfo = resp->info(lastIdx); resp->set_last_key(lastInfo.key()); FLOG_DEBUG("last key: %s", lastInfo.key().c_str()); } common::SetResponseHeader(req.header(), ds_resp->mutable_header(), err); context_->SocketSession()->Send(msg, ds_resp); } } // namespace range } }
35.570605
126
0.569027
[ "vector" ]
f705828499d55be41dd08afe7ca55b74f7dfc85b
3,585
cpp
C++
src/demo_framework/src/AgentPath.cpp
werchou/ai-programming-with-lua
d9290fde56c01839e75bb2ea7d13c8f6c3594f5e
[ "Zlib" ]
2
2021-03-31T07:25:53.000Z
2021-04-19T14:06:37.000Z
src/demo_framework/src/AgentPath.cpp
werchou/ai-programming-with-lua
d9290fde56c01839e75bb2ea7d13c8f6c3594f5e
[ "Zlib" ]
null
null
null
src/demo_framework/src/AgentPath.cpp
werchou/ai-programming-with-lua
d9290fde56c01839e75bb2ea7d13c8f6c3594f5e
[ "Zlib" ]
1
2021-02-22T04:38:57.000Z
2021-02-22T04:38:57.000Z
/** * Copyright (c) 2013 David Young dayoung@goliathdesigns.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. */ #include "PrecompiledHeaders.h" #include "demo_framework/include/AgentPath.h" AgentPath::AgentPath() : PolylinePathway() { } AgentPath::AgentPath( const std::vector<Ogre::Vector3>& points, const Ogre::Real radius, const bool cyclic) { OpenSteer::Vec3 vec3Point[MAX_PATH_POINTS]; assert(points.size() < MAX_PATH_POINTS); std::vector<Ogre::Vector3>::const_iterator it; int count = 0; for (it = points.begin(); it != points.end(); ++it) { const Ogre::Vector3& vec = *it; vec3Point[count].x = vec.x; vec3Point[count].y = vec.y; vec3Point[count].z = vec.z; ++count; } initialize(count, vec3Point, static_cast<float>(radius), cyclic); } AgentPath::~AgentPath() { } AgentPath::AgentPath(const AgentPath& path) { initialize(path.pointCount, path.points, path.radius, path.cyclic); } AgentPath& AgentPath::operator=(const AgentPath& path) { initialize(path.pointCount, path.points, path.radius, path.cyclic); return *this; } Ogre::Real AgentPath::GetDistanceAlongPath(const Ogre::Vector3& position) const { const OpenSteer::Vec3 vec3(position.x, position.y, position.z); return const_cast<AgentPath*>(this)->mapPointToPathDistance(vec3); } Ogre::Vector3 AgentPath::GetNearestPointOnPath( const Ogre::Vector3& position) const { const OpenSteer::Vec3 vec3(position.x, position.y, position.z); OpenSteer::Vec3 tangent; float outside; const OpenSteer::Vec3 pointOnPath = const_cast<AgentPath*>(this)->mapPointToPath(vec3, tangent, outside); return Ogre::Vector3(pointOnPath.x, pointOnPath.y, pointOnPath.z); } size_t AgentPath::GetNumberOfPathPoints() const { return pointCount; } Ogre::Real AgentPath::GetPathLength() const { // XXX(8-22-13) - This variable may become private in the future. return Ogre::Real(totalPathLength); } void AgentPath::GetPathPoints(std::vector<Ogre::Vector3>& outPoints) const { outPoints.clear(); const size_t pathPoints = GetNumberOfPathPoints(); for (size_t index = 0; index < pathPoints; ++index) { const OpenSteer::Vec3& vec3 = points[index]; outPoints.push_back(Ogre::Vector3(vec3.x, vec3.y, vec3.z)); } } Ogre::Vector3 AgentPath::GetPointOnPath(const Ogre::Real distance) const { const OpenSteer::Vec3 pointOnPath = const_cast<AgentPath*>(this)->mapPathDistanceToPoint(distance); return Ogre::Vector3(pointOnPath.x, pointOnPath.y, pointOnPath.z); } Ogre::Real AgentPath::GetRadius() const { return radius; } unsigned int AgentPath::GetSegmentCount() const { return static_cast<unsigned int>(pointCount) - 1; }
26.753731
79
0.709623
[ "vector" ]
f706f98a922cf4989fb9005474bc5a3be62fd99e
262
cpp
C++
leetcode/189/main.cpp
yukienomiya/competitive-programming
6f5e502ba66da2f62fb37aaa786a841f64bb192a
[ "MIT" ]
null
null
null
leetcode/189/main.cpp
yukienomiya/competitive-programming
6f5e502ba66da2f62fb37aaa786a841f64bb192a
[ "MIT" ]
null
null
null
leetcode/189/main.cpp
yukienomiya/competitive-programming
6f5e502ba66da2f62fb37aaa786a841f64bb192a
[ "MIT" ]
null
null
null
#include <vector> using namespace std; class Solution { public: void rotate(vector<int> &nums, int k) { vector<int> nums2 = nums; int l = size(nums); for (int i = 0; i < l; i++) { nums2[(i + k) % l] = nums[i]; } nums = nums2; } };
17.466667
41
0.530534
[ "vector" ]
f7078ae937e0af8b8789ceb0d42ab71f1a98d9b2
20,494
cpp
C++
inetsrv/iis/svcs/infocomm/log/comlog/context.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/iis/svcs/infocomm/log/comlog/context.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/iis/svcs/infocomm/log/comlog/context.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1995-1996 Microsoft Corporation Module Name : Context.cxx Abstract: The file contains the implementation of the Context object. A context job is an object which stored in the logging request queue. Author: Terence Kwan ( terryk ) 18-Sep-1996 Project: IIS Logging 3.0 --*/ #include "precomp.hxx" #include "comlog.hxx" #include "iiscnfg.h" // // statics // CRITICAL_SECTION COMLOG_CONTEXT::sm_listLock; LIST_ENTRY COMLOG_CONTEXT::sm_ContextListHead; CHAR g_pszResFromGetComputerName [MAX_PATH] =""; VOID COMLOG_CONTEXT::LoadPluginModules( VOID ) /*++ Routine Description: load all the plugin module from the metabase Arguments: None. Return Value: None --*/ { DWORD cb; MB mb( (IMDCOM*) m_pvIMDCOM ); PCHAR p; CLSID clsid; WCHAR buf[MAX_PATH]; BUFFER szLoadOrder(1024); PCHAR pEnd; DWORD dwLogType; DWORD nPlugins = 0; PPLUGIN_NODE pluginNode; LPUNKNOWN punk; ILogPluginEx *pComponent; bool fExtended; HRESULT hr ; // // get the config information from the metabase // LockExclusive( ); if ( !mb.Open(m_strMetabasePath.QueryStr()) ) { DBGPRINTF((DBG_CONTEXT,"Unable to open MB path %s[err %x]\n", m_strMetabasePath.QueryStr(), GetLastError())); goto exit; } // // If logging disabled, bail out // if ( mb.GetDword( "", MD_LOG_TYPE, IIS_MD_UT_SERVER, &dwLogType)) { if ( dwLogType == MD_LOG_TYPE_DISABLED ) { DBGPRINTF((DBG_CONTEXT,"Logging disabled\n")); goto exit; } } // // Read the plugin order list // retry: cb = szLoadOrder.QuerySize( ); if ( !mb.GetString( "", MD_LOG_PLUGIN_ORDER, IIS_MD_UT_SERVER, (PCHAR)szLoadOrder.QueryPtr( ), &cb )) { DWORD err = GetLastError(); if ( err == ERROR_INSUFFICIENT_BUFFER ) { DBGPRINTF((DBG_CONTEXT,"Buff Too Small[%d] need[%d]\n", szLoadOrder.QuerySize(), cb )); if ( cb > szLoadOrder.QuerySize( ) ) { szLoadOrder.Resize( cb ); goto retry; } } DBGPRINTF((DBG_CONTEXT,"Error getting pluginOrder[err %x]\n", err)); mb.Close(); goto exit; } mb.Close(); // // Parse it // pEnd = (PCHAR)szLoadOrder.QueryPtr( ); for ( p = pEnd; pEnd != NULL; p = pEnd + 1 ) { if ( *p == '\0' ) { break; } // // pEnd will point to the next entry // pEnd = strchr(p, ','); if ( pEnd != NULL ) { *pEnd = '\0'; } // // p points to the CLSID // DBGPRINTF((DBG_CONTEXT,"Got Logging clsid %s\n",p)); if ( !TsIsNtServer() ) { // // odbc not allowed // if ( _stricmp(p,ODBCLOG_CLSID) == 0 ) { DBGPRINTF((DBG_CONTEXT,"ODBC logging not allowed for NTW\n")); continue; } } // // convert string to CLSID // mbstowcs( (WCHAR *)buf, p, MAX_PATH); hr = CLSIDFromString( buf, &clsid ); if (FAILED(hr)) { // // cannot convert string // DBGPRINTF((DBG_CONTEXT,"Cannot convert string to CLSID: %s\n",p)); continue; } hr = CoCreateInstance( clsid, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (void **)&punk ); if (FAILED(hr)) { // // cannot convert string // DBGPRINTF((DBG_CONTEXT,"Cannot create instance: %s\n",p)); continue; } hr = punk->QueryInterface(IID_ILogPluginEx, (void **)&pComponent); if (SUCCEEDED(hr)) { fExtended = true; } else { fExtended = false; // // Try getting the older interface // hr = punk->QueryInterface(IID_ILogPlugin, (void **)&pComponent); } punk->Release(); if (FAILED(hr)) { DBGPRINTF((DBG_CONTEXT,"Unable to get the Extended or the Standard Plugin Interface.\n")); continue; } // // Add the component // pluginNode = (PPLUGIN_NODE)LocalAlloc( 0, sizeof(PLUGIN_NODE) ); if ( pluginNode == NULL ) { pComponent->Release( ); continue; } pluginNode->pComponent = pComponent; pluginNode->fSupportsExtendedInterface = fExtended; nPlugins++; InsertTailList(&m_pluginList, &pluginNode->ListEntry); // // Is this the default? // if ( _stricmp(p,EXTLOG_CLSID) == 0 ) { m_fDefault = TRUE; DBGPRINTF((DBG_CONTEXT,"Logging Extended[%d]\n", m_fDefault)); } } if ( nPlugins > 1 ) { m_fDefault = FALSE; } exit: Unlock( ); return; } // COMLOG_CONTEXT::LoadPlugInModules VOID COMLOG_CONTEXT::ReleasePluginModules( VOID ) { PLIST_ENTRY listEntry; PPLUGIN_NODE pluginModule; LockExclusive( ); m_fDefault = FALSE; while ( !IsListEmpty(&m_pluginList) ) { listEntry = RemoveHeadList( &m_pluginList ); pluginModule = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); pluginModule->pComponent->Release( ); LocalFree( pluginModule ); } Unlock( ); return; } // COMLOG_CONTEXT::ReleasePlugInModules COMLOG_CONTEXT::COMLOG_CONTEXT( LPCSTR pszInstanceName, LPCSTR pszMetabasePath, LPVOID pvIMDCOM ) : m_fDefault (FALSE), m_pvIMDCOM (pvIMDCOM) /*++ Routine Description: Constructor for clapi context object Arguments: pszInstanceName - name of the instance Return Value: --*/ { DWORD cbComputerNameSize = sizeof(g_pszResFromGetComputerName); MB mb( (IMDCOM*) m_pvIMDCOM ); InitializeListHead( &m_pluginList ); InitializeListHead( &m_PublicListEntry); m_strInstanceName.Copy(pszInstanceName); m_strMetabasePath.Copy(pszMetabasePath); if (g_pszResFromGetComputerName[0]==0) { if ( !GetComputerName( g_pszResFromGetComputerName, &cbComputerNameSize) ) { strcpy(g_pszResFromGetComputerName,"<Server>"); } } m_strComputerName.Copy(g_pszResFromGetComputerName); // // Add into the global list // EnterCriticalSection( &COMLOG_CONTEXT::sm_listLock ); InsertTailList( &COMLOG_CONTEXT::sm_ContextListHead, &m_ContextListEntry ); LeaveCriticalSection( &COMLOG_CONTEXT::sm_listLock ); // // Load all the plugin modules // LoadPluginModules( ); return; } // COMLOG_CONTEXT::COMLOG COMLOG_CONTEXT::~COMLOG_CONTEXT() /*++ Routine Description: destructor Arguments: Return Value: --*/ { PLIST_ENTRY listEntry; PInetLogPublic pPublic; EnterCriticalSection( &COMLOG_CONTEXT::sm_listLock ); LockExclusive(); RemoveEntryList(&m_ContextListEntry); ReleasePluginModules(); for ( listEntry = m_PublicListEntry.Flink; listEntry != &m_PublicListEntry; listEntry = listEntry->Flink ) { pPublic = (PInetLogPublic)CONTAINING_RECORD( listEntry, CInetLogPublic, m_ListEntry ); pPublic->m_pContext = NULL; } Unlock(); LeaveCriticalSection( &COMLOG_CONTEXT::sm_listLock ); } // COMLOG_CONTEXT::~COMLOG() VOID COMLOG_CONTEXT::LogInformation( PINETLOG_INFORMATION pLogInfo ) { PLIST_ENTRY listEntry; PPLUGIN_NODE plugin; CInetLogInformation inetLog; LockShared(); if ( m_pluginList.Flink != &m_pluginList ) { // logging is enabled inetLog.CanonicalizeLogRecord( pLogInfo, m_strInstanceName.QueryStr(), m_strComputerName.QueryStr(), m_fDefault ); for ( listEntry = m_pluginList.Flink; listEntry != &m_pluginList; listEntry = listEntry->Flink ) { plugin = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); plugin->pComponent->LogInformation( &inetLog ); } } Unlock(); } // COMLOG_CONTEXT::LogInformation VOID COMLOG_CONTEXT::LogInformation( IInetLogInformation *pLogObj ) { PLIST_ENTRY listEntry; PPLUGIN_NODE plugin; LockShared(); if ( m_pluginList.Flink != &m_pluginList ) { // logging is enabled for ( listEntry = m_pluginList.Flink; listEntry != &m_pluginList; listEntry = listEntry->Flink ) { plugin = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); plugin->pComponent->LogInformation( pLogObj ); } } Unlock(); } // COMLOG_CONTEXT::LogInformation VOID COMLOG_CONTEXT::LogCustomInformation( IN DWORD cCount, IN PCUSTOM_LOG_DATA pCustomLogData, IN LPSTR szHeaderSuffix ) { // // This function is supported only if the extended interface was found on the plugin // PLIST_ENTRY listEntry; PPLUGIN_NODE plugin; LockShared(); for ( listEntry = m_pluginList.Flink; listEntry != &m_pluginList; listEntry = listEntry->Flink ) { plugin = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); if (plugin->fSupportsExtendedInterface) { plugin->pComponent->LogCustomInformation( cCount, pCustomLogData, szHeaderSuffix); } } Unlock(); } // COMLOG_CONTEXT::LogCustomInformation VOID COMLOG_CONTEXT::NotifyChange( VOID ) { TerminateLog(); ReleasePluginModules( ); LoadPluginModules( ); InitializeLog( m_strInstanceName.QueryStr(), m_strMetabasePath.QueryStr(), (CHAR*)m_pvIMDCOM ); } // COMLOG_CONTEXT::NotifyChange VOID COMLOG_CONTEXT::GetConfig( IN INETLOG_CONFIGURATIONA *pConfigInfo ) { // // just return the first configuration information // PLIST_ENTRY listEntry; PPLUGIN_NODE plugin; LockShared( ); listEntry = m_pluginList.Flink; if (listEntry != &m_pluginList){ plugin = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); plugin->pComponent->GetConfig( sizeof(INETLOG_CONFIGURATIONA), (BYTE *)pConfigInfo); Unlock( ); return; } // // No Log // Unlock( ); pConfigInfo->inetLogType = INET_LOG_DISABLED; return; } // GetConfig VOID COMLOG_CONTEXT::SetConfig( IN INETLOG_CONFIGURATIONA *pConfigInfo ) { // // check the log type and call the proper setconfig function // MB mb( (IMDCOM*) m_pvIMDCOM ); // // NTW restrictions // if ( (pConfigInfo->inetLogType == INET_LOG_TO_SQL) && !TsIsNtServer() ) { return; } if ( !mb.Open( m_strMetabasePath.QueryStr(), METADATA_PERMISSION_READ | METADATA_PERMISSION_WRITE )) { return; } // // Release all // ReleasePluginModules( ); switch (pConfigInfo->inetLogType) { case INET_LOG_TO_FILE: switch (pConfigInfo->u.logFile.ilFormat) { case INET_LOG_FORMAT_INTERNET_STD: mb.SetString("", MD_LOG_PLUGIN_ORDER, IIS_MD_UT_SERVER, ASCLOG_CLSID ); break; case INET_LOG_FORMAT_NCSA: mb.SetString("", MD_LOG_PLUGIN_ORDER, IIS_MD_UT_SERVER, NCSALOG_CLSID ); break; case INET_LOG_FORMAT_EXTENDED: mb.SetString("", MD_LOG_PLUGIN_ORDER, IIS_MD_UT_SERVER, EXTLOG_CLSID ); mb.SetDword( "", MD_LOGEXT_FIELD_MASK, IIS_MD_UT_SERVER, pConfigInfo->u.logFile.dwFieldMask ); break; default: DBGPRINTF((DBG_CONTEXT,"SetConfig: Invalid Format type %d\n", pConfigInfo->inetLogType)); goto no_log; } mb.SetDword( "", MD_LOGFILE_PERIOD, IIS_MD_UT_SERVER, pConfigInfo->u.logFile.ilPeriod ); if (pConfigInfo->u.logFile.ilPeriod == INET_LOG_PERIOD_NONE ) { mb.SetDword( "", MD_LOGFILE_TRUNCATE_SIZE, IIS_MD_UT_SERVER, pConfigInfo-> u.logFile.cbSizeForTruncation ); } mb.SetString( "", MD_LOGFILE_DIRECTORY, IIS_MD_UT_SERVER, pConfigInfo->u.logFile.rgchLogFileDirectory ); mb.SetDword( "", MD_LOG_TYPE, IIS_MD_UT_SERVER, MD_LOG_TYPE_ENABLED ); break; case INET_LOG_TO_SQL: mb.SetString("", MD_LOG_PLUGIN_ORDER, IIS_MD_UT_SERVER, ODBCLOG_CLSID ); mb.SetString( "", MD_LOGSQL_DATA_SOURCES, IIS_MD_UT_SERVER, pConfigInfo->u.logSql.rgchDataSource ); mb.SetString( "", MD_LOGSQL_TABLE_NAME, IIS_MD_UT_SERVER, pConfigInfo->u.logSql.rgchTableName ); mb.SetString( "", MD_LOGSQL_USER_NAME, IIS_MD_UT_SERVER, pConfigInfo->u.logSql.rgchUserName ); mb.SetString( "", MD_LOGSQL_PASSWORD, IIS_MD_UT_SERVER, pConfigInfo->u.logSql.rgchPassword, METADATA_INHERIT|METADATA_SECURE ); mb.SetDword( "", MD_LOG_TYPE, IIS_MD_UT_SERVER, MD_LOG_TYPE_ENABLED ); break; case INET_LOG_DISABLED: default: goto no_log; } exit: mb.Save(); mb.Close(); return; no_log: mb.SetString( "", MD_LOG_PLUGIN_ORDER, IIS_MD_UT_SERVER, "" ); mb.SetDword( "", MD_LOG_TYPE, IIS_MD_UT_SERVER, MD_LOG_TYPE_DISABLED ); goto exit; } // COMLOG_CONTEXT::SetConfig VOID COMLOG_CONTEXT::QueryExtraLogFields( PDWORD pcbSize, PCHAR pszLogFields ) { PLIST_ENTRY listEntry; PPLUGIN_NODE plugin; LockShared( ); listEntry = m_pluginList.Flink; if (listEntry != &m_pluginList){ plugin = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); plugin->pComponent->QueryExtraLoggingFields( pcbSize, pszLogFields ); // // handle just the 1st component // Unlock( ); return; } Unlock( ); *pcbSize = 0; *pszLogFields = '\0'; return; } // COMLOG_CONTEXT::QueryExtraLogFields VOID COMLOG_CONTEXT::InitializeLog( LPCSTR pszInstanceName, LPCSTR pszMetabasePath, LPVOID ) { PLIST_ENTRY listEntry; PPLUGIN_NODE plugin; LockExclusive(); for ( listEntry = m_pluginList.Flink; listEntry != &m_pluginList; listEntry = listEntry->Flink ) { plugin = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); plugin->pComponent->InitializeLog( pszInstanceName, pszMetabasePath, (PCHAR)m_pvIMDCOM ); if ( m_fDefault ) { INETLOG_CONFIGURATIONA config; m_fDefault = FALSE; if ( SUCCEEDED( plugin->pComponent->GetConfig( sizeof(config), (PBYTE)&config ) ) ) { if ( (config.u.logFile.ilFormat == INET_LOG_FORMAT_EXTENDED) && (config.u.logFile.dwFieldMask == DEFAULT_EXTLOG_FIELDS) ) { m_fDefault = TRUE; } } } } Unlock(); } // COMLOG_CONTEXT::InitializeLog VOID COMLOG_CONTEXT::TerminateLog( VOID ) { PLIST_ENTRY listEntry; PPLUGIN_NODE plugin; LockExclusive( ); for ( listEntry = m_pluginList.Flink; listEntry != &m_pluginList; listEntry = listEntry->Flink ) { plugin = (PPLUGIN_NODE)CONTAINING_RECORD( listEntry, PLUGIN_NODE, ListEntry ); plugin->pComponent->TerminateLog( ); } Unlock( ); } // COMLOG_CONTEXT::TerminateLog
23.637832
107
0.459305
[ "object" ]
f7088db4855d8829ef3f09a6698fea8c77c96bd4
1,562
cpp
C++
src/ftxui/component/menu_test.cpp
azchatlanin/FTXUI
cdd63398493559238cf7c93bb76a4e6401696db3
[ "MIT" ]
1
2022-01-24T23:53:32.000Z
2022-01-24T23:53:32.000Z
src/ftxui/component/menu_test.cpp
azchatlanin/FTXUI
cdd63398493559238cf7c93bb76a4e6401696db3
[ "MIT" ]
null
null
null
src/ftxui/component/menu_test.cpp
azchatlanin/FTXUI
cdd63398493559238cf7c93bb76a4e6401696db3
[ "MIT" ]
null
null
null
#include <gtest/gtest-message.h> // for Message #include <gtest/gtest-test-part.h> // for TestPartResult, SuiteApiResolver, TestFactoryImpl #include <memory> // for allocator, __shared_ptr_access, shared_ptr #include <string> // for string, basic_string #include <vector> // for vector #include "ftxui/component/captured_mouse.hpp" // for ftxui #include "ftxui/component/component.hpp" // for Menu #include "ftxui/component/component_base.hpp" // for ComponentBase #include "ftxui/component/component_options.hpp" // for MenuOption #include "ftxui/component/event.hpp" // for Event, Event::ArrowDown, Event::Return #include "ftxui/util/ref.hpp" // for Ref #include "gtest/gtest_pred_impl.h" // for Test, EXPECT_EQ, TEST using namespace ftxui; TEST(MenuTest, RemoveEntries) { int focused_entry = 0; int selected = 0; std::vector<std::string> entries = {"1", "2", "3"}; MenuOption option; option.focused_entry = &focused_entry; auto menu = Menu(&entries, &selected, option); EXPECT_EQ(selected, 0); EXPECT_EQ(focused_entry, 0); menu->OnEvent(Event::ArrowDown); menu->OnEvent(Event::ArrowDown); menu->OnEvent(Event::Return); EXPECT_EQ(selected, 2); EXPECT_EQ(focused_entry, 2); entries.resize(2); EXPECT_EQ(selected, 2); EXPECT_EQ(focused_entry, 2); (void)menu->Render(); EXPECT_EQ(selected, 1); EXPECT_EQ(focused_entry, 1); } // Copyright 2022 Arthur Sonzogni. All rights reserved. // Use of this source code is governed by the MIT license that can be found in // the LICENSE file.
31.877551
92
0.713828
[ "render", "vector" ]
f70cbba67c33b8cf30602275f3883337e7b1fac7
12,830
cpp
C++
main.cpp
hensm/ddccli
300d01e43628e222bc8dddf5423da7717d10ccf8
[ "MIT" ]
33
2019-12-31T10:48:56.000Z
2022-03-31T14:57:41.000Z
main.cpp
hensm/ddccli
300d01e43628e222bc8dddf5423da7717d10ccf8
[ "MIT" ]
4
2019-02-02T20:07:35.000Z
2021-08-31T03:16:10.000Z
main.cpp
hensm/ddccli
300d01e43628e222bc8dddf5423da7717d10ccf8
[ "MIT" ]
2
2021-08-31T09:39:56.000Z
2022-01-13T01:32:28.000Z
/* Copyright (c) 2018 Matt Hensman <m@matt.tf> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "HighLevelMonitorConfigurationAPI.h" #include "PhysicalMonitorEnumerationAPI.h" #include "windows.h" #include "winuser.h" #include <iostream> #include <map> #include <string> #include <argagg.hpp> #include <json.hpp> using json = nlohmann::json; void logError(const char* message) { std::cerr << "error: " << message << std::endl; } std::map<std::string, HANDLE> handles; void populateHandlesMap() { // Cleanup if (!handles.empty()) { for (auto const& handle : handles) { DestroyPhysicalMonitor(handle.second); } handles.clear(); } struct Monitor { HMONITOR handle; std::vector<HANDLE> physicalHandles; }; auto monitorEnumProc = [](HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) -> BOOL { auto monitors = reinterpret_cast<std::vector<struct Monitor>*>(dwData); monitors->push_back({ hMonitor, {} }); return TRUE; }; std::vector<struct Monitor> monitors; EnumDisplayMonitors( NULL, NULL, monitorEnumProc, reinterpret_cast<LPARAM>(&monitors)); // Get physical monitor handles for (auto& monitor : monitors) { DWORD numPhysicalMonitors; LPPHYSICAL_MONITOR physicalMonitors = NULL; if (!GetNumberOfPhysicalMonitorsFromHMONITOR(monitor.handle, &numPhysicalMonitors)) { throw std::runtime_error("Failed to get physical monitor count."); exit(EXIT_FAILURE); } physicalMonitors = new PHYSICAL_MONITOR[numPhysicalMonitors]; if (physicalMonitors == NULL) { throw std::runtime_error( "Failed to allocate physical monitor array"); } if (!GetPhysicalMonitorsFromHMONITOR( monitor.handle, numPhysicalMonitors, physicalMonitors)) { throw std::runtime_error("Failed to get physical monitors."); } for (DWORD i = 0; i <= numPhysicalMonitors; i++) { monitor.physicalHandles.push_back( physicalMonitors[(numPhysicalMonitors == 1 ? 0 : i)] .hPhysicalMonitor); } delete[] physicalMonitors; } DISPLAY_DEVICE adapterDev; adapterDev.cb = sizeof(DISPLAY_DEVICE); // Loop through adapters int adapterDevIndex = 0; while (EnumDisplayDevices(NULL, adapterDevIndex++, &adapterDev, 0)) { DISPLAY_DEVICE displayDev; displayDev.cb = sizeof(DISPLAY_DEVICE); // Loop through displays (with device ID) on each adapter int displayDevIndex = 0; while (EnumDisplayDevices(adapterDev.DeviceName, displayDevIndex++, &displayDev, EDD_GET_DEVICE_INTERFACE_NAME)) { // Check valid target if (!(displayDev.StateFlags & DISPLAY_DEVICE_ATTACHED_TO_DESKTOP) || displayDev.StateFlags & DISPLAY_DEVICE_MIRRORING_DRIVER) { continue; } for (auto const& monitor : monitors) { MONITORINFOEX monitorInfo; monitorInfo.cbSize = sizeof(MONITORINFOEX); GetMonitorInfo(monitor.handle, &monitorInfo); for (size_t i = 0; i < monitor.physicalHandles.size(); i++) { /** * Re-create DISPLAY_DEVICE.DeviceName with * MONITORINFOEX.szDevice and monitor index. */ std::string monitorName = static_cast<std::string>(monitorInfo.szDevice) + "\\Monitor" + std::to_string(i); std::string deviceName = static_cast<std::string>(displayDev.DeviceName); // Match and store against device ID if (monitorName == deviceName) { handles.insert( { static_cast<std::string>(displayDev.DeviceID), monitor.physicalHandles[i] }); break; } } } } } } struct MonitorBrightness { unsigned long maximumBrightness; unsigned long currentBrightness; }; struct MonitorContrast { unsigned long maximumContrast; unsigned long currentContrast; }; MonitorBrightness getMonitorBrightness(HANDLE hMonitor) { DWORD minimumBrightness; DWORD maximumBrightness; DWORD currentBrightness; if (!GetMonitorBrightness(hMonitor, &minimumBrightness, &currentBrightness, &maximumBrightness)) { throw std::runtime_error("failed to get monitor brightness"); } MonitorBrightness brightness = { static_cast<unsigned long>(maximumBrightness), static_cast<unsigned long>(currentBrightness) }; return brightness; } MonitorContrast getMonitorContrast(HANDLE hMonitor) { DWORD minimumContrast; DWORD maximumContrast; DWORD currentContrast; if (!GetMonitorContrast( hMonitor, &minimumContrast, &currentContrast, &maximumContrast)) { throw std::runtime_error("failed to get monitor contrast"); } MonitorContrast contrast = { static_cast<unsigned long>(maximumContrast), static_cast<unsigned long>(currentContrast) }; return contrast; } void setMonitorBrightness(HANDLE hMonitor, unsigned long level) { auto brightness = getMonitorBrightness(hMonitor); if (level > brightness.maximumBrightness) { throw std::runtime_error("brightness level exceeds maximum"); } if (!SetMonitorBrightness(hMonitor, static_cast<DWORD>(level))) { throw std::runtime_error("failed to set monitor brightness"); } } void setMonitorContrast(HANDLE hMonitor, unsigned long level) { auto contrast = getMonitorContrast(hMonitor); if (level > contrast.maximumContrast) { throw std::runtime_error("contrast level exceeds maximum"); } if (!SetMonitorContrast(hMonitor, static_cast<DWORD>(level))) { throw std::runtime_error("failed to set monitor contrast"); } } int main(int argc, char** argv) { argagg::parser parser{ { { "setBrightness", { "-b", "--brightness" }, "Sets monitor brightness", 1 }, { "getBrightness", { "-B", "--get-brightness" }, "Gets monitor brightness", 0 }, { "setContrast", { "-c", "--contrast" }, "Sets monitor contrast", 1 }, { "getContrast", { "-C", "--get-contrast" }, "Gets monitor contrast", 0 }, { "help", { "-h", "--help" }, "Prints this help message", 0 }, { "version", { "-v", "--version" }, "Prints the version number", 0 }, { "list", { "-l", "--list" }, "Lists connected monitors", 0 }, { "monitor", { "-m", "--monitor" }, "Selects a monitor to adjust. If not specified, actions affects all monitors.", 1 }, { "json", { "-j", "--json" }, "Outputs action results as JSON", 0 } } }; std::string versionString = "v0.1.0"; std::ostringstream usage; usage << argv[0] << " " << versionString << std::endl << "Usage: " << argv[0] << " [options]" << std::endl; try { argagg::parser_results args = parser.parse(argc, argv); // Help if (args["help"]) { std::cout << usage.str() << parser; return EXIT_SUCCESS; } if (args["version"]) { argagg::fmt_ostream fmt(std::cout); fmt << "ddccli " << versionString << std::endl << "Copyright (c) 2021 Matt Hensman <m@matt.tf>" << std::endl << "MIT License" << std::endl; return EXIT_SUCCESS; } bool shouldOutputJson = false; json jsonOutput; if (args["json"]) { shouldOutputJson = true; } try { populateHandlesMap(); if (args["list"]) { if (shouldOutputJson) { jsonOutput["monitorList"] = json::array(); } for (auto const& [ id, handle ] : handles) { if (shouldOutputJson) { jsonOutput["monitorList"].push_back(id); } else { std::cout << id << std::endl; } } } if (args["monitor"]) { std::string selectedMonitorName = args["monitor"]; // Remove all non-matching monitors from the map for (auto const& [ id, handle ] : handles) { if (id != selectedMonitorName) { handles.erase(id); } } if (handles.empty()) { throw std::runtime_error("monitor doesn't exist"); } } if (args["setBrightness"]) { unsigned long level = args["setBrightness"]; for (auto const& [ id, handle ] : handles) { setMonitorBrightness(handle, level); } } if (args["getBrightness"]) { if (args["monitor"]) { auto it = handles.find(args["monitor"]); if (it == handles.end()) { throw std::runtime_error("monitor not found"); } auto brightness = getMonitorBrightness(it->second).currentBrightness; if (shouldOutputJson) { jsonOutput["brightness"] = brightness; } else { std::cout << brightness << std::endl; } } else { throw std::runtime_error( "no monitor specified to query brightness"); } } if (args["setContrast"]) { unsigned long level = args["setContrast"]; for (auto const& [ id, handle ] : handles) { setMonitorContrast(handle, level); } } if (args["getContrast"]) { if (args["monitor"]) { auto it = handles.find(args["monitor"]); if (it == handles.end()) { throw std::runtime_error("monitor not found"); } auto contrast = getMonitorContrast(it->second).currentContrast; if (shouldOutputJson) { jsonOutput["contrast"] = contrast; } else { std::cout << contrast << std::endl; } } else { throw std::runtime_error( "no monitor specified to query contrast"); } } } catch (const std::runtime_error e) { logError(e.what()); return EXIT_FAILURE; } if (shouldOutputJson) { std::cout << jsonOutput << std::endl; } } catch (const std::exception& e) { std::cerr << "Error parsing arguments: " << e.what() << std::endl << usage.str() << parser; return EXIT_FAILURE; } return EXIT_SUCCESS; }
31.446078
91
0.537178
[ "vector" ]
f7153b607ec7dc049ebb66a60814b44499246659
6,713
cc
C++
systems/rendering/test/pose_vector_test.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
2
2021-02-25T02:01:02.000Z
2021-03-17T04:52:04.000Z
systems/rendering/test/pose_vector_test.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
null
null
null
systems/rendering/test/pose_vector_test.cc
RobotLocomotion/drake-python3.7
ae397a4c6985262d23e9675b9bf3927c08d027f5
[ "BSD-3-Clause" ]
1
2021-06-13T12:05:39.000Z
2021-06-13T12:05:39.000Z
#include "drake/systems/rendering/pose_vector.h" #include <memory> #include <sstream> #include <string> #include <vector> #include <Eigen/Dense> #include <Eigen/Geometry> #include <gtest/gtest.h> #include "drake/common/symbolic.h" #include "drake/common/test_utilities/eigen_matrix_compare.h" #include "drake/common/test_utilities/symbolic_test_util.h" namespace drake { using Eigen::Vector3d; using math::RigidTransform; using math::RigidTransformd; using symbolic::test::ExprEqual; namespace systems { namespace rendering { namespace { // Tests that the default PoseVector is initialized to identity. GTEST_TEST(PoseVector, InitiallyIdentity) { const PoseVector<double> vec; EXPECT_TRUE(CompareMatrices(RigidTransformd().GetAsMatrix4(), vec.get_transform().GetAsMatrix4())); // Check that the underlying storage has the values we'd expect. for (int i = 0; i < 3; ++i) { // p_WA is entirely zero. EXPECT_EQ(0.0, vec[i]); } // The real part of R_WA is cos(0) = 1. EXPECT_EQ(1.0, vec[3]); for (int i = 4; i < vec.kSize; ++i) { // The imaginary parts of R_WA are sin(0) = 0. EXPECT_EQ(0.0, vec[i]); } } // Tests the fully-parameterized PoseVector. GTEST_TEST(PoseVector, FullyParameterizedCtor) { const Eigen::Quaternion<double> rotation(0.5, 0.5, 0.5, 0.5); const Eigen::Vector3d origin(1.0, 2.0, 3.0); const Eigen::Translation3d translation(origin); const PoseVector<double> vec(rotation, translation); RigidTransformd transform_expected(rotation, origin); EXPECT_TRUE(CompareMatrices(transform_expected.GetAsMatrix4(), vec.get_transform().GetAsMatrix4())); EXPECT_TRUE(CompareMatrices( RigidTransformd(translation).GetAsMatrix4(), RigidTransformd(vec.get_translation().vector()).GetAsMatrix4())); EXPECT_TRUE(CompareMatrices(rotation.matrix(), vec.get_rotation().matrix())); } GTEST_TEST(PoseVector, Rotation) { PoseVector<double> vec; // Rotate by 2π/3 around the axis {1, 1, 1}. vec.set_rotation(Eigen::Quaternion<double>(0.5, 0.5, 0.5, 0.5)); // Check that the data was copied. for (int i = 3; i < vec.kSize; ++i) { EXPECT_EQ(0.5, vec[i]); } // Check that the isometry transforms the x-axis to the y-axis. const RigidTransformd X_WA = vec.get_transform(); const Eigen::Vector3d p_in = {1.0, 0.0, 0.0}; const Eigen::Vector3d p_out = X_WA * p_in; EXPECT_EQ((Eigen::Vector3d{0.0, 1.0, 0.0}), p_out); } GTEST_TEST(PoseVector, Translation) { PoseVector<double> vec; vec.set_translation(Eigen::Translation<double, 3>(1.0, 2.0, 3.0)); // Check that the data was copied. for (int i = 0; i < 3; ++i) { EXPECT_EQ(1.0 * (i + 1), vec[i]); } // Check that the isometry is a pure translation. const RigidTransformd X_WA = vec.get_transform(); const Eigen::Vector3d p_in = {1.0, 2.0, 3.0}; const Eigen::Vector3d p_out = X_WA * p_in; EXPECT_EQ((Eigen::Vector3d{2.0, 4.0, 6.0}), p_out); } // Tests that PoseVector<T>::Clone has PoseVector type. GTEST_TEST(PoseVector, Clone) { const PoseVector<double> vec; auto clone = vec.Clone(); EXPECT_NE(nullptr, dynamic_cast<PoseVector<double>*>(clone.get())); } GTEST_TEST(PoseVector, Symbolic) { PoseVector<symbolic::Expression> vec; vec[0] = symbolic::Variable("x"); vec[1] = symbolic::Variable("y"); vec[2] = symbolic::Variable("z"); vec[3] = symbolic::Variable("w"); vec[4] = symbolic::Variable("a"); vec[5] = symbolic::Variable("b"); vec[6] = symbolic::Variable("c"); // Spot-check some terms from the output. const RigidTransform<symbolic::Expression> X_WA = vec.get_transform(); const auto matrix = X_WA.GetAsMatrix4(); // Note: RigidTransform normalizes the quaternion in an order of operations // that leads to a *very* specific set of symbolic expressions. That is what // is represented below. // The squared L2 norm of the quaternion; if it were already unit length, // this factor would be one and the expressions down below would be much // simpler. const symbolic::Expression q_norm2 = vec[3] * vec[3] + vec[4] * vec[4] + vec[5] * vec[5] + vec[6] * vec[6]; // Rotation - first element on the diagonal EXPECT_PRED2( ExprEqual, 1 - vec[5] * ((2 * vec[5]) / q_norm2) - vec[6] * ((2 * vec[6]) / q_norm2), matrix(0, 0)); // Rotation - second element in the third row EXPECT_PRED2( ExprEqual, vec[5] * ((2 * vec[6]) / q_norm2) + vec[3] * ((2 * vec[4]) / q_norm2), matrix(2, 1)); // Translation - fourth element in the second row EXPECT_PRED2(ExprEqual, vec[1], matrix(1, 3)); } GTEST_TEST(PoseVector, Autodiff) { PoseVector<AutoDiffXd> vec; for (int i = 0; i < vec.size(); ++i) { // Initialize the position to {0.5, 0.5, 0.5}, and the rotation to // 2π/3 around the axis {1, 1, 1}. vec[i].value() = 0.5; // Initialize the Jacobian to the identity matrix. vec[i].derivatives().resize(vec.kSize); for (int j = 0; j < vec.kSize; ++j) { vec[i].derivatives()[j] = j == i ? 1.0 : 0.0; } } // Spot-check some terms from the output. const RigidTransform<AutoDiffXd> X_WA = vec.get_transform(); auto matrix = X_WA.GetAsMatrix4(); // Converting quaternion to RigidTransform performs a normalization step. // As illustrated in the `Symbolic` test the value stored in M(0, 0) is: // // 2b² + 2c² // M(0,0) = 1 - ────────── // |q|² // // ∂ 4b(a² + w²) // ── M(0, 0) = - ─────────────, and // ∂b (|q|²)² // // ∂ 4w(b² + c²) // ── M(0, 0) = ───────────── // ∂w (|q|²)² // const double w = vec[3].value(); const double a = vec[4].value(); const double b = vec[5].value(); const double c = vec[6].value(); const double q_norm2 = w * w + a * a + b * b + c * c; const double dMdb = -4 * b * (a * a + w * w) / (q_norm2 * q_norm2); EXPECT_DOUBLE_EQ(dMdb, matrix(0, 0).derivatives()[5]); const double dMdw = 4 * w * (b * b + c * c) / (q_norm2 * q_norm2); EXPECT_DOUBLE_EQ(dMdw, matrix(0, 0).derivatives()[3]); // The partial of the third element of the transformation vector with respect // to "z" is 1. With respect to anything else, it's zero. const auto& dz = matrix(2, 3).derivatives(); for (int i = 0; i < dz.size(); ++i) { EXPECT_EQ(i == 2 ? 1 : 0, dz[i]); } // The bottom row of the rotation matrix is constant. for (int i = 0; i < 4; ++i) { const auto& partials = matrix(3, i).derivatives(); for (int j = 0; j < partials.size(); ++j) { EXPECT_EQ(0.0, partials[j]); } } } }; // namespace } // namespace rendering } // namespace systems } // namespace drake
33.733668
80
0.628929
[ "geometry", "vector" ]
f7287955b80a131cddf68ce7b3dbfe4426ee4bc4
5,359
cpp
C++
tests/util_test.cpp
sheny1xuan/casbin-cpp
5fd4056277d9ddb433b8db53dc5edd0a1a8a1237
[ "Apache-2.0" ]
null
null
null
tests/util_test.cpp
sheny1xuan/casbin-cpp
5fd4056277d9ddb433b8db53dc5edd0a1a8a1237
[ "Apache-2.0" ]
null
null
null
tests/util_test.cpp
sheny1xuan/casbin-cpp
5fd4056277d9ddb433b8db53dc5edd0a1a8a1237
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 The casbin Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This is a test file for testing the Utility methods in casbin */ #include <casbin/casbin.h> #include <gtest/gtest.h> namespace { void TestEscapeAssertionFn(const std::string& s, const std::string& res) { std::string my_res = casbin::EscapeAssertion(s); ASSERT_EQ(my_res, res); } TEST(TestUtil, TestEscapeAssertion) { TestEscapeAssertionFn("r.attr.value == p.attr", "r_attr.value == p_attr"); TestEscapeAssertionFn("r.attp.value || p.attr", "r_attp.value || p_attr"); TestEscapeAssertionFn("r.attp.value &&p.attr", "r_attp.value &&p_attr"); TestEscapeAssertionFn("r.attp.value >p.attr", "r_attp.value >p_attr"); TestEscapeAssertionFn("r.attp.value <p.attr", "r_attp.value <p_attr"); TestEscapeAssertionFn("r.attp.value +p.attr", "r_attp.value +p_attr"); TestEscapeAssertionFn("r.attp.value -p.attr", "r_attp.value -p_attr"); TestEscapeAssertionFn("r.attp.value *p.attr", "r_attp.value *p_attr"); TestEscapeAssertionFn("r.attp.value /p.attr", "r_attp.value /p_attr"); TestEscapeAssertionFn("!r.attp.value /p.attr", "!r_attp.value /p_attr"); TestEscapeAssertionFn("g(r.sub, p.sub) == p.attr", "g(r_sub, p_sub) == p_attr"); TestEscapeAssertionFn("g(r.sub,p.sub) == p.attr", "g(r_sub,p_sub) == p_attr"); TestEscapeAssertionFn("(r.attp.value || p.attr)p.u", "(r_attp.value || p_attr)p_u"); } void TestRemoveCommentsFn(const std::string& s, const std::string& res) { std::string my_res = casbin::RemoveComments(s); ASSERT_EQ(my_res, res); } TEST(TestUtil, TestRemoveComments) { TestRemoveCommentsFn("r.act == p.act # comments", "r.act == p.act"); TestRemoveCommentsFn("r.act == p.act#comments", "r.act == p.act"); TestRemoveCommentsFn("r.act == p.act###", "r.act == p.act"); TestRemoveCommentsFn("### comments", ""); TestRemoveCommentsFn("r.act == p.act", "r.act == p.act"); } void TestArrayEqualsFn(const std::vector<std::string>& a, const std::vector<std::string>& b, bool res) { bool my_res = casbin::ArrayEquals(a, b); ASSERT_EQ(my_res, res); } TEST(TestUtil, TestArrayEquals) { TestArrayEqualsFn({"a", "b", "c"}, {"a", "b", "c"}, true); TestArrayEqualsFn({"a", "b", "c"}, {"a", "b"}, false); TestArrayEqualsFn({"a", "b", "c"}, {"a", "c", "b"}, true); TestArrayEqualsFn({"a", "b", "c"}, {}, false); } void testContainEval(std::string s, bool res) { ASSERT_EQ(casbin::HasEval(s), res); } TEST(TestUtil, TestContainEval) { testContainEval("eval() && a && b && c", true); testContainEval("eval) && a && b && c", false); testContainEval("eval)( && a && b && c", false); testContainEval("eval(c * (a + b)) && a && b && c", true); testContainEval("xeval() && a && b && c", false); } void testReplaceEvalWithMap(std::string s, std::unordered_map<std::string, std::string> sets, std::string res) { ASSERT_EQ(casbin::ReplaceEvalWithMap(s, sets), res); } TEST(TestUtil, TestReplaceEvalWithMap) { testReplaceEvalWithMap("eval(rule1)", {{"rule1", "a == b"}}, "a == b"); testReplaceEvalWithMap("eval(rule1) && c && d", {{"rule1", "a == b"}}, "a == b && c && d"); testReplaceEvalWithMap("eval(rule1)", {{}}, "eval(rule1)"); testReplaceEvalWithMap("eval(rule1) && c && d", {{}}, "eval(rule1) && c && d"); testReplaceEvalWithMap("eval(rule1) || eval(rule2)", {{"rule1", "a == b"}, {"rule2", "a == c"}}, "a == b || a == c"); testReplaceEvalWithMap("eval(rule1) || eval(rule2) && c && d", {{"rule1", "a == b"}, {"rule2", "a == c"}}, "a == b || a == c && c && d"); testReplaceEvalWithMap("eval(rule1) || eval(rule2)", {{"rule1", "a == b"}}, "a == b || eval(rule2)"); testReplaceEvalWithMap("eval(rule1) || eval(rule2) && c && d", {{"rule1", "a == b"}}, "a == b || eval(rule2) && c && d"); testReplaceEvalWithMap("eval(rule1) || eval(rule2)", {{"rule2", "a == b"}}, "eval(rule1) || a == b"); testReplaceEvalWithMap("eval(rule1) || eval(rule2) && c && d", {{"rule2", "a == b"}}, "eval(rule1) || a == b && c && d"); testReplaceEvalWithMap("eval(rule1) || eval(rule2)", {}, "eval(rule1) || eval(rule2)"); testReplaceEvalWithMap("eval(rule1) || eval(rule2) && c && d", {}, "eval(rule1) || eval(rule2) && c && d"); } void testGetEvalValue(std::string s, std::vector<std::string> res) { auto myRes = casbin::GetEvalValue(s); ASSERT_EQ(res.size(), myRes.size()); for (size_t i = 0; i < res.size(); i++) { ASSERT_EQ(res[i], myRes[i]); } } TEST(TestUtil, TestGetEvalValue) { testGetEvalValue("eval(a) && a && b && c", {"a"}); testGetEvalValue("a && eval(a) && b && c", {"a"}); testGetEvalValue("eval(a) && eval(b) && a && b && c", {"a", "b"}); testGetEvalValue("a && eval(a) && eval(b) && b && c", {"a", "b"}); } } // namespace
46.6
167
0.61672
[ "vector" ]
f72d90f82e952ba892d9c92c63582cfc73a57482
3,126
cpp
C++
OrderMGMT.cpp
Jackie890621/Order-management
099f8e44d4d48cd5dc9a67427f8a4503d4392eed
[ "MIT" ]
null
null
null
OrderMGMT.cpp
Jackie890621/Order-management
099f8e44d4d48cd5dc9a67427f8a4503d4392eed
[ "MIT" ]
null
null
null
OrderMGMT.cpp
Jackie890621/Order-management
099f8e44d4d48cd5dc9a67427f8a4503d4392eed
[ "MIT" ]
null
null
null
#include "OrderMGMT.h" // Function to insert a new order. // date: Date of a order. // id: Order ID. node *insert(node *Root, unsigned id, unsigned date) { node *current; if (Root == NULL) { current = (node *)malloc(sizeof(node)); assert(current != NULL); data.push_back(date); current->date = date; current->id = id; current->left = NULL; current->right = NULL; return current; } if (date < Root->date) { Root->left = insert(Root->left, id, date); } else if (date > Root->date) { Root->right = insert(Root->right, id, date); } return Root; } void OrderMGMT::addOrder(unsigned date, unsigned id) { root = insert(root, id, date); } // Function to delete orders from a given range. // start: Begin date. // end: End date. node *del(node *Root, int key) { if (Root->date > key) { Root->left = del(Root->left, key); } else if (Root->date < key) { Root->right = del(Root->right, key); } else { if (Root->left == NULL || Root->right == NULL) { if (Root->left != NULL) { Root = Root->left; } else { Root = Root->right; } } else { node *current = Root->right; while (current->left != NULL) { current = current->left; } Root->date = current->date; Root->id = current->id; Root->right = del(Root->right, current->date); } } return Root; } void OrderMGMT::deleteOrders(unsigned start, unsigned end) { int count = -1; vector<int> temp; sort(data.begin(), data.end()); if (data.front() > end || data.back() < start) { return; } for (int i = 0; i < data.size(); i++) { count++; temp.push_back(data[i]); if (data[i] >= start && data[i] <= end) { root = del(root, data[i]); temp.pop_back(); } } data.assign(temp.begin(), temp.end()); } // Function to return a STL list of order IDs from a given range of dates. // start: Begin date. // end: End date. unsigned get_id(node *Root, int date) { unsigned ans; if (date == Root->date) { return Root->id; } if (date > Root->date) { ans = get_id(Root->right, date); } else if (date < Root->date) { ans = get_id(Root->left, date); } return ans; } list<unsigned> OrderMGMT::searchByDate(unsigned start, unsigned end) { sort(data.begin(), data.end()); list<unsigned> ans; for (int i = 0; i < data.size(); i++) { if (data[i] >= start && data[i] <= end) { ans.push_back(get_id(root, data[i])); } } return ans; } // Function to return a STL list of order IDs starting from the a_th rank of date to the b_th rank of date. // a_th: Begin rank. // b_th: End rank. list<unsigned> OrderMGMT::searchByDateRank(unsigned a_th, unsigned b_th) { sort(data.begin(), data.end()); list<unsigned> ans; if (a_th > data.size()) { // } else if (b_th > data.size()) { for (int i = a_th; i <= data.size(); i++) { ans.push_back(get_id(root, data[i - 1])); } } else { for (int i = a_th; i <= b_th; i++) { ans.push_back(get_id(root, data[i - 1])); } } return ans; }
23.328358
107
0.565579
[ "vector" ]
f7366abfe523be014c3c4da44f16165e80d97bbf
3,621
cpp
C++
src/AglImagePool.cpp
philiphubbard/Agl
7ee5c6911d4cf2199f1ebf56f28d01d3e051e789
[ "MIT" ]
1
2016-04-09T00:41:41.000Z
2016-04-09T00:41:41.000Z
src/AglImagePool.cpp
philiphubbard/Agl
7ee5c6911d4cf2199f1ebf56f28d01d3e051e789
[ "MIT" ]
null
null
null
src/AglImagePool.cpp
philiphubbard/Agl
7ee5c6911d4cf2199f1ebf56f28d01d3e051e789
[ "MIT" ]
null
null
null
// Copyright (c) 2013 Philip M. Hubbard // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // http://opensource.org/licenses/MIT // // AglImagePool.cpp // #include "AglImagePool.h" #include <thread> #include <vector> namespace Agl { class ImagePool::Imp { public: Imp() : width(0), height(0), bytesPerPixel(0) {} GLsizei width; GLsizei height; GLsizei bytesPerPixel; std::mutex mutex; std::vector<GLubyte*> pool; }; ImagePool::ImagePool() : _m(new Imp) { } ImagePool::~ImagePool() { while (!_m->pool.empty()) { delete [] _m->pool.back(); _m->pool.pop_back(); } } void ImagePool::setImageSize(GLsizei width, GLsizei height, GLsizei bytesPerPixel) { std::lock_guard<std::mutex> lock(_m->mutex); if ((_m->width != 0) || (_m->height != 0) || (_m->bytesPerPixel != 0)) { throw std::runtime_error("Agl::ImagePool::setImageSize() " "can be called only once"); } _m->width = width; _m->height = height; _m->bytesPerPixel = bytesPerPixel; } GLsizei ImagePool::imageWidth() const { std::lock_guard<std::mutex> lock(_m->mutex); return _m->width; } GLsizei ImagePool::imageHeight() const { std::lock_guard<std::mutex> lock(_m->mutex); return _m->height; } GLsizei ImagePool::bytesPerPixel() const { std::lock_guard<std::mutex> lock(_m->mutex); return _m->bytesPerPixel; } GLubyte* ImagePool::alloc() { std::lock_guard<std::mutex> lock(_m->mutex); if ((_m->width == 0) || (_m->height == 0) || (_m->bytesPerPixel == 0)) { throw std::runtime_error("Agl::ImagePool::setImageSize() " "must be called (once) to set a non-zero " "image size"); } if (_m->pool.empty()) { return new GLubyte [_m->width * _m->height * _m->bytesPerPixel]; } else { GLubyte* result = _m->pool.back(); _m->pool.pop_back(); return result; } } void ImagePool::free(GLubyte* image) { std::lock_guard<std::mutex> lock(_m->mutex); _m->pool.push_back(image); } }
29.680328
80
0.562276
[ "vector" ]
f73bab9a1a5413dddf71c1369d5415d431d78f2c
1,331
cpp
C++
test/unit/test_itertools.cpp
mdklatt/pypp
4b17bdf8d57b777d6f22c0f359ce5e93bd81c5bc
[ "MIT" ]
null
null
null
test/unit/test_itertools.cpp
mdklatt/pypp
4b17bdf8d57b777d6f22c0f359ce5e93bd81c5bc
[ "MIT" ]
null
null
null
test/unit/test_itertools.cpp
mdklatt/pypp
4b17bdf8d57b777d6f22c0f359ce5e93bd81c5bc
[ "MIT" ]
null
null
null
/** * Test suite for the itertools module. * * Link all test files with the `gtest_main` library to create a command line * test runner. */ #include <iterator> #include <exception> #include <limits> #include <vector> #include <gtest/gtest.h> #include "pypp/pypp.hpp" using namespace pypp::itertools; using std::begin; using std::numeric_limits; using std::vector; /** * Test the itertools::count() function. */ TEST(itertools, count) { vector<ssize_t> values; for (const auto value: count<ssize_t>(-1, 2)) { values.emplace_back(value); if (values.size() == 3) { break; } } ASSERT_EQ(values, vector<ssize_t>({-1, 1, 3})); } /** * Test the itertools::count() function with a step of 0. */ TEST(itertools, count_fixed) { vector<ssize_t> values; for (const auto value: count<ssize_t>(1, 0)) { values.emplace_back(value); if (values.size() == 3) { break; } } ASSERT_EQ(values, vector<ssize_t>({1, 1, 1})); } /** * Test the itertools::count() function for an overflow. */ TEST(itertools, count_overflow) { static const auto start(numeric_limits<ssize_t>::min()); auto counter(count<ssize_t>(start, -1)); auto it(begin(counter)); ASSERT_EQ(start, *it); ASSERT_THROW(++it, std::out_of_range); }
21.467742
77
0.623591
[ "vector" ]
f740ce52d46d9836f3b6a5447301b8769863d9f4
1,131
cpp
C++
LeetCode/100/606.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
LeetCode/100/606.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
LeetCode/100/606.cpp
K-ona/C-_Training
d54970f7923607bdc54fc13677220d1b3daf09e5
[ "Apache-2.0" ]
null
null
null
// created by Kona @VSCode #include <algorithm> #include <iostream> #include <map> #include <string> #include <queue> #include <vector> #include <string.h> #define LOCAL_TEST typedef long long ll; using std::cin; using std::cout; using std::endl; using std::map; using std::queue; using std::string; using std::vector; struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(): val(0), left(nullptr), right(nullptr) {} TreeNode(int x): val(x), left(nullptr), right(nullptr) {} }; class Solution { public: string tree2str(TreeNode* root) { string res; res.reserve(30000); DFS(root, res); return res; } void DFS(TreeNode* root, string& s) { s += std::to_string(root->val); if (!root->left and !root->right) return; s += '('; if (root->left) DFS(root->left, s); s += ')'; if (root->right) { s += '('; DFS(root->right, s); s += ')'; } } }; int main() { std::ios_base::sync_with_stdio(false); #ifdef LOCAL_TEST freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif /* code */ return 0; }
17.4
59
0.597701
[ "vector" ]
f7460860d4a78d516ba70f570d9c2d9638c3c969
9,466
cpp
C++
src/hit/api/linearalgebra/encryptedrowvector.cpp
SalusaSecondus/homomorphic-implementors-toolkit
b7775b77cb0ff4ff42a1b47bf958bb0e3c75fb9b
[ "Apache-2.0" ]
38
2020-12-02T12:43:16.000Z
2022-03-15T19:27:39.000Z
src/hit/api/linearalgebra/encryptedrowvector.cpp
SalusaSecondus/homomorphic-implementors-toolkit
b7775b77cb0ff4ff42a1b47bf958bb0e3c75fb9b
[ "Apache-2.0" ]
15
2020-12-03T05:04:12.000Z
2021-08-20T21:26:27.000Z
src/hit/api/linearalgebra/encryptedrowvector.cpp
SalusaSecondus/homomorphic-implementors-toolkit
b7775b77cb0ff4ff42a1b47bf958bb0e3c75fb9b
[ "Apache-2.0" ]
6
2021-01-06T18:37:00.000Z
2021-09-20T06:43:13.000Z
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #include "encryptedrowvector.h" #include <glog/logging.h> #include <algorithm> #include <execution> #include "common.h" using namespace std; namespace hit { EncryptedRowVector::EncryptedRowVector(int width, const EncodingUnit &unit, vector<CKKSCiphertext> &cts) : width_(width), unit(unit), cts(cts) { validate(); } void EncryptedRowVector::read_from_proto(const shared_ptr<HEContext> &context, const protobuf::EncryptedRowVector &encrypted_row_vector) { width_ = encrypted_row_vector.width(); // if width is 0, this object is uninitialized. Don't call validate() (or create a unit): // both will fail. Just return an uninitailzed object. if (width_ == 0) { return; } unit = EncodingUnit(encrypted_row_vector.unit()); cts.reserve(encrypted_row_vector.cts().cts_size()); deserialize_vector(context, encrypted_row_vector.cts(), cts); validate(); } EncryptedRowVector::EncryptedRowVector(const shared_ptr<HEContext> &context, const protobuf::EncryptedRowVector &encrypted_row_vector) { read_from_proto(context, encrypted_row_vector); } EncryptedRowVector::EncryptedRowVector(const shared_ptr<HEContext> &context, istream &stream) { protobuf::EncryptedRowVector proto_vec; proto_vec.ParseFromIstream(&stream); read_from_proto(context, proto_vec); } protobuf::EncryptedRowVector *EncryptedRowVector::serialize() const { auto *encrypted_row_vector = new protobuf::EncryptedRowVector(); encrypted_row_vector->set_width(width_); encrypted_row_vector->set_allocated_unit(unit.serialize()); encrypted_row_vector->set_allocated_cts(serialize_vector(cts)); return encrypted_row_vector; } void EncryptedRowVector::save(ostream &stream) const { protobuf::EncryptedRowVector *proto_vec = serialize(); proto_vec->SerializeToOstream(&stream); delete proto_vec; } int EncryptedRowVector::width() const { return width_; } int EncryptedRowVector::num_units() const { return cts.size(); } int EncryptedRowVector::num_slots() const { return cts[0].num_slots(); } int EncryptedRowVector::he_level() const { // assumes that cts is non-empty and that we enforce all cts must have the same level return cts[0].he_level(); } bool EncryptedRowVector::needs_rescale() const { return cts[0].needs_rescale(); } bool EncryptedRowVector::needs_relin() const { return cts[0].needs_relin(); } Vector EncryptedRowVector::plaintext() const { vector<Matrix> plaintext_pieces(cts.size()); for (int i = 0; i < cts.size(); i++) { // The CKKSCiphertext plaintext is just a list of coefficients. // We know that it has additional meaning here: it's really a matrix // with the dimensions of the encoding unit. // To decode and recover the underlying plaintext matrix, we must first // add this additional context. Vector raw_plaintext = cts[i].plaintext(); if (raw_plaintext.size() != unit.encoding_height() * unit.encoding_width()) { LOG_AND_THROW_STREAM("Internal error: plaintext has " << raw_plaintext.size() << " coefficients, expected " << unit.encoding_height() * unit.encoding_width()); } Matrix formatted_plaintext = Matrix(unit.encoding_height(), unit.encoding_width(), raw_plaintext.data()); plaintext_pieces[i] = formatted_plaintext; } return decode_row_vector(plaintext_pieces, width_); } EncodingUnit EncryptedRowVector::encoding_unit() const { return unit; } double EncryptedRowVector::scale() const { // assumes that cts is non-empty and that we enforce all cts must have the same scale return cts[0].scale(); } void EncryptedRowVector::validate() const { // validate the unit unit.validate(); if (width_ <= 0) { LOG_AND_THROW_STREAM("Invalid EncryptedRowVector: " << "width must be non-negative, got " << width_); } if (cts.size() != ceil(width_ / static_cast<double>(unit.encoding_height()))) { LOG_AND_THROW_STREAM("Invalid EncryptedRowVector: " << "Expected " << ceil(width_ / static_cast<double>(unit.encoding_height())) << " ciphertexts, found " << cts.size() << ". "); } for (int i = 1; i < cts.size(); i++) { if (cts[i].scale() != cts[0].scale()) { LOG_AND_THROW_STREAM("Invalid EncryptedRowVector: " << "Each ciphertext must have the same scale."); } if (cts[i].he_level() != cts[0].he_level()) { LOG_AND_THROW_STREAM("Invalid EncryptedRowVector: " << "Each ciphertext must have the same level."); } } } size_t EncryptedRowVector::num_cts() const { return cts.size(); } CKKSCiphertext &EncryptedRowVector::operator[](size_t idx) { return cts[idx]; } const CKKSCiphertext &EncryptedRowVector::operator[](size_t idx) const { return cts[idx]; } bool EncryptedRowVector::same_size(const EncryptedRowVector &enc_vec) const { return width_ == enc_vec.width() && unit == enc_vec.encoding_unit(); } /********* CKKS Basics ********* * The basic form of a CKKS plaintext is an 'array' of real or complex values * (distinguished from a 'vector', which will refer to linear algebra vectors * below). All plaintext arrays must first be *encoded* into a CKKS Plaintext * type. This encoding is done implicitly in the high-level API. * Plaintexts can then be encrypted to obtain a Ciphertext. * ********* Vector Encoding ********* * It might seem obvious that we should encode vectors directly as arrays. * However, it turns out to be more convenient to first encode a linear algebra * vector \vec{x} as a *matrix* X. There are two different encodings: either as * rows or columns. We would encode a *column* vector as *rows* of a matrix, * and a *row* vector as *columns* of a matrix. The intuition for this is that * for an matrix A, we can compute A*x for a column vector x as A(*)X, * where (*) is the Hadamard (component-wise) product and X is the m x n * row-encoding of \vec{x}. (This accomplishes the multiplication in a * single step; the 'sum' portion of the dot product is another step.) * Similarly, for a row-vector x, we can * compute x*A easily if we use the column-encoding for X and compute X(*)A. * The vector encoding is always relative to a matrix A, and the dimension of * the the encoded matrix X is the same as the dimension of the transpose of A. * [ x y ] * |x| ... * The row encoding turns the vector |y| to matrix [ x y ], while the column * [ x ... x ] * encoding of | x y | produces the matrix [ y ... y ]. */ vector<Matrix> encode_row_vector(const Vector &vec, const EncodingUnit &unit) { int width = vec.size(); // We encode row vectors as *columns*, which is why the row vector's width is used to // calculated the number of vertical units. size_t num_units = ceil(vec.size() / static_cast<double>(unit.encoding_height())); vector<Matrix> cts(num_units); for (size_t i = 0; i < num_units; i++) { vector<double> unit_i; for (int k = 0; k < unit.encoding_height(); k++) { for (int l = 0; l < unit.encoding_width(); l++) { size_t col = unit.encoding_height() * i + k; if (col < width) { unit_i.emplace_back(vec[col]); } else { unit_i.emplace_back(0); } } } cts[i] = Matrix(unit.encoding_height(), unit.encoding_width(), unit_i); } return cts; } Vector decode_row_vector(const vector<Matrix> &mats, int trim_length) { if (mats.empty()) { LOG_AND_THROW_STREAM("Internal error: input to decode_row_vector cannot be empty"); } if (trim_length < 0) { trim_length = static_cast<int>(mats.size() * mats[0].size1()); } // row vectors are encoded as columns of a matrix. // return the first column of each matrix, concatenated together vector<double> v; v.reserve(trim_length); for (int i = 0; i < mats.size(); i++) { for (int j = 0; j < mats[0].size1() && i * mats[0].size1() + j < trim_length; j++) { v.emplace_back(mats[i](j, 0)); } } return Vector(v); } } // namespace hit
40.801724
117
0.58895
[ "object", "vector" ]
f746e9b81325061ba7344c2de54b6e24f82a8318
4,342
cpp
C++
zzxcf/zzxcf.cpp
ZhangZexiao/ZhangZeXiaoCodeFormatter
609cb3dc3db9bff19fa7d410fdcd35331150c3ed
[ "MIT" ]
null
null
null
zzxcf/zzxcf.cpp
ZhangZexiao/ZhangZeXiaoCodeFormatter
609cb3dc3db9bff19fa7d410fdcd35331150c3ed
[ "MIT" ]
2
2018-05-02T04:42:22.000Z
2018-05-31T01:59:08.000Z
zzxcf/zzxcf.cpp
ZhangZexiao/ZhangZeXiaoCodeFormatter
609cb3dc3db9bff19fa7d410fdcd35331150c3ed
[ "MIT" ]
null
null
null
#include <algorithm> #include <cctype> #include <functional> #include <list> #include <locale> #include <map> #include <memory> #include <sstream> #include <stack> #include <string> #include <vector> #include <assert.h> #include <conio.h> #include <io.h> #include <stdio.h> #include <sys/stat.h> #include <windows.h> #include <comdef.h> #include <atlbase.h> #include <crtdbg.h> #pragma comment(lib,"sqlite3.lib") #include "..\common\Macro.h" #include "zzxcf_command_line_option.h" #include "zzxcf_performance_monitor.h" #include "zzxcf_file_operation.h" #include "zzxcf_multithread_utility.h" #include "zzxcf_console_utility.h" #include "zzxcf_statistic_utility.h" #include "zzxcf_format_utility.h" #include "../sqlite/sqlite3.h" int main(int argc,char**argv) { int in_out_argv_position=1; command_line_namespace::command_line_option_parser::parse(argc,argv,in_out_argv_position); std::list<std::string>out_to_be_formatted_files; file_operation_namespace::search_files(argc,argv,in_out_argv_position,out_to_be_formatted_files); if(command_line_namespace::option_restore_previous_version.is_turned_on()) { format_utility_namespace::restore_previous_version(out_to_be_formatted_files); return 0; } if(command_line_namespace::option_cleanup_orig_files.is_turned_on()) { format_utility_namespace::delete_all_orig_files(argc,argv,in_out_argv_position); } ::atexit(console_utility_namespace::at_zzxcf_exit); std::string new_stdout_file=file_operation_namespace::generate_unique_file_name(argv[0],".stdout"); std::string new_stderr_file=file_operation_namespace::generate_unique_file_name(argv[0],".stderr"); console_utility_namespace::class_console_output_redirector redirect_stdout(1,new_stdout_file),redirect_stderr(2,new_stderr_file); if(command_line_namespace::option_redirect_stdout_to_file.is_turned_on()) { redirect_stdout.turn_on(); } if(!command_line_namespace::option_do_not_redirect_stderr_to_file.is_turned_on()) { redirect_stderr.turn_on(); } QueryPerformanceCounter(&statistic_utility_namespace::program_start_time); QueryPerformanceFrequency(&statistic_utility_namespace::program_time_frequency); if(command_line_namespace::option_print_help.is_turned_on()) { console_utility_namespace::print_zzxcf_usage(argc,argv); return 0; } if(!command_line_namespace::option_do_not_print_logo.is_turned_on()) { console_utility_namespace::print_zzxcf_logo(); } if(command_line_namespace::option_convert_to_bridge_pattern.is_turned_on()) { format_utility_namespace::convert_to_bridge_pattern(out_to_be_formatted_files); return 0; } if(command_line_namespace::option_save_functions_into_sqlite3_database.is_turned_on()&&command_line_namespace::option_do_not_touch_files.is_turned_on()) { format_utility_namespace::save_functions_into_sqlite3_database(out_to_be_formatted_files); return 0; } if(command_line_namespace::option_import_maps.is_turned_on()) { import_comment_map(format_utility_namespace::comment_map); import_directive_map(format_utility_namespace::directive_map); import_id_map(format_utility_namespace::identifier_map,format_utility_namespace::inverse_identifier_map); } if(command_line_namespace::option_do_not_use_multithreads.is_turned_on()) { format_utility_namespace::format_files_in_process(out_to_be_formatted_files); } else { InitializeCriticalSection(&namespace_multithread::critical_section_of_statistic); InitializeCriticalSection(&namespace_multithread::critical_section_of_map_operation); format_utility_namespace::format_files_in_threads(out_to_be_formatted_files); } QueryPerformanceCounter(&statistic_utility_namespace::program_stop_time); if(!command_line_namespace::option_do_not_print_statistical_data.is_turned_on()) { statistic_utility_namespace::print_statistical_data(); } if(command_line_namespace::option_notify_user_when_job_done.is_turned_on()) { statistic_utility_namespace::notify_user(); } if(command_line_namespace::option_export_maps.is_turned_on()) { export_comment_map(format_utility_namespace::comment_map); export_id_map(format_utility_namespace::identifier_map); export_directive_map(format_utility_namespace::directive_map,format_utility_namespace::directive_list); } return 0; }
38.767857
154
0.809535
[ "vector" ]
f7494fdefd9c7d5a868efb84b8a76ceb50eb0e08
38,982
cpp
C++
orchagent/p4orch/acl_util.cpp
pins/sonic-swss-public
4a443eaa33a3d354d99daa3c340cdcff882fc061
[ "Apache-2.0" ]
null
null
null
orchagent/p4orch/acl_util.cpp
pins/sonic-swss-public
4a443eaa33a3d354d99daa3c340cdcff882fc061
[ "Apache-2.0" ]
3
2021-11-19T21:46:50.000Z
2021-11-19T22:14:08.000Z
orchagent/p4orch/acl_util.cpp
pins/sonic-swss-public
4a443eaa33a3d354d99daa3c340cdcff882fc061
[ "Apache-2.0" ]
1
2021-11-19T19:42:07.000Z
2021-11-19T19:42:07.000Z
#include "p4orch/acl_util.h" #include "converter.h" #include "json.hpp" #include "logger.h" #include "sai_serialize.h" #include "table.h" #include "tokenize.h" namespace p4orch { std::string trim(const std::string& s) { size_t end = s.find_last_not_of(WHITESPACE); size_t start = s.find_first_not_of(WHITESPACE); return (end == std::string::npos) ? EMPTY_STRING : s.substr(start, end - start + 1); } bool parseAclTableAppDbActionField( const std::string& aggr_actions_str, std::vector<P4ActionParamName>* action_list, std::vector<P4PacketActionWithColor>* action_color_list) { try { const auto& j = nlohmann::json::parse(aggr_actions_str); if (!j.is_array()) { SWSS_LOG_ERROR( "Invalid ACL table definition action %s, expecting an array.\n", aggr_actions_str.c_str()); return false; } P4ActionParamName action_with_param; for (auto& action_item : j) { auto sai_action_it = action_item.find(kAction); if (sai_action_it == action_item.end()) { SWSS_LOG_ERROR( "Invalid ACL table definition action %s, missing 'action':\n", aggr_actions_str.c_str()); return false; } if (aclPacketActionLookup.find(sai_action_it.value()) == aclPacketActionLookup.end()) { action_with_param.sai_action = sai_action_it.value(); auto action_param_it = action_item.find(kActionParamPrefix); if (action_param_it != action_item.end() && !action_param_it.value().is_null()) { action_with_param.p4_param_name = action_param_it.value(); } action_list->push_back(action_with_param); } else { auto packet_color_it = action_item.find(kPacketColor); P4PacketActionWithColor packet_action_with_color; packet_action_with_color.packet_action = sai_action_it.value(); if (packet_color_it != action_item.end() && !packet_color_it.value().is_null()) { packet_action_with_color.packet_color = packet_color_it.value(); } action_color_list->push_back(packet_action_with_color); } } return true; } catch (std::exception& ex) { SWSS_LOG_ERROR( "Failed to deserialize ACL table definition action fields: %s (%s)", aggr_actions_str.c_str(), ex.what()); return false; } } ReturnCode validateAndSetSaiMatchFieldJson( const nlohmann::json& match_json, const std::string& p4_match, const std::string& aggr_match_str, std::map<std::string, SaiMatchField>* sai_match_field_lookup, std::map<std::string, std::string>* ip_type_bit_type_lookup) { SaiMatchField sai_match_field; auto format_str_it = match_json.find(kAclMatchFieldFormat); if (format_str_it == match_json.end() || format_str_it.value().is_null() || !format_str_it.value().is_string()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << kAclMatchFieldFormat << " value is required and should be a string"; } auto format_it = formatLookup.find(format_str_it.value()); if (format_it == formatLookup.end()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << kAclMatchFieldFormat << " value is invalid, should be one of {" << P4_FORMAT_HEX_STRING << ", " << P4_FORMAT_MAC << ", " << P4_FORMAT_IPV4 << ", " << P4_FORMAT_IPV6 << ", " << P4_FORMAT_STRING << "}"; } sai_match_field.format = format_it->second; if (sai_match_field.format != Format::STRING) { // bitwidth is required if the format is not "STRING" auto bitwidth_it = match_json.find(kAclMatchFieldBitwidth); if (bitwidth_it == match_json.end() || bitwidth_it.value().is_null() || !bitwidth_it.value().is_number()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << kAclMatchFieldBitwidth << " value is required and should be a number"; } sai_match_field.bitwidth = bitwidth_it.value(); } auto match_field_it = match_json.find(kAclMatchFieldSaiField); if (match_field_it == match_json.end() || match_field_it.value().is_null() || !match_field_it.value().is_string()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << kAclMatchFieldSaiField << " value is required and should be a string"; } std::vector<std::string> tokenized_field = swss::tokenize(match_field_it.value(), kFieldDelimiter); const auto& sai_match_field_str = tokenized_field[0]; auto table_attr_it = aclMatchTableAttrLookup.find(sai_match_field_str); auto rule_attr_it = aclMatchEntryAttrLookup.find(sai_match_field_str); if (table_attr_it == aclMatchTableAttrLookup.end() || rule_attr_it == aclMatchEntryAttrLookup.end()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << match_field_it.value() << " is not supported in P4Orch "; } const auto& expected_format_it = aclMatchTableAttrFormatLookup.find(table_attr_it->second); if (expected_format_it == aclMatchTableAttrFormatLookup.end() || sai_match_field.format != expected_format_it->second) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: format for field " << match_field_it.value() << " is expected to be " << expected_format_it->second << ", but got " << format_it->first; } sai_match_field.table_attr = table_attr_it->second; sai_match_field.entry_attr = rule_attr_it->second; (*sai_match_field_lookup)[p4_match] = sai_match_field; if (rule_attr_it->second == SAI_ACL_ENTRY_ATTR_FIELD_ACL_IP_TYPE && tokenized_field.size() == 2) { // Get IP_TYPE suffix and save the bit mapping. if (aclIpTypeBitSet.find(tokenized_field[1]) == aclIpTypeBitSet.end()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} has invalid IP_TYPE encode bit."; } (*ip_type_bit_type_lookup)[p4_match] = tokenized_field[1]; } SWSS_LOG_INFO("ACL table built match field %s with kind:sai_field", sai_match_field_str.c_str()); return ReturnCode(); } ReturnCode validateAndSetCompositeElementSaiFieldJson( const nlohmann::json& element_match_json, const std::string& p4_match, std::map<std::string, std::vector<SaiMatchField>>* composite_sai_match_fields_lookup, const std::string& format_str) { SaiMatchField sai_match_field; const auto& element_str = element_match_json.dump(); if (format_str != P4_FORMAT_IPV6) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field " << p4_match << " element: " << element_str << " is an invalid ACL table attribute: '" << kAclMatchFieldFormat << "' should be " << P4_FORMAT_IPV6; } sai_match_field.format = Format::IPV6; auto bitwidth_it = element_match_json.find(kAclMatchFieldBitwidth); if (bitwidth_it == element_match_json.end() || bitwidth_it.value().is_null() || !bitwidth_it.value().is_number()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field " << p4_match << "element: " << element_str << " is an invalid ACL table attribute: " << kAclMatchFieldBitwidth << " value is required and should be a number"; } sai_match_field.bitwidth = bitwidth_it.value(); auto match_field_it = element_match_json.find(kAclMatchFieldSaiField); if (match_field_it == element_match_json.end() || match_field_it.value().is_null() || !match_field_it.value().is_string()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field " << p4_match << " element: " << element_str << " is an invalid ACL table attribute: " << kAclMatchFieldSaiField << " value is required in composite elements and should be a string"; } const std::string& match_field_str = match_field_it.value(); auto table_attr_it = aclCompositeMatchTableAttrLookup.find(match_field_str); auto rule_attr_it = aclCompositeMatchEntryAttrLookup.find(match_field_str); if (table_attr_it == aclCompositeMatchTableAttrLookup.end() || rule_attr_it == aclCompositeMatchEntryAttrLookup.end()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field " << p4_match << " element: " << element_str << " is an invalid ACL table attribute: not supported in P4Orch " "as an element in composite match fields"; } const uint32_t expected_bitwidth = BYTE_BITWIDTH * IPV6_SINGLE_WORD_BYTES_LENGTH; if (sai_match_field.bitwidth != expected_bitwidth) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field " << p4_match << " element: " << element_str << " is an invalid ACL table attribute: element.bitwidth is " "expected to be " << expected_bitwidth << " but got " << sai_match_field.bitwidth; } sai_match_field.table_attr = table_attr_it->second; sai_match_field.entry_attr = rule_attr_it->second; (*composite_sai_match_fields_lookup)[p4_match].push_back(sai_match_field); SWSS_LOG_INFO( "ACL table built composite match field element %s with kind:sai_field", match_field_str.c_str()); return ReturnCode(); } ReturnCode validateAndSetUdfFieldJson( const nlohmann::json& match_json, const std::string& p4_match, const std::string& aggr_match_str, const std::string& acl_table_name, std::map<std::string, std::vector<P4UdfField>>* udf_fields_lookup, std::map<std::string, uint16_t>* udf_group_attr_index_lookup) { P4UdfField udf_field; // Parse UDF bitwitdth auto bitwidth_json_it = match_json.find(kAclMatchFieldBitwidth); if (bitwidth_json_it == match_json.end() || bitwidth_json_it.value().is_null() || !bitwidth_json_it.value().is_number()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match composite UDF field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << kAclMatchFieldBitwidth << " value is required and should be a number"; } uint32_t bitwidth = bitwidth_json_it.value(); if (bitwidth % BYTE_BITWIDTH != 0) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match composite UDF field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << kAclMatchFieldBitwidth << " value should be a multiple of 8."; } udf_field.length = (uint16_t)(bitwidth / BYTE_BITWIDTH); // Parse UDF offset auto udf_offset_it = match_json.find(kAclUdfOffset); if (udf_offset_it == match_json.end() || udf_offset_it.value().is_null() || !udf_offset_it.value().is_number()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match composite UDF field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << kAclUdfOffset << " value is required in composite elements and should be a number"; } udf_field.offset = udf_offset_it.value(); // Parse UDF base auto udf_base_json_it = match_json.find(kAclUdfBase); if (udf_base_json_it == match_json.end() || udf_base_json_it.value().is_null() || !udf_base_json_it.value().is_string()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match composite UDF field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << kAclUdfBase << " value is required in composite elements and should be a string"; } const auto& udf_base_it = udfBaseLookup.find(udf_base_json_it.value()); if (udf_base_it == udfBaseLookup.end()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match composite UDF field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << udf_base_json_it.value() << " is not supported in P4Orch " "as a valid UDF base. Supported UDF bases are: " << P4_UDF_BASE_L2 << ", " << P4_UDF_BASE_L3 << " and " << P4_UDF_BASE_L4; } udf_field.base = udf_base_it->second; // Set UDF group id udf_field.group_id = acl_table_name + "-" + p4_match + "-" + std::to_string((*udf_fields_lookup)[p4_match].size()); udf_field.udf_id = udf_field.group_id + "-base" + std::to_string(udf_field.base) + "-offset" + std::to_string(udf_field.offset); (*udf_fields_lookup)[p4_match].push_back(udf_field); // Assign UDF group to a new ACL entry attr index if it is a new group uint16_t index = 0; auto udf_group_attr_index_it = udf_group_attr_index_lookup->find(udf_field.group_id); if (udf_group_attr_index_it != udf_group_attr_index_lookup->end()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "Error when building UDF field for ACL talbe: duplicated UDF " "groups found for the same index."; } index = (uint16_t)udf_group_attr_index_lookup->size(); (*udf_group_attr_index_lookup)[udf_field.group_id] = index; SWSS_LOG_INFO( "ACL table built composite match field elelment %s with kind:udf", udf_field.group_id.c_str()); return ReturnCode(); } ReturnCode validateAndSetCompositeMatchFieldJson( const nlohmann::json& aggr_match_json, const std::string& p4_match, const std::string& aggr_match_str, const std::string& acl_table_name, std::map<std::string, std::vector<SaiMatchField>>* composite_sai_match_fields_lookup, std::map<std::string, std::vector<P4UdfField>>* udf_fields_lookup, std::map<std::string, uint16_t>* udf_group_attr_index_lookups) { auto format_str_it = aggr_match_json.find(kAclMatchFieldFormat); if (format_str_it == aggr_match_json.end() || format_str_it.value().is_null() || !format_str_it.value().is_string()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << kAclMatchFieldFormat << " value is required and should be a string"; } auto format_it = formatLookup.find(format_str_it.value()); if (format_it == formatLookup.end() || format_it->second == Format::STRING) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << kAclMatchFieldFormat << " value is invalid, should be one of {" << P4_FORMAT_HEX_STRING << ", " << P4_FORMAT_IPV6 << "}"; } auto bitwidth_it = aggr_match_json.find(kAclMatchFieldBitwidth); if (bitwidth_it == aggr_match_json.end() || bitwidth_it.value().is_null() || !bitwidth_it.value().is_number()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << kAclMatchFieldBitwidth << " value is required and should be a number"; } uint32_t composite_bitwidth = bitwidth_it.value(); auto elements_it = aggr_match_json.find(kAclMatchFieldElements); // b/175596733: temp disable verification on composite elements field until // p4rt implementation is added. if (elements_it == aggr_match_json.end()) { (*udf_fields_lookup)[p4_match]; return ReturnCode(); } if (elements_it.value().is_null() || !elements_it.value().is_array()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: 'elements' value is " "required and should be an array"; } for (const auto& element : elements_it.value()) { if (element.is_null() || !element.is_object()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: 'elements' member " "should be an json"; } const auto& element_kind_it = element.find(kAclMatchFieldKind); if (element_kind_it == element.end() || element_kind_it.value().is_null() || !element_kind_it.value().is_string()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: composite element " "'kind' value is required and should be a string"; } ReturnCode rc; if (element_kind_it.value() == kAclMatchFieldSaiField) { rc = validateAndSetCompositeElementSaiFieldJson( element, p4_match, composite_sai_match_fields_lookup, format_str_it.value()); } else if (element_kind_it.value() == kAclMatchFieldKindUdf) { if (format_str_it.value() != P4_FORMAT_HEX_STRING) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << kAclMatchFieldFormat << " value should be HEX_STRING for UDF field"; } rc = validateAndSetUdfFieldJson(element, p4_match, aggr_match_str, acl_table_name, udf_fields_lookup, udf_group_attr_index_lookups); } else { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: composite element " "'kind' should be either " << kAclMatchFieldKindUdf << " or " << kAclMatchFieldSaiField; } if (!rc.ok()) return rc; } // elements kind should be all sai_field or all udf. auto sai_field_it = composite_sai_match_fields_lookup->find(p4_match); auto udf_field_it = udf_fields_lookup->find(p4_match); if (sai_field_it != composite_sai_match_fields_lookup->end() && udf_field_it != udf_fields_lookup->end()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: composite element " "'kind' should be consistent within all elements."; } // The sum of bitwidth of elements should equals overall bitwidth defined // in composite fields uint32_t total_bitwidth = 0; if (sai_field_it != composite_sai_match_fields_lookup->end()) { // IPV6_64bit(IPV6_WORD3 and IPV6_WORD2 in elements, kind:sai_field, // format:IPV6) if (sai_field_it->second.size() != 2) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: composite match field " "with sai_field in element kind should have 2 elements."; } if (!((sai_field_it->second[0].table_attr == SAI_ACL_TABLE_ATTR_FIELD_DST_IPV6_WORD3 && sai_field_it->second[1].table_attr == SAI_ACL_TABLE_ATTR_FIELD_DST_IPV6_WORD2) || (sai_field_it->second[0].table_attr == SAI_ACL_TABLE_ATTR_FIELD_SRC_IPV6_WORD3 && sai_field_it->second[1].table_attr == SAI_ACL_TABLE_ATTR_FIELD_SRC_IPV6_WORD2))) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: For composite match " "field " "with element.kind == sai_field, the SAI match field " "in elements list should be either pair {" << P4_MATCH_DST_IPV6_WORD3 << ", " << P4_MATCH_DST_IPV6_WORD2 << "} or pair {" << P4_MATCH_SRC_IPV6_WORD3 << ", " << P4_MATCH_SRC_IPV6_WORD2 << "} with the correct sequence"; } total_bitwidth = sai_field_it->second[0].bitwidth + sai_field_it->second[1].bitwidth; } if (udf_field_it != udf_fields_lookup->end()) { for (const auto& udf_field : udf_field_it->second) { total_bitwidth += (uint32_t)udf_field.length * BYTE_BITWIDTH; } } if (total_bitwidth != composite_bitwidth) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: composite bitwidth " "does not equal with the sum of elements bitwidth."; } return ReturnCode(); } ReturnCode buildAclTableDefinitionMatchFieldValues( const std::map<std::string, std::string>& match_field_lookup, P4AclTableDefinition* acl_table) { for (const auto& raw_match_field : match_field_lookup) { const auto& p4_match = fvField(raw_match_field); const auto& aggr_match_str = fvValue(raw_match_field); try { const auto& aggr_match_json = nlohmann::json::parse(aggr_match_str); if (!aggr_match_json.is_object()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: expecting an json"; } const auto& kind_it = aggr_match_json.find(kAclMatchFieldKind); if (kind_it == aggr_match_json.end() || kind_it.value().is_null() || !kind_it.value().is_string()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: 'kind' value is " "required and should be a string"; } ReturnCode rc; if (kind_it.value() == kAclMatchFieldSaiField) { rc = validateAndSetSaiMatchFieldJson( aggr_match_json, p4_match, aggr_match_str, &acl_table->sai_match_field_lookup, &acl_table->ip_type_bit_type_lookup); } else if (kind_it.value() == kAclMatchFieldKindComposite) { rc = validateAndSetCompositeMatchFieldJson( aggr_match_json, p4_match, aggr_match_str, acl_table->acl_table_name, &acl_table->composite_sai_match_fields_lookup, &acl_table->udf_fields_lookup, &acl_table->udf_group_attr_index_lookup); } else if (kind_it.value() == kAclMatchFieldKindUdf) { auto format_str_it = aggr_match_json.find(kAclMatchFieldFormat); if (format_str_it == aggr_match_json.end() || format_str_it.value().is_null() || !format_str_it.value().is_string()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << kAclMatchFieldFormat << " value is required and should be a string"; } if (format_str_it.value() != P4_FORMAT_HEX_STRING) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: " << kAclMatchFieldFormat << " value should be HEX_STRING for UDF field"; } rc = validateAndSetUdfFieldJson( aggr_match_json, p4_match, aggr_match_str, acl_table->acl_table_name, &acl_table->udf_fields_lookup, &acl_table->udf_group_attr_index_lookup); } else { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: 'kind' is expecting " "one of {" << kAclMatchFieldKindComposite << ", " << kAclMatchFieldSaiField << ", " << kAclMatchFieldKindUdf << "}."; } if (!rc.ok()) return rc; } catch (std::exception& ex) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table match field {" << p4_match << ": " << aggr_match_str << "} is an invalid ACL table attribute: ex" << ex.what(); } } return ReturnCode(); } ReturnCode buildAclTableDefinitionActionFieldValues( const std::map<std::string, std::vector<P4ActionParamName>>& action_field_lookup, std::map<std::string, std::vector<SaiActionWithParam>>* aggr_sai_actions_lookup) { SaiActionWithParam action_with_param; for (const auto& aggr_action_field : action_field_lookup) { auto& aggr_sai_actions = (*aggr_sai_actions_lookup)[fvField(aggr_action_field)]; for (const auto& single_action : fvValue(aggr_action_field)) { auto rule_action_it = aclActionLookup.find(single_action.sai_action); if (rule_action_it == aclActionLookup.end()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table action is invalid: " << single_action.sai_action; } action_with_param.action = rule_action_it->second; action_with_param.param_name = single_action.p4_param_name; aggr_sai_actions.push_back(action_with_param); } } return ReturnCode(); } ReturnCode buildAclTableDefinitionActionColorFieldValues( const std::map<std::string, std::vector<P4PacketActionWithColor>>& action_color_lookup, std::map<std::string, std::vector<SaiActionWithParam>>* aggr_sai_actions_lookup, std::map<std::string, std::map<sai_policer_attr_t, sai_packet_action_t>>* aggr_sai_action_color_lookup) { for (const auto& aggr_action_color : action_color_lookup) { auto& aggr_sai_actions = (*aggr_sai_actions_lookup)[fvField(aggr_action_color)]; auto& aggr_sai_action_color = (*aggr_sai_action_color_lookup)[fvField(aggr_action_color)]; for (const auto& action_color : fvValue(aggr_action_color)) { auto packet_action_it = aclPacketActionLookup.find(action_color.packet_action); if (packet_action_it == aclPacketActionLookup.end()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table packet action is invalid: " << action_color.packet_action; } if (action_color.packet_color.empty()) { // Handle packet action without packet color, set ACL entry attribute SaiActionWithParam action_with_param; action_with_param.action = SAI_ACL_ENTRY_ATTR_ACTION_PACKET_ACTION; action_with_param.param_name = EMPTY_STRING; action_with_param.param_value = action_color.packet_action; aggr_sai_actions.push_back(action_with_param); continue; } // Handle packet action with packet color, set ACL policer attribute auto packet_color_it = aclPacketColorPolicerAttrLookup.find(action_color.packet_color); if (packet_color_it == aclPacketColorPolicerAttrLookup.end()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL table packet color is invalid: " << action_color.packet_color; } aggr_sai_action_color[packet_color_it->second] = packet_action_it->second; } } return ReturnCode(); } bool isSetUserTrapActionInAclTableDefinition( const std::map<std::string, std::vector<SaiActionWithParam>>& aggr_sai_actions_lookup) { for (const auto& aggr_action : aggr_sai_actions_lookup) { for (const auto& sai_action : fvValue(aggr_action)) { if (sai_action.action == SAI_ACL_ENTRY_ATTR_ACTION_SET_USER_TRAP_ID) return true; } } return false; } bool setMatchFieldIpType(const std::string& attr_value, sai_attribute_value_t* value, const std::string& ip_type_bit_type) { SWSS_LOG_ENTER(); if (ip_type_bit_type == EMPTY_STRING) { SWSS_LOG_ERROR("Invalid IP type %s, bit type is not defined.", attr_value.c_str()); return false; } // go/p4-ip-type const auto& ip_type_bit_data_mask = swss::tokenize(attr_value, kDataMaskDelimiter); if (ip_type_bit_data_mask.size() == 2 && swss::to_uint<uint16_t>(trim(ip_type_bit_data_mask[1])) == 0) { SWSS_LOG_ERROR( "Invalid IP_TYPE mask %s for bit type %s: ip type bit mask " "should not be zero.", attr_value.c_str(), ip_type_bit_type.c_str()); return false; } int ip_type_bit_data = std::stoi(ip_type_bit_data_mask[0], nullptr, 0); value->aclfield.mask.u32 = 0xFFFFFFFF; if (ip_type_bit_type == P4_IP_TYPE_BIT_IP) { if (ip_type_bit_data) { value->aclfield.data.u32 = SAI_ACL_IP_TYPE_IP; } else { value->aclfield.data.u32 = SAI_ACL_IP_TYPE_NON_IP; } } else if (ip_type_bit_type == P4_IP_TYPE_BIT_IPV4ANY) { if (ip_type_bit_data) { value->aclfield.data.u32 = SAI_ACL_IP_TYPE_IPV4ANY; } else { value->aclfield.data.u32 = SAI_ACL_IP_TYPE_NON_IPV4; } } else if (ip_type_bit_type == P4_IP_TYPE_BIT_IPV6ANY) { if (ip_type_bit_data) { value->aclfield.data.u32 = SAI_ACL_IP_TYPE_IPV6ANY; } else { value->aclfield.data.u32 = SAI_ACL_IP_TYPE_NON_IPV6; } } else if (ip_type_bit_type == P4_IP_TYPE_BIT_ARP && ip_type_bit_data) { value->aclfield.data.u32 = SAI_ACL_IP_TYPE_ARP; } else if (ip_type_bit_type == P4_IP_TYPE_BIT_ARP_REQUEST && ip_type_bit_data) { value->aclfield.data.u32 = SAI_ACL_IP_TYPE_ARP_REQUEST; } else if (ip_type_bit_type == P4_IP_TYPE_BIT_ARP_REPLY && ip_type_bit_data) { value->aclfield.data.u32 = SAI_ACL_IP_TYPE_ARP_REPLY; } else { SWSS_LOG_ERROR("Invalid IP_TYPE bit data %s for ip type %s", attr_value.c_str(), ip_type_bit_type.c_str()); return false; } return true; } ReturnCode setCompositeSaiMatchValue(const acl_entry_attr_union_t attr_name, const std::string& attr_value, sai_attribute_value_t* value) { try { const auto& tokenized_ip = swss::tokenize(attr_value, kDataMaskDelimiter); swss::IpAddress ip_data; swss::IpAddress ip_mask; if (tokenized_ip.size() == 2) { // data & mask ip_data = swss::IpAddress(trim(tokenized_ip[0])); if (ip_data.isV4()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "IP data type should be v6 type: " << attr_value; } ip_mask = swss::IpAddress(trim(tokenized_ip[1])); if (ip_mask.isV4()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "IP mask type should be v6 type: " << attr_value; } } else { // LPM annotated value swss::IpPrefix ip_prefix(trim(attr_value)); if (ip_prefix.isV4()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "IP type should be v6 type: " << attr_value; } ip_data = ip_prefix.getIp(); ip_mask = ip_prefix.getMask(); } switch (attr_name) { case SAI_ACL_TABLE_ATTR_FIELD_DST_IPV6_WORD3: case SAI_ACL_TABLE_ATTR_FIELD_SRC_IPV6_WORD3: { // IPv6 Address 127:96 32 bits memcpy(&value->aclfield.data.ip6[0], &ip_data.getV6Addr()[0], IPV6_SINGLE_WORD_BYTES_LENGTH); memcpy(&value->aclfield.mask.ip6[0], &ip_mask.getV6Addr()[0], IPV6_SINGLE_WORD_BYTES_LENGTH); break; } case SAI_ACL_TABLE_ATTR_FIELD_DST_IPV6_WORD2: case SAI_ACL_TABLE_ATTR_FIELD_SRC_IPV6_WORD2: { // IPv6 Address 95:64 32 bits memcpy(&value->aclfield.data.ip6[IPV6_SINGLE_WORD_BYTES_LENGTH], &ip_data.getV6Addr()[IPV6_SINGLE_WORD_BYTES_LENGTH], IPV6_SINGLE_WORD_BYTES_LENGTH); memcpy(&value->aclfield.mask.ip6[IPV6_SINGLE_WORD_BYTES_LENGTH], &ip_mask.getV6Addr()[IPV6_SINGLE_WORD_BYTES_LENGTH], IPV6_SINGLE_WORD_BYTES_LENGTH); break; } default: { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "ACL match field " << attr_name << " is not supported in composite match field sai_field type."; } } } catch (std::exception& e) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "Failed to parse match attribute " << attr_name << " (value: " << attr_value << "). Error:" << e.what(); } value->aclfield.enable = true; return ReturnCode(); } ReturnCode setUdfMatchValue(const P4UdfField& udf_field, const std::string& attr_value, sai_attribute_value_t* value, P4UdfDataMask* udf_data_mask, uint16_t bytes_offset) { if (!udf_data_mask->data.empty() || !udf_data_mask->mask.empty()) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "Failed to set UDF match field " << udf_field.udf_id << " with value " << attr_value << " in ACL rule: the UDF: duplicated UDF value found for the same " "UDF field."; } try { // Extract UDF field values by length(in bytes) and offset(in bytes) const std::vector<std::string>& value_and_mask = swss::tokenize(attr_value, kDataMaskDelimiter); uint32_t data_str_offset = bytes_offset * 2, mask_str_offset = bytes_offset * 2; const auto& data = trim(value_and_mask[0]); if (data.size() > 2 && data[0] == '0' && (data[1] == 'x' || data[1] == 'X')) { data_str_offset += 2; } std::string mask = EMPTY_STRING; if (value_and_mask.size() > 1) { mask = trim(value_and_mask[1]); if (mask.size() > 2 && mask[0] == '0' && (mask[1] == 'x' || mask[1] == 'X')) { mask_str_offset += 2; } } for (uint16_t i = 0; i < udf_field.length; i++) { // Add to udf_data uint8_t list udf_data_mask->data.push_back( std::stoul(data.substr(data_str_offset, 2), nullptr, 16) & 0xFF); data_str_offset += 2; if (value_and_mask.size() > 1) { // Add to udf_mask uint8_t list udf_data_mask->mask.push_back( (std::stoul(mask.substr(mask_str_offset, 2), nullptr, 16)) & 0xFF); mask_str_offset += 2; } else { udf_data_mask->mask.push_back(0xFF); } } value->aclfield.data.u8list.count = udf_field.length; value->aclfield.data.u8list.list = udf_data_mask->data.data(); value->aclfield.mask.u8list.count = udf_field.length; value->aclfield.mask.u8list.list = udf_data_mask->mask.data(); } catch (std::exception& ex) { return ReturnCode(StatusCode::SWSS_RC_INVALID_PARAM) << "Failed to set UDF match field " << udf_field.udf_id << " with value " << attr_value << " in ACL rule: " << ex.what(); } value->aclfield.enable = true; return ReturnCode(); } bool isDiffActionFieldValue(const acl_entry_attr_union_t attr_name, const sai_attribute_value_t& value, const sai_attribute_value_t& old_value, const P4AclRule& acl_rule, const P4AclRule& old_acl_rule) { switch (attr_name) { case SAI_ACL_ENTRY_ATTR_ACTION_PACKET_ACTION: case SAI_ACL_ENTRY_ATTR_ACTION_SET_PACKET_COLOR: { return value.aclaction.parameter.s32 != old_value.aclaction.parameter.s32; } case SAI_ACL_ENTRY_ATTR_ACTION_REDIRECT: { return value.aclaction.parameter.oid != old_value.aclaction.parameter.oid; } case SAI_ACL_ENTRY_ATTR_ACTION_ENDPOINT_IP: case SAI_ACL_ENTRY_ATTR_ACTION_SET_SRC_IP: case SAI_ACL_ENTRY_ATTR_ACTION_SET_DST_IP: { return value.aclaction.parameter.ip4 != old_value.aclaction.parameter.ip4; } case SAI_ACL_ENTRY_ATTR_ACTION_MIRROR_INGRESS: case SAI_ACL_ENTRY_ATTR_ACTION_MIRROR_EGRESS: { return acl_rule.action_mirror_sessions.at(attr_name).oid != old_acl_rule.action_mirror_sessions.at(attr_name).oid; } case SAI_ACL_ENTRY_ATTR_ACTION_SET_SRC_MAC: case SAI_ACL_ENTRY_ATTR_ACTION_SET_DST_MAC: { return memcmp(value.aclaction.parameter.mac, old_value.aclaction.parameter.mac, sizeof(sai_mac_t)); } case SAI_ACL_ENTRY_ATTR_ACTION_SET_SRC_IPV6: case SAI_ACL_ENTRY_ATTR_ACTION_SET_DST_IPV6: { return memcmp(value.aclaction.parameter.ip6, old_value.aclaction.parameter.ip6, sizeof(sai_ip6_t)); } case SAI_ACL_ENTRY_ATTR_ACTION_SET_TC: case SAI_ACL_ENTRY_ATTR_ACTION_SET_DSCP: case SAI_ACL_ENTRY_ATTR_ACTION_SET_ECN: case SAI_ACL_ENTRY_ATTR_ACTION_SET_INNER_VLAN_PRI: case SAI_ACL_ENTRY_ATTR_ACTION_SET_OUTER_VLAN_PRI: { return value.aclaction.parameter.u8 != old_value.aclaction.parameter.u8; } case SAI_ACL_ENTRY_ATTR_ACTION_SET_INNER_VLAN_ID: { return value.aclaction.parameter.u32 != old_value.aclaction.parameter.u32; } case SAI_ACL_ENTRY_ATTR_ACTION_SET_OUTER_VLAN_ID: case SAI_ACL_ENTRY_ATTR_ACTION_SET_L4_SRC_PORT: case SAI_ACL_ENTRY_ATTR_ACTION_SET_L4_DST_PORT: { return value.aclaction.parameter.u16 != old_value.aclaction.parameter.u16; } case SAI_ACL_ENTRY_ATTR_ACTION_SET_VRF: case SAI_ACL_ENTRY_ATTR_ACTION_SET_USER_TRAP_ID: { return value.aclaction.parameter.oid != old_value.aclaction.parameter.oid; } case SAI_ACL_ENTRY_ATTR_ACTION_FLOOD: case SAI_ACL_ENTRY_ATTR_ACTION_DECREMENT_TTL: case SAI_ACL_ENTRY_ATTR_ACTION_SET_DO_NOT_LEARN: { // parameter is not needed return false; } default: { return false; } } } } // namespace p4orch
45.64637
80
0.654328
[ "vector" ]
f7528429212d9ca88dc27ea8e1e0848d125fbab0
2,476
cpp
C++
Glitter/Sources/main.cpp
reedlaw/breakout
702e912248576861116f9853a45ff54d9562e924
[ "MIT", "Unlicense" ]
2
2021-03-11T13:47:08.000Z
2021-04-12T23:57:42.000Z
Glitter/Sources/main.cpp
reedlaw/breakout
702e912248576861116f9853a45ff54d9562e924
[ "MIT", "Unlicense" ]
null
null
null
Glitter/Sources/main.cpp
reedlaw/breakout
702e912248576861116f9853a45ff54d9562e924
[ "MIT", "Unlicense" ]
null
null
null
// Local Headers #include "glitter.hpp" #include "shader.hpp" #include "game.hpp" // System Headers #include <glad/glad.h> #include <GLFW/glfw3.h> // Standard Headers #include <iostream> #include <cstdio> #include <cstdlib> Game Breakout(mWidth, mHeight); int main(int argc, char * argv[]) { // Load GLFW and Create a Window glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); auto mWindow = glfwCreateWindow(mWidth, mHeight, "Breakout", nullptr, nullptr); // Check for Valid Context if (mWindow == nullptr) { fprintf(stderr, "Failed to Create OpenGL Context"); return EXIT_FAILURE; } // Create Context and Load OpenGL Functions glfwMakeContextCurrent(mWindow); gladLoadGL(); fprintf(stderr, "OpenGL %s\n", glGetString(GL_VERSION)); // OpenGL configuration glViewport(0, 0, mWidth, mHeight); glEnable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Initialize game Breakout.Init(); // DeltaTime variables GLfloat deltaTime = 0.0f; GLfloat lastFrame = 0.0f; // Start Game within Menu State Breakout.State = GAME_ACTIVE; GLint movement = 0; // -1 for left, 0 for none, 1 for right GLboolean action = false; // Rendering Loop while (glfwWindowShouldClose(mWindow) == false) { if (glfwGetKey(mWindow, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(mWindow, true); if (glfwGetKey(mWindow, GLFW_KEY_LEFT) == GLFW_PRESS) movement = -1; if (glfwGetKey(mWindow, GLFW_KEY_RIGHT) == GLFW_PRESS) movement = 1; if ((glfwGetKey(mWindow, GLFW_KEY_LEFT) != GLFW_PRESS) && (glfwGetKey(mWindow, GLFW_KEY_RIGHT) != GLFW_PRESS)) movement = 0; if (glfwGetKey(mWindow, GLFW_KEY_SPACE) == GLFW_PRESS) action = true; glfwPollEvents(); // Calculate delta time GLfloat currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Manage user input Breakout.ProcessInput(deltaTime, movement, action); // Update Game state Breakout.Update(deltaTime); // Background Fill Color glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); Breakout.Render(); glfwSwapBuffers(mWindow); } glfwTerminate(); return EXIT_SUCCESS; }
25.525773
114
0.696688
[ "render" ]
f75547577b2a9d6164cdb72e15c0a55fde9418df
2,509
cpp
C++
segmentation/Caffe_Segmentation/examples/seg/createFinalRes.cpp
USCDataScience/cmu-fg-bg-similarity
d8fc9a53937551f7a052bc2c6f442bcc29ea2615
[ "Apache-2.0" ]
8
2020-04-13T21:40:26.000Z
2022-01-22T11:32:31.000Z
segmentation/Caffe_Segmentation/examples/seg/createFinalRes.cpp
USCDataScience/cmu-fg-bg-similarity
d8fc9a53937551f7a052bc2c6f442bcc29ea2615
[ "Apache-2.0" ]
null
null
null
segmentation/Caffe_Segmentation/examples/seg/createFinalRes.cpp
USCDataScience/cmu-fg-bg-similarity
d8fc9a53937551f7a052bc2c6f442bcc29ea2615
[ "Apache-2.0" ]
null
null
null
/* * createFinalRes.cpp * * Created on: Dec 1, 2014 * Author: rohitgirdhar */ #include <glog/logging.h> #include <leveldb/db.h> #include <leveldb/write_batch.h> #include <algorithm> #include <string> #include <iostream> #include <fstream> #include <vector> #include <set> #include <algorithm> #include <libgen.h> #include <boost/filesystem.hpp> #include <opencv2/opencv.hpp> #include "caffe/proto/caffe.pb.h" #include "caffe/util/io.hpp" using namespace caffe; using std::string; using namespace cv; using namespace std; #define SZ_X 256 #define SZ_Y 256 #define OFFSET ((256-227)/2) int main(int argc, char** argv) { ::google::InitGoogleLogging(argv[0]); if (argc < 4) { LOG(ERROR)<< "Usage: " << argv[0] << " LOC_RES_FILE SEG_IMG_DIR IMG_DIR OUT_DIR"; return -1; } char *LOC_RES_FILE = argv[1]; char *SEG_IMG_DIR = argv[2]; char *IMG_DIR = argv[3]; char *OUT_DIR = argv[4]; boost::filesystem::create_directory(OUT_DIR); string fname; float xmin, xmax, ymin, ymax; ifstream infile(LOC_RES_FILE); if (!infile.is_open()) { LOG(ERROR)<< "Unable to open file: " << LOC_RES_FILE; return -1; } Mat I, S; Mat I2; I = Mat(SZ_X, SZ_Y, CV_8UC1); while (infile >> fname >> xmin >> ymin >> xmax >> ymax) { I.setTo(0); xmin = std::min(std::max(xmin + OFFSET, (float) 0), (float) SZ_X-1); ymin = std::min(std::max(ymin + OFFSET, (float) 0), (float) SZ_Y-1); xmax = std::min(std::max(xmax + OFFSET, (float) 0), (float) SZ_X-1); ymax = std::min(std::max(ymax + OFFSET, (float) 0), (float) SZ_Y-1); int x1 = xmin; int y1 = ymin; int x2 = xmax; int y2 = ymax; //LOG(ERROR)<<fname<<" "<<x1<<" "<<y1<<" "<<x2<<" "<<y2; S = imread(string(SEG_IMG_DIR) + "/" + fname, CV_LOAD_IMAGE_GRAYSCALE); if (!S.data) { LOG(ERROR)<< "Unable to read image " << string(SEG_IMG_DIR) + "/" + fname; continue; } int height = MAX(1, y2 - y1 + 1); int width = MAX(1, x2 - x1 + 1); resize(S, S, Size(width, height)); Mat extractedImage = I(Rect(x1, y1, width, height)); S.copyTo(extractedImage); string fpath = string(OUT_DIR) + "/" + fname; boost::filesystem::create_directory(dirname(strdup(fpath.c_str()))); imwrite(fpath, I); I2 = imread(string(IMG_DIR) + "/" + fname); I2 = I2 * 0.5; resize(I2, I2, Size(SZ_X, SZ_Y)); Mat channels[3]; split(I2, channels); addWeighted(channels[2], 0.5, I, 1.0, 0.0, channels[2]); merge(channels, 3, I2); fpath = string(OUT_DIR) + "/" + fname + ".segmask.jpg"; imwrite(fpath, I2); } return 0; }
25.343434
83
0.63053
[ "vector" ]
f75de404e24ab3a01009507ccb9928c3d0d47435
4,020
hpp
C++
lib/mtl4/boost/numeric/mtl/operation/qr.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
2
2018-07-04T16:44:04.000Z
2021-01-03T07:26:27.000Z
lib/mtl4/boost/numeric/mtl/operation/qr.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
lib/mtl4/boost/numeric/mtl/operation/qr.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
// Software License for MTL // // Copyright (c) 2007 The Trustees of Indiana University. // 2008 Dresden University of Technology and the Trustees of Indiana University. // 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com. // All rights reserved. // Authors: Peter Gottschling and Andrew Lumsdaine // With contributions from Cornelius Steinhardt // // This file is part of the Matrix Template Library // // See also license.mtl.txt in the distribution. #ifndef MTL_MATRIX_QR_INCLUDE #define MTL_MATRIX_QR_INCLUDE #include <cmath> #include <boost/numeric/linear_algebra/identity.hpp> #include <boost/numeric/linear_algebra/inverse.hpp> #include <boost/numeric/mtl/mtl_fwd.hpp> #include <boost/numeric/mtl/vector/parameter.hpp> #include <boost/numeric/mtl/matrix/parameter.hpp> #include <boost/numeric/mtl/utility/exception.hpp> #include <boost/numeric/mtl/utility/irange.hpp> #include <boost/numeric/mtl/concept/collection.hpp> #include <boost/numeric/mtl/concept/magnitude.hpp> #include <boost/numeric/mtl/operation/householder.hpp> #include <boost/numeric/mtl/operation/rank_one_update.hpp> #include <boost/numeric/mtl/operation/trans.hpp> #include <boost/numeric/mtl/interface/vpt.hpp> namespace mtl { namespace matrix { /// QR-Factorization of matrix A(m x n) /** Return pair R upper triangel matrix and Q= orthogonal matrix. R and Q are always dense2D **/ template <typename Matrix, typename MatrixQ, typename MatrixR> void qr(const Matrix& A, MatrixQ& Q, MatrixR& R) { vampir_trace<4013> tracer; typedef typename Collection<Matrix>::value_type value_type; typedef typename Collection<Matrix>::size_type size_type; typedef typename Magnitude<value_type>::type magnitude_type; typedef mtl::vector::dense_vector<value_type, vector::parameters<> > vector_type; size_type ncols = num_cols(A), nrows = num_rows(A), mini= ncols == nrows ? ncols - 1 : (nrows >= ncols ? ncols : nrows); magnitude_type factor= magnitude_type(2); Q= 1; for (size_type i = 0; i < mini; i++) { irange r(i, imax); // Intervals [i, n-1] vector_type w(R[r][i]), v(householder_s(w)); // R-= 2*v*(v'*R) MatrixR Rsub(R[r][r]); vector_type tmp(-factor * trans(Rsub) * v); rank_one_update(Rsub, v, tmp); //update Q: Q-= 2*(v*Q)*v' MatrixQ Qsub(Q[iall][r]); vector_type qtmp(-factor * Qsub * v); rank_one_update(Qsub, qtmp, v); } //end for } /// QR-Factorization of matrix A(m x n) template <typename Matrix> std::pair<mtl::matrix::dense2D<typename Collection<Matrix>::value_type, matrix::parameters<> >, mtl::matrix::dense2D<typename Collection<Matrix>::value_type, matrix::parameters<> > > inline qr(const Matrix& A) { mtl::matrix::dense2D<typename Collection<Matrix>::value_type, matrix::parameters<> > R(A), Q(num_rows(A),num_rows(A)); qr(A, Q, R); return std::make_pair(Q,R); } // QR-Factorization of matrix A // Return Q and R with A = Q*R R upper triangle and Q othogonal template <typename Matrix> std::pair<typename mtl::matrix::dense2D<typename Collection<Matrix>::value_type, matrix::parameters<> >, typename mtl::matrix::dense2D<typename Collection<Matrix>::value_type, matrix::parameters<> > > inline qr_factors(const Matrix& A) { vampir_trace<4014> tracer; using std::abs; typedef typename Collection<Matrix>::value_type value_type; // typedef typename Magnitude<value_type>::type magnitude_type; // to multiply with 2 not 2+0i typedef typename Collection<Matrix>::size_type size_type; size_type ncols = num_cols(A), nrows = num_rows(A); value_type zero= math::zero(A[0][0]), one= math::one(A[0][0]); //evaluation of Q Matrix Q(nrows, nrows), Qk(nrows, nrows), HEL(nrows, ncols), R(nrows, ncols), R_tmp(nrows, ncols); Q= one; R= zero; HEL= zero; boost::tie(Q, R_tmp)= qr(A); R= upper(R_tmp); return std::make_pair(Q,R); } }} // namespace mtl::matrix #endif // MTL_MATRIX_QR_INCLUDE
36.216216
123
0.698507
[ "vector" ]
f76017bceed718f1690efba5660151a1b98f8e20
30,896
cpp
C++
testdata/csmith-git/src/ReducerOutputMgr.cpp
Konstantin8105/c2go-rating
edba6b8aa1ce2a69a17b076596764fec656cb2f9
[ "MIT" ]
null
null
null
testdata/csmith-git/src/ReducerOutputMgr.cpp
Konstantin8105/c2go-rating
edba6b8aa1ce2a69a17b076596764fec656cb2f9
[ "MIT" ]
null
null
null
testdata/csmith-git/src/ReducerOutputMgr.cpp
Konstantin8105/c2go-rating
edba6b8aa1ce2a69a17b076596764fec656cb2f9
[ "MIT" ]
null
null
null
// -*- mode: C++ -*- // // Copyright (c) 2007, 2008, 2009, 2010, 2011, 2013, 2015, 2017 The University of Utah // All rights reserved. // // This file is part of `csmith', a random generator of C programs. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #if HAVE_CONFIG_H # include <config.h> #endif #include "ReducerOutputMgr.h" #include <cassert> #include <sstream> #include "Common.h" #include "CGOptions.h" #include "platform.h" #include "Bookkeeper.h" #include "Function.h" #include "FunctionInvocation.h" #include "FunctionInvocationUser.h" #include "ExpressionFuncall.h" #include "ExpressionVariable.h" #include "CGContext.h" #include "ArrayVariable.h" #include "VariableSelector.h" #include "Type.h" #include "random.h" #include "DeltaMonitor.h" #include "Error.h" #include "Reducer.h" #include "Block.h" #include "Statement.h" #include "StatementIf.h" #include "StatementFor.h" #include "StatementArrayOp.h" #include "StatementGoto.h" #include "StringUtils.h" #include "FactMgr.h" using namespace std; #define BINARY_REDUCTION_LIMIT 18 struct binary_reduced_stm { string cmd; string stm; int len; }; std::ostream & ReducerOutputMgr::get_main_out() { if (ofile_) return *ofile_; if (!CGOptions::output_file().empty()) { ofile_ = new ofstream(CGOptions::output_file().c_str()); return *ofile_; } else { return std::cout; } } ReducerOutputMgr::ReducerOutputMgr() : ofile_(NULL) { reducer = CGOptions::get_reducer(); assert(reducer); } ReducerOutputMgr::~ReducerOutputMgr() { if (ofile_) { ofile_->close(); delete ofile_; } } void ReducerOutputMgr::OutputHeader(int argc, char *argv[], unsigned long /*seed*/) { // output shortened header: csmith options + random_inc.h include ostream& out = get_main_out(); out << "// Options: "; if (argc <= 1) { out << " (none)"; } else { for (int i = 1; i < argc; ++i) { out << " " << argv[i]; } } out << endl; out << "#include \"csmith.h\"" << endl << endl; } void ReducerOutputMgr::output_var(const Variable* v, std::ostream &out, int indent) { if (!reducer->is_var_init_reduced(v)) { v->OutputDef(out, indent); } else { string init = reducer->map_reduced_var_inits[v]; output_tab(out, indent); v->OutputDecl(out); out << " = " << init << ";" << endl; } } void ReducerOutputMgr::output_vars(const vector<Variable*> &vars, std::ostream &out, int indent) { size_t i; int dimen = 0; vector<const ArrayVariable*> avs; // print used vars, and find the max dimension of all array variables for (i=0; i<vars.size(); i++) { const Variable* v = vars[i]; if (!reducer->is_var_used(v)) continue; output_var((const ArrayVariable*)v, out, indent); if (v->isArray) { const ArrayVariable* av = (const ArrayVariable*)(v); if (!av->no_loop_initializer()) { if (av->get_dimension() > (size_t)dimen) { dimen = av->get_dimension(); } avs.push_back(av); } } } // output array initializers if (dimen > 0) { vector <const Variable*> &ctrl_vars = Variable::get_new_ctrl_vars(); OutputArrayCtrlVars(ctrl_vars, out, dimen, indent); for (i=0; i<avs.size(); i++) { const ArrayVariable* av = avs[i]; av->output_init(out, av->init, ctrl_vars, indent); } } } int ReducerOutputMgr::output_block(const Block* blk, std::ostream& out, int indent, bool no_bracelet) { size_t i; if (reducer->is_blk_deleted(blk)) { output_tab(out, indent + 1); out << ";" << endl; return 0; } // see Reducer::config_diff_active_blks if (reducer->replaced_stms.find(blk) != reducer->replaced_stms.end() && reducer->replaced_stms[blk] == NULL) { output_tab(out, indent + 1); out << reducer->map_pre_stm_assigns[blk] << endl; return 0; } if (!no_bracelet) { output_open_encloser("{", out, indent); } // add support for "--math-notmp" if (CGOptions::math_notmp()) { blk->OutputTmpVariableList(out, indent); } output_vars(blk->local_vars, out, indent); // dump global state for top level block if necessary if (blk->parent == NULL) { output_global_state_for_func(blk->func, out, indent); } // dump "entering block ..." information output_block_entry_msg(blk, out, indent); if (reducer->dump_stms_in_blocks == blk->func) { string fname = blk->func->name; if (fname == "func_1") fname = "main"; string s = "// " + fname + " block " + StringUtils::int2str(blk->stm_id) + " ["; for (i=0; i<blk->stms.size(); i++) { if (i > 0) { s += ":"; } s += StringUtils::int2str(blk->stms[i]->stm_id); } s += "]"; output_tab(out, indent); out << s << endl; } FactMgr* fm = get_fact_mgr_for_func(blk->func); for (i=0; i<blk->stms.size(); i++) { const Statement* stm = blk->stms[i]; output_stm(stm, out, fm, indent); } if (!no_bracelet) { output_close_encloser("}", out, indent, true); } outputln(out); return 0; } int ReducerOutputMgr::output_func_header(const Function* f, std::ostream& out) { // output function header out << "static "; f->rv->qfer.output_qualified_type(f->return_type, out); out << " " << f->name << "("; size_t i; bool first = true; for (i=0; i<f->param.size(); i++) { const Variable* var = f->param[i]; if (!reducer->is_param_dropped(f, i)) { if (!first) { out << ", "; } var->output_qualified_type(out); out << " " << var->name; first = false; } } out << ")"; return 0; } void ReducerOutputMgr::output_crc_lines(std::ostream& out) { // declare loop variables if they are used in crc lines for (char c = 'i'; c <= 'z'; c++) { string pattern = string("; ") + c + "++)"; if (reducer->crc_lines.find(pattern) != string::npos) { output_tab(out, 1); out << "int " << c << " = 0;" << endl; } } if (reducer->crc_lines.find("print_hash_value") != string::npos) { output_tab(out, 1); out << "int print_hash_value = 0;" << endl; } // print the real CRC lines output_tab(out, 1); out << reducer->crc_lines << endl; } int ReducerOutputMgr::output_main_func(std::ostream& out) { size_t i; const Function* f = reducer->main; if (f->param.size() == 0 && (reducer->main_str == "" || reducer->main_str.find("func_")==0)) { out << "int main(void)" << endl; if (reducer->is_blk_deleted(f->body)) { out << "{" << endl; if (!reducer->crc_lines.empty()) { output_crc_lines(out); } output_tab(out, 1); out << "return 0;" << endl; out << "}" << endl; } else { output_block(f->body, out, 0); } } else { output_func(f, out); out << endl << "int main(void) {" << endl; output_tab(out, 1); // break up function call and parameters, and skip parameters that are reduced vector<string> strs; StringUtils::split_string(reducer->main_str, strs, "();"); assert(strs.size() == 2 || strs.size() == 1); string func_name = strs[0]; out << func_name << "("; if (strs.size() == 2) { const Function* f = find_function_by_name(func_name); assert(f); string params = strs[1]; strs.clear(); StringUtils::split_string(params, strs, ","); bool first = true; for (i=0; i<strs.size(); i++) { if (!reducer->is_param_dropped(f, i)) { if (!first) { out << ", "; } out << strs[i]; first = false; } } } out << ");" << endl; output_tab(out, 1); out << "return 0;" << endl << "}"; outputln(out); } return 0; } int ReducerOutputMgr::output_func(const Function* f, std::ostream& out) { output_func_header(f, out); out << endl; output_block(f->body, out, 0); return 0; } void ReducerOutputMgr::output_pre_stm_assigns(const Statement* stm, std::ostream &out, int indent) { if (reducer->map_pre_stm_assigns.find(stm) != reducer->map_pre_stm_assigns.end()) { string assigns = reducer->map_pre_stm_assigns[stm]; output_tab(out, indent); out << assigns; outputln(out); } } void ReducerOutputMgr::output_block_entry_msg(const Block* blk, std::ostream &out, int indent) { if (reducer->dump_block_entry) { const Statement* s = blk->find_container_stm(); if (s && s->eType == eFor) { output_tab(out, indent); out << "static int cnt = 0;" << endl; output_tab(out, indent++); out << "if (cnt++ < 1000) {" << endl; } string msg = "entering " + blk->func->name + "@" + StringUtils::int2str(blk->stm_id) + "\\n"; output_print_str(out, msg, "", indent); outputln(out); if (s && s->eType == eFor) { output_tab(out, --indent); out << "}" << endl; } } } void ReducerOutputMgr::output_pre_stm_values(const Statement* stm, std::ostream &out, FactMgr* fm, int indent) { if (find_stm_in_set(reducer->dump_value_before, stm) != -1) { assert(stm->parent); string blkid = StringUtils::int2str(stm->parent->stm_id); string id = StringUtils::int2str(stm->stm_id); out << "/* replacing " << blkid << " " << id << " before" << endl; output_write_var_values("values before " + id + "...\\n", stm, out, fm, indent, true); out << "*/" << endl; } } void ReducerOutputMgr::output_post_stm_values(const Statement* stm, std::ostream &out, FactMgr* fm, int indent) { // print value of variables that may have been written by the statement if (find_stm_in_set(reducer->dump_value_after, stm) != -1) { assert(stm->parent); string blkid = StringUtils::int2str(stm->parent->stm_id); string id = StringUtils::int2str(stm->stm_id); out << "/* replacing " << blkid << " " << id << " after" << endl; output_write_var_values("values after " + id + "...\\n", stm, out, fm, indent, true); output_memory_addrs(stm, out, indent); out << "*/" << endl; } } /* * compute the real "meaningful" length of statement or expression * anything not affecting the program complexity is ignored */ int real_length(string exp) { int len = 0; size_t i; for (i=1; i<exp.length(); i++) { if (exp[i-1] == '0' && exp[i] == 'x') { len -= 2; } if (exp[i] == 'L') { len -= 1; } if (exp[i-1] == '-' && exp[i] >= '0' && exp[i] <= '9') { len -= 1; } if (((exp[i-1] >= '0' && exp[i-1] <= '9') || (exp[i-1] >= 'A' && exp[i-1] <= 'F')) && ((exp[i] >= '0' && exp[i] <= '9') || (exp[i] >= 'A' && exp[i] <= 'F'))) { len -= 1; } len++; } return len; } /* * insert an output for a binary reduced statement into the ordered array */ void insert_alt_stm_cmd(vector<struct binary_reduced_stm>& stms, const string& cmd, const string& stm) { int len = real_length(stm); struct binary_reduced_stm alt = {cmd, stm, len}; for (size_t i=0; i<stms.size(); i++) { if (stm == stms[i].stm) return; if (len < stms[i].len) { stms.insert(stms.begin() + i, alt); return; } } stms.push_back(alt); } /* * limit the number of binary operations by removing some simple ones */ void ReducerOutputMgr::limit_binarys(vector<const FunctionInvocationBinary*>& binarys, vector<int>& ids) { int s; while (binarys.size() > BINARY_REDUCTION_LIMIT) { for (s = binarys.size() - 1; s>=0; s--) { const FunctionInvocationBinary* fib = binarys[s]; vector<const FunctionInvocationBinary*> dummy1; vector<int> dummy2; if (reducer->find_binary_operations(fib->param_value[0], dummy1, dummy2, true) == 0 && reducer->find_binary_operations(fib->param_value[1], dummy1, dummy2, true) == 0) { binarys.erase(binarys.begin() + s); ids.erase(ids.begin() + s); break; } } } // if still more than limit, delete the last few binary operations if (binarys.size() > BINARY_REDUCTION_LIMIT) { int extra = binarys.size() - BINARY_REDUCTION_LIMIT; for (s=0; s<extra; s++) { binarys.pop_back(); ids.pop_back(); } } } /******************************************************************************* * output statement with "all" possible binary reductions. * note this probably takes a long time to compute, therefore we need to limit * the number of binary operations we could reduce (default 18) *******************************************************************************/ void ReducerOutputMgr::output_alt_exprs(const Statement* stm, std::ostream &out, int indent) { size_t i, j, k, len; if (!reducer->reduce_binaries || stm->get_direct_invocation() == NULL) return; vector<const FunctionInvocationBinary*> binarys; vector<int> ids; reducer->find_binary_operations(stm, binarys, ids, true); assert(ids.size() == binarys.size()); // reduce runtime by limiting the number of binary operations we try to reduce limit_binarys(binarys, ids); vector<intvec> combinations; vector<intvec> left_trees, right_trees; reducer->build_left_right_binary_trees(binarys, left_trees, right_trees); assert(binarys.size() == left_trees.size() && binarys.size() == right_trees.size()); // special case: output "if (1)" for if conditions if (stm->eType == eIfElse) { output_tab(out, indent); out << "// [" << StringUtils::int2str(stm->stm_id) << ":0:-1] " << "if (1)" << endl; } // output the selections at single points for (i=0; i<binarys.size(); i++) { const FunctionInvocation* fi = binarys[i]; for (j=0; j<2; j++) { output_tab(out, indent); out << "// [" << StringUtils::int2str(stm->stm_id); const Expression* op = fi->param_value[j]; reducer->map_reduced_invocations[fi] = op; out << ":" + StringUtils::int2str(ids[i]) << ":" << StringUtils::int2str(j+1) << "] "; stm->eType == eIfElse ? ((const StatementIf*)stm)->output_condition(out, 0, 0) : stm->Output(out, 0, 0); reducer->map_reduced_invocations.erase(fi); } } if (binarys.size()) { output_tab(out, indent); out << "// end of single choices" << endl; } intvec orig; for (i=0; i<binarys.size(); i++) { orig.push_back(0); } combinations.push_back(orig); for (i=0; i<binarys.size(); i++) { len = combinations.size(); for (j=0; j<len; j++) { const intvec& curr = combinations[j]; if (curr[i] == 0) { // make choice, select left, fork a new combination intvec combination = curr; combination[i] = 1; intvec& skipped = right_trees[i]; for (k=0; k<skipped.size(); k++) { combination[skipped[k]] = 3; } combinations.push_back(combination); //combinations.push_back(combination); // make choice, select left, fork a new combination combination = combinations[j]; combination[i] = 2; skipped = left_trees[i]; for (k=0; k<skipped.size(); k++) { combination[skipped[k]] = 3; } combinations.push_back(combination); } } } vector<struct binary_reduced_stm> alt_stms; for (i=1; i<combinations.size(); i++) { intvec& tmp = combinations[i]; assert(tmp.size() == binarys.size()); string cmd = "// [" + StringUtils::int2str(stm->stm_id); vector<const FunctionInvocation*> reduced_invokes; for (j=0; j<binarys.size(); j++) { const FunctionInvocation* fi = binarys[j]; if (tmp[j] == 1 || tmp[j] == 2) { int choice = tmp[j]; const Expression* op = binarys[j]->param_value[choice - 1]; reducer->map_reduced_invocations[fi] = op; cmd += ":" + StringUtils::int2str(ids[j]) + ":" + StringUtils::int2str(choice); reduced_invokes.push_back(fi); } } cmd += "]"; ostringstream oss; stm->eType == eIfElse ? ((const StatementIf*)stm)->output_condition(oss, 0, 0) : stm->Output(oss, 0, 0); insert_alt_stm_cmd(alt_stms, cmd, oss.str()); // impose an artificial upper limit on number of alternatives so reducer can finish quicker if (alt_stms.size() >= 10000) { break; } for (j=0; j<reduced_invokes.size(); j++) { reducer->map_reduced_invocations.erase(reduced_invokes[j]); } } for (i=0; i<alt_stms.size(); i++) { output_tab(out, indent); out << alt_stms[i].cmd << " " << alt_stms[i].stm; } } void ReducerOutputMgr::output_if_stm(const StatementIf* si, std::ostream &out, int indent) { if (reducer->is_blk_deleted(si->get_true_branch()) && reducer->is_blk_deleted(si->get_false_branch())) { assert(0); // should have been taken care in get_used_vars_and_funcs_and_labels } else if (reducer->is_blk_deleted(si->get_false_branch())) { if (reducer->replaced_stms.find(si) != reducer->replaced_stms.end() && reducer->replaced_stms[si] == si->get_true_branch()) { output_block(si->get_true_branch(), out, indent, true); } else { if (reducer->output_if_ids) { out << "/* if reduction candidate: " << StringUtils::int2str(si->stm_id) << " */" << endl; } si->output_condition(out, 0, indent); output_block(si->get_true_branch(), out, indent); } } else if (reducer->is_blk_deleted(si->get_true_branch())) { if (reducer->replaced_stms.find(si) != reducer->replaced_stms.end() && reducer->replaced_stms[si] == si->get_false_branch()) { output_block(si->get_false_branch(), out, indent, true); } else { if (reducer->output_if_ids) { out << "/* if reduction candidate: " << StringUtils::int2str(si->stm_id) << " */" << endl; } // special case: if condition is replaced, don't flip it by outputting "!" if (reducer->is_exp_replaced(si->get_test())) { si->output_condition(out, 0, indent); } else { output_tab(out, indent); out << "if (!("; si->get_test()->Output(out); out << "))" << endl; } output_block(si->get_false_branch(), out, indent); } } else { si->output_condition(out, 0, indent); output_block(si->get_true_branch(), out, indent); output_tab(out, indent); out << "else" << endl; output_block(si->get_false_branch(), out, indent); } } void ReducerOutputMgr::output_reduced_stm(const Statement* stm, std::ostream &out, int indent) { vector<const Block*> blks; stm->get_blocks(blks); if (blks.empty()) { // insert printing value for focus variable if (stm->eType == eReturn) { // output value(s) of monitor variable(s) before return if (reducer->dump_monitored_var && stm->func->feffect.is_written_partially(reducer->monitored_var)) { output_tab(out, indent); string vname = reducer->monitored_var->name; out <<"printf(\" " << vname << " = %d\", " << vname <<");"; outputln(out); output_tab(out, indent); out << "printf(\" before leaving " << stm->func->name << ":%d\\n\", call_id);"; outputln(out); } // output value of key variable for the main function before return else if (stm->func == reducer->main) { if (reducer->monitored_var) { ostringstream oss; const Variable* key = reducer->monitored_var; oss << "checksum " << key->get_actual_name() << " = "; key->output_runtime_value(out, oss.str(), "\\n", indent, 0); outputln(out); } } if (stm->func == GetFirstFunction()) { // output crc lines if they are required if (!reducer->crc_lines.empty()) { output_crc_lines(out); } output_tab(out, indent); out << "return 0;" << endl; return; } } else if (stm->eType == eGoto && reducer->dump_block_entry) { const StatementGoto* sg = (const StatementGoto*)stm; output_tab(out, indent); out << "if ("; sg->test.Output(out); out << ")" << endl; output_open_encloser("{", out, indent); output_block_entry_msg(sg->dest->parent, out, indent); output_tab(out, indent); out << "goto " << sg->label << ";" << endl; output_close_encloser("}", out, indent); return; } stm->Output(out, 0, indent); return; } switch (stm->eType) { case eIfElse: output_if_stm((const StatementIf*)stm, out, indent); break; case eFor: { const StatementFor* sf = (const StatementFor*)stm; if (reducer->is_blk_deleted(sf->get_body())) { bool keep_body = false; const Variable* cv = sf->get_init()->get_lhs()->get_var(); if (cv == reducer->monitored_var) { vector<string> labels, req_labels; if (sf->get_body()->find_contained_labels(labels)) { size_t i; for (i=0; i<labels.size(); i++) { if (reducer->is_label_used(labels[i])) { req_labels.push_back(labels[i]); } } if (req_labels.size() > 0) { sf->output_header(out, indent); for (i=0; i<req_labels.size()-1; i++) { out << req_labels[i] << ":" << endl; } out << req_labels[req_labels.size() -1] << ": ;" << endl; keep_body = true; } } } if (!keep_body) { sf->get_init()->Output(out, 0, indent); } } else { sf->output_header(out, indent); output_block(sf->get_body(), out, indent); } break; } case eArrayOp: { const StatementArrayOp* sa = (const StatementArrayOp*)stm; if (reducer->is_blk_deleted(sa->body)) { break; } sa->output_header(out, indent); output_block(sa->body, out, indent); break; } default: break; } } void ReducerOutputMgr::output_stm(const Statement* stm, std::ostream &out, FactMgr* fm, int indent) { string str_out; // print pre-statement assignments output_pre_stm_assigns(stm, out, indent); output_pre_stm_values(stm, out, fm, indent); if (reducer->replaced_stms.find(stm) != reducer->replaced_stms.end()) { const Statement* alt_stm = reducer->replaced_stms[stm]; vector<string> labels; // special case for goto target: if the jump source is still around, we have to keep the label somehow if (reducer->find_missing_labels(stm, alt_stm, labels)) { for (size_t i=0; i<labels.size(); i++) { out << labels[i] << ": ;" << endl; } } if (alt_stm && alt_stm->eType == eBlock) { output_block((const Block*)alt_stm, out, indent, true); } else if (alt_stm) { output_stm(reducer->replaced_stms[stm], out, fm, indent); } return; } if (stm->func == reducer->rewrite_calls_inside) { rewrite_func_calls(stm, out, indent); } // print lable for jump detination string label = reducer->find_jump_label(stm); label.empty() ? (out << "") : (out << label << ":" << endl); output_alt_exprs(stm, out, indent); output_reduced_stm(stm, out, indent); output_post_stm_values(stm, out, fm, indent); } void ReducerOutputMgr::rewrite_func_call(const Statement* stm, const FunctionInvocation* invoke, string tmp_id, std::ostream& out, int indent) { // output pre-values FactMgr* fm = get_fact_mgr_for_func(stm->func); output_write_var_values("begin of values before rewrite...\\n", stm, out, fm, indent); // output "<type> t1 = <call>" const Type* type = &(invoke->get_type());; Expression* tmp_call = new ExpressionFuncall(*(invoke->clone())); CVQualifiers qfer = CVQualifiers::random_qualifiers(type, 0, 0); Variable* tmp_var = Variable::CreateVariable(tmp_id, type, tmp_call, &qfer); tmp_var->OutputDef(out, indent); // output the value of the tmp variable ostringstream oss; oss << "<" << tmp_id << " = "; tmp_var->output_runtime_value(out, oss.str(), ">\\n", indent); outputln(out); // output post values output_write_var_values("begin of values after rewrite...\\n", stm, out, fm, indent); if (reducer->is_ptr_written_in_stm(stm)) { output_memory_addrs(stm, out, indent); } ExpressionVariable* tmp_ev = new ExpressionVariable(*tmp_var); reducer->map_reduced_invocations[invoke] = tmp_ev; // output stm with call replaced with tmp_id (stm->eType == eIfElse) ? ((const StatementIf*)stm)->output_condition(out, 0, indent) : stm->Output(out, 0, indent); // clean up reducer->map_reduced_invocations.erase(invoke); delete tmp_ev; delete tmp_var; } int ReducerOutputMgr::rewrite_func_calls(const Statement* stm, std::ostream &out, int indent) { vector<const FunctionInvocationUser*> calls; const FunctionInvocation* fi = stm->get_direct_invocation(); if (fi) { vector<string> ids; string init_name = "t" + StringUtils::int2str(stm->stm_id); reducer->find_called_funcs(fi, init_name, calls, ids); if (!calls.empty()) { size_t i; for (i=0; i<calls.size(); i++) { // exclude calls that return struct/union for now because struct const is not accepted as parameter value if (calls[i]->get_type().is_aggregate()) { continue; } output_tab(out, indent); out << "/* " << "replacing " << ids[i] << endl; rewrite_func_call(stm, calls[i], ids[i], out, indent); output_tab(out, indent); out << "*/" << endl; } } } return calls.size(); } /* * dumping global states at the function entry point for path shortcutting purpose */ void ReducerOutputMgr::output_global_state_for_func(const Function* f, std::ostream &out, int indent) { if (!reducer->dump_monitored_var) return; size_t i; if (reducer->monitored_func && f == reducer->main) { output_global_values("values before main\\n", out, indent); } // output statement to increment call counter for delta purpose if (f->feffect.is_written(reducer->monitored_var)) { output_tab(out, indent); out <<"int call_id = ++global_call_id;"; outputln(out); // output global state if we are interested in this particular function call if (f == reducer->monitored_func) { assert(reducer->monitored_call_id != ""); output_tab(out, indent); out << "if (call_id == " << reducer->monitored_call_id << ")" << endl; output_open_encloser("{", out, indent); // dump addresses of global variables output_memory_addrs(f->body, out, indent); // dump global state at the beginning of this call output_global_values("values after main and before " + f->name + "\\n", out, indent); // output parameter values for this call output_print_str(out, "\\n", "", indent); output_print_str(out, f->name + "(", "", indent); bool first = true; for (i=0; i<f->param.size(); i++) { const Variable* v = f->param[i]; if (reducer->is_var_used(v)) { if (!first) { output_print_str(out, ", ", "", 0); } v->output_runtime_value(out, "", "", 0); first = false; } } output_print_str(out, ");\\n", "", indent); output_close_encloser("}", out, indent); outputln(out); } } } void ReducerOutputMgr::output_write_var_values(string title, const Statement* stm, std::ostream &out, FactMgr* fm, int indent, bool cover_block_writes) { output_print_str(out, title, "", indent); outputln(out); size_t i; const Statement* s = stm; if (cover_block_writes) { s = stm->parent; assert(s); } const vector<const Variable *>& write_vars = fm->map_stm_effect[s].get_write_vars(); for (i=0; i<write_vars.size(); i++) { const Variable* wvar = write_vars[i]; if (wvar->is_visible(stm->parent) && reducer->is_var_used(wvar)) { // output printf statements to record the type of the variable ostringstream oss; //wvar->OutputDecl(oss); string dimen = StringUtils::int2str(wvar->get_dimension()); oss << "<" << wvar->get_actual_name() << "(" << dimen << ")" << " = "; wvar->output_runtime_value(out, oss.str(), ">\\n", indent); outputln(out); } } output_print_str(out, "end of values\\n", "", indent); outputln(out); } void ReducerOutputMgr::output_memory_addrs(const Statement* stm, std::ostream& out, int indent) { size_t i; vector<Variable*> all_vars = VariableSelector::find_all_visible_vars(stm->parent); //combine_variable_sets(beffect.get_read_vars(), beffect.get_write_vars(), all_vars); //remove_field_vars(all_vars); output_print_str(out, "begin memory dump \\n", "", indent); outputln(out); for (i=0; i<all_vars.size(); i++) { const Variable* v = all_vars[i]; if (reducer->is_var_used(v)) { v->output_addressable_name(out, indent); } } output_print_str(out, "end memory dump \\n", "", indent); outputln(out); } void ReducerOutputMgr::output_global_values(string header, std::ostream& out, int indent) { size_t i; // dump values of global variables // "begin global vars entering main \\n" output_print_str(out, header, "", indent); outputln(out); for (i=0; i<reducer->used_vars.size(); i++) { const Variable* v = reducer->used_vars[i]; if (v->is_global()) { ostringstream oss; string dimen = StringUtils::int2str(v->get_dimension()); oss << "<" << v->get_actual_name() << "(" << dimen << ")" << " = "; v->output_runtime_value(out, oss.str(), ">\\n", indent); outputln(out); } } output_print_str(out, "end of values\\n", "", indent); outputln(out); } void ReducerOutputMgr::OutputStructUnions(ostream& out) { size_t i; for (i=0; i<reducer->used_vars.size(); i++) { const Type* t = reducer->used_vars[i]->type; if (t->is_aggregate()) { Type* type = Type::find_type(t); assert(type); OutputStructUnion(type, out); } } } void ReducerOutputMgr::output_artificial_globals(ostream& out) { for (size_t i=0; i<reducer->artificial_globals.size(); i++) { out << reducer->artificial_globals[i] << ";" << endl; } } void ReducerOutputMgr::output_tail(ostream& out) { size_t i; if (reducer->dump_block_entry || reducer->dump_all_block_info) { out << "// all blocks: "; // print from backward so the leaf blocks will be printed last for (i=reducer->all_blks.size(); i>0; i--) { out << StringUtils::int2str(reducer->all_blks[i-1]) << ", "; } out << endl; } if (reducer->drop_params && reducer->dump_dropped_params) { out << "// all dropped parameters: "; for (i=0; i<reducer->dropped_params.size(); i++) { out << reducer->dropped_params[i]->name << ", "; } out << endl; } } void ReducerOutputMgr::Output() { // configure reducer reducer->configure(); // find all the functions and variables that are used after reductions const Function* main = reducer->main; reducer->get_used_vars_and_funcs_and_labels(main->body, reducer->used_vars, reducer->used_funcs, reducer->used_labels); reducer->expand_used_vars(); std::ostream &out = get_main_out(); OutputStructUnions(out); output_vars(*VariableSelector::GetGlobalVariables(), out, 0); output_artificial_globals(out); size_t i; for (i=0; i<reducer->used_funcs.size(); i++) { output_func_header(reducer->used_funcs[i], out); out << ";" << endl; } for (int j=reducer->used_funcs.size(); j>0; j--) { const Function* f = reducer->used_funcs[j-1]; outputln(out); output_func(f, out); outputln(out); } outputln(out); output_main_func(out); output_tail(out); }
30.23092
146
0.646783
[ "vector" ]
f760dff3b355cebcb1f4fda1ea45d1ec74ec07dc
6,624
cpp
C++
examples/xp_example2/xp_example2.cpp
GAMS-dev/gams-cpp
0e86b3a659865edd980ed37fada1453da1552786
[ "MIT" ]
3
2017-10-19T10:54:51.000Z
2020-07-02T09:32:34.000Z
examples/xp_example2/xp_example2.cpp
GAMS-dev/gams-cpp
0e86b3a659865edd980ed37fada1453da1552786
[ "MIT" ]
4
2017-07-24T08:51:10.000Z
2020-07-08T15:02:39.000Z
examples/xp_example2/xp_example2.cpp
GAMS-dev/gams-cpp
0e86b3a659865edd980ed37fada1453da1552786
[ "MIT" ]
1
2021-07-09T16:06:04.000Z
2021-07-09T16:06:04.000Z
/** * * GAMS - General Algebraic Modeling System C++ API * * Copyright (c) 2017 GAMS Software GmbH <support@gams.com> * Copyright (c) 2017 GAMS Development Corp. <support@gams.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /* Use this command to compile the example: cl xp_example2.cpp ../C/api/gdxcc.c ../C/api/optcc.c -I../C/api */ /* This program performs the following steps: 1. Generate a gdx file with demand data 2. Calls GAMS to solve a simple transportation model (The GAMS model writes the solution to a gdx file) 3. The solution is read from the gdx file */ #include "gclgms.h" #include "gdxcc.h" #include "optcc.h" #include <stdio.h> #include <stdlib.h> #include <cstring> #include <cassert> #include <iostream> using namespace std; /* Handles to the GDX and Option objects */ gdxHandle_t gdx = NULL; optHandle_t opt = NULL; #define gdxerror(i, s) { gdxErrorStr(gdx, i, msg); \ cout << s << "% failed: " << msg << endl; return 1; } int WriteModelData(const char * fngdxfile) { int status; char msg[GMS_SSSIZE]; gdxStrIndex_t strIndex; gdxStrIndexPtrs_t sp; gdxValues_t v; gdxOpenWrite(gdx, fngdxfile, "xp_Example2", &status); if (status) gdxerror(status, "gdxOpenWrite"); if (0 == gdxDataWriteStrStart(gdx, "Demand", "Demand Data", 1, GMS_DT_PAR, 0)) gdxerror(gdxGetLastError(gdx), "gdxDataWriteStrStart"); /* Initalize some GDX data structure */ GDXSTRINDEXPTRS_INIT(strIndex, sp); strcpy(sp[0], "New-York"); v[GMS_VAL_LEVEL] = 324.0; gdxDataWriteStr(gdx, (const char **)sp, v); strcpy(sp[0], "Chicago"); v[GMS_VAL_LEVEL] = 299.0; gdxDataWriteStr(gdx, (const char **)sp, v); strcpy(sp[0], "Topeka"); v[GMS_VAL_LEVEL] = 274.0; gdxDataWriteStr(gdx, (const char **)sp, v); if (0 == gdxDataWriteDone(gdx)) gdxerror(gdxGetLastError(gdx), "gdxDataWriteDone"); if (gdxClose(gdx)) gdxerror(gdxGetLastError(gdx), "gdxClose"); return 0; } int CallGams(const char *sysdir, const char *model) { char msg[GMS_SSSIZE], deffile[GMS_SSSIZE], cmdLine[2*GMS_SSSIZE]; strncpy(deffile, sysdir, sizeof(deffile)); strncat(deffile, "/optgams.def", sizeof(deffile)); if (optReadDefinition(opt, deffile)) { int i, itype; for (i = 1; i <= optMessageCount(opt); i++) { optGetMessage(opt, i, msg, &itype); cout << msg << endl; } return 1; } optSetStrStr(opt, "input", model); optSetIntStr(opt, "logoption", 2); optWriteParameterFile(opt,"gams.opt"); sprintf(cmdLine, "\"%s/gams\" dummy pf=gams.opt", sysdir); return system(cmdLine); } int ReadSolutionData(const char *fngdxfile) { int status, VarNr, NrRecs, FDim, dim, vartype; char msg[GMS_SSSIZE], VarName[GMS_SSSIZE]; gdxStrIndex_t strIndex; gdxStrIndexPtrs_t sp; gdxValues_t v; gdxOpenRead(gdx, fngdxfile, &status); if (status) gdxerror(status, "gdxOpenRead"); strcpy(VarName, "result"); if (0 == gdxFindSymbol(gdx, VarName, &VarNr)) { cout << "Could not find variable >" << VarName << "<" << endl; return 1; } gdxSymbolInfo(gdx, VarNr, VarName, &dim, &vartype); if (2 != dim || GMS_DT_VAR != vartype) { cout << VarName << " is not a two dimensional variable" << endl; return 1; } if (0 == gdxDataReadStrStart(gdx, VarNr, &NrRecs)) gdxerror(gdxGetLastError(gdx), "gdxDataReadStrStart"); /* Initalize some GDX data structure */ GDXSTRINDEXPTRS_INIT(strIndex, sp); while (gdxDataReadStr(gdx, sp, v, &FDim)) { int i; if (0.0 == v[GMS_VAL_LEVEL]) continue; /* skip level = 0.0 is default */ for (i = 0; i < dim; i++) cout << sp[i] << ((i < dim - 1) ? "." : ""); cout << " = " << v[GMS_VAL_LEVEL] << endl; } cout << "All solution values shown" << endl; gdxDataReadDone(gdx); if ((status = gdxGetLastError(gdx))) gdxerror(status, "GDX"); if (gdxClose(gdx)) gdxerror(gdxGetLastError(gdx), "gdxClose"); return 0; } int main(int argc, char *argv[]) { int status; char sysdir[GMS_SSSIZE], model[GMS_SSSIZE], msg[GMS_SSSIZE]; const char defModel[] = "../GAMS/model2.gms"; if (argc < 2 || argc > 3) { cout << "xp_Example2: Incorrect number of parameters, first arg is sysDir, second arg is model to execute (optional)" << endl; return 1; } if (argc > 2) strncpy(model, argv[2], sizeof(model)); else strncpy(model, defModel, sizeof(model)); strncpy(sysdir, argv[1], sizeof(sysdir)); cout << "Loading objects from GAMS system directory: " << sysdir << endl; /* Create objects */ if (!gdxCreateD(&gdx, sysdir, msg, sizeof(msg))) { cout << "Could not create gdx object: " << msg << endl; return 1; } if (!optCreateD(&opt, sysdir, msg, sizeof(msg))) { cout << "Could not create opt object: " << msg << endl; return 1; } if ((status = WriteModelData("demanddata.gdx"))) { cout << "Model data not written" << endl; goto TERMINATE; } if ((status = CallGams(sysdir, model))) { cout << "Call to GAMS failed" << endl; goto TERMINATE; } if ((status = ReadSolutionData("results.gdx"))) { cout << "Could not read solution back" << endl; goto TERMINATE; } TERMINATE: return status; }
30.809302
134
0.62349
[ "object", "model" ]
f7634fe6f6e25045fbc49c6367bfddef512dba49
1,021
cpp
C++
src/simulation_observers/MultiSimulationObserver.cpp
IBM/dna-replication
2569f71c6eed0e6e9e201c1d531c2a93b69efcbe
[ "MIT" ]
null
null
null
src/simulation_observers/MultiSimulationObserver.cpp
IBM/dna-replication
2569f71c6eed0e6e9e201c1d531c2a93b69efcbe
[ "MIT" ]
null
null
null
src/simulation_observers/MultiSimulationObserver.cpp
IBM/dna-replication
2569f71c6eed0e6e9e201c1d531c2a93b69efcbe
[ "MIT" ]
3
2019-11-02T06:15:13.000Z
2022-03-09T08:51:08.000Z
#include "MultiSimulationObserver.h" namespace DNAReplication { void MultiSimulationObserver::handleOriginFired(SimulationOriginEvent const &e) { if (e.origin.getState() == Origin::State::ReplLR) { originFiringCounts[e.origin.getID()]++; originFiringTimeSums[e.origin.getID()] += e.simulation.getCurrentTime(); } } std::vector<int> MultiSimulationObserver::getOriginFiringCounts(std::vector<Origin> const &origins) { std::vector<int> result; result.reserve(origins.size()); for (Origin const &o : origins) { result.push_back(originFiringCounts[o.getID()]); } return result; } std::vector<double> MultiSimulationObserver::getOriginFiringTimeSums(const std::vector<Origin> &origins) { std::vector<double> result; result.reserve(origins.size()); for (Origin const &o : origins) { result.push_back(originFiringTimeSums[o.getID()]); } return result; } }
34.033333
110
0.63859
[ "vector" ]
f76ee8570ec63b6cc6ecc6f95abf94c63dd0b1da
21,412
cpp
C++
src/TFmini_plus.cpp
Leenix/TFmini_plus_driver
0876bdebefe3729eb0e4c22281990a3b7c1a827e
[ "MIT" ]
null
null
null
src/TFmini_plus.cpp
Leenix/TFmini_plus_driver
0876bdebefe3729eb0e4c22281990a3b7c1a827e
[ "MIT" ]
null
null
null
src/TFmini_plus.cpp
Leenix/TFmini_plus_driver
0876bdebefe3729eb0e4c22281990a3b7c1a827e
[ "MIT" ]
null
null
null
#include <TFmini_plus.h> /////////////////////////////////////////////////////////////////////////////// /** * Send a packet to the lidar. * Data is sent by either UART or I2C; whichever is actively in use. * * @param input: Array containing headers, payload, and checksum. * @param size: Number of bytes to send. * @return: True for successful transmission. */ bool TFminiPlus::send(uint8_t *input, uint8_t size) { bool result = false; if (_communications_mode == TFMINI_PLUS_UART) result = send_uart(input, size); if (_communications_mode == TFMINI_PLUS_I2C) result = send_i2c(input, size); return result; } /** * Send the packet over UART. * Both software and hardware implementations are allowed. * @param input: Data packet to send. * @param size: Number of bytes to send. * @return: True if the correct number of bytes were sent. */ bool TFminiPlus::send_uart(uint8_t *input, uint8_t size) { // Burn any other bytes waiting in the receive buffer dump_serial_cache(); dump_serial_cache(); uint8_t bytes_sent = _stream->write(input, size) == size; return bytes_sent == size; } /** * Send the packet over I2C. * Both software and hardware implementations are allowed. * @param input: Data packet to send. * @param size: Number of bytes to send. * @return: True if the correct number of bytes were sent. */ bool TFminiPlus::send_i2c(uint8_t *input, uint8_t size) { Wire.beginTransmission(_address); uint8_t bytes_sent = Wire.write(input, size); if (bytes_sent != size) Wire.write(0); uint8_t error = Wire.endTransmission(true); return (bytes_sent == size and not error); } /** * Send a command packet to the lidar. * Command packets use the following structure: * [0] 0x5A - Command header * [1] Length of packet * [2] Command code * [3-n] Command arguments (Not all commands have arguments) * [n] Checksum * * @param command: 8-bit command to send; see TFMINI_PLUS_COMMANDS. * @param arguments: Container containing the command arguments in little-endian format. * @param size: Total number of bytes to send, including header and checksum. * @return: True if the transmission was successful. */ bool TFminiPlus::send_command(tfminiplus_command_t command, uint8_t *arguments, uint8_t size) { bool result; uint8_t packet[size]; packet[0] = TFMINI_PLUS_FRAME_START; packet[1] = size; packet[2] = command; // Put arguments into the packet as-is, assuming the endianess has been handled elsewhere if (size > TFMINI_PLUS_MINIMUM_PACKET_SIZE) { for (uint8_t i = 0; i < size - TFMINI_PLUS_MINIMUM_PACKET_SIZE; i++) { packet[TFMINI_PLUS_MINIMUM_PACKET_SIZE - 1 + i] = arguments[i]; } } // Slap on the checksum and run packet[size - 1] = calculate_checksum(packet, size - 1); result = send(packet, size); return result; } /** * Send a command packet to the lidar. * Only to be used with commands that do not take arguments. * * @param command: 8-bit command to send; see TFMINI_PLUS_COMMANDS. * @return: True if the transmission was successful. */ bool TFminiPlus::send_command(tfminiplus_command_t command) { return send_command(command, 0, TFMINI_PLUS_MINIMUM_PACKET_SIZE); } /////////////////////////////////////////////////////////////////////////////// /** * Get a packet from the lidar. * Data is received by either UART or I2c; whichever is actively in use. * * @param output: Container for received data, headers, and checksum. * @param size: Number of bytes expected to receive. * @return: True if the received length and checksum is valid */ bool TFminiPlus::receive(uint8_t *output, uint8_t size) { bool result = false; uint8_t bytes_received = 0; // Grab data from stream if (_communications_mode == TFMINI_PLUS_UART) bytes_received = receive_uart(output, size); if (_communications_mode == TFMINI_PLUS_I2C) bytes_received = receive_i2c(output, size); result = (bytes_received == size); // Data is valid if the packet length matches the received length value and if the checksum matches result &= compare_checksum(output, size); return result; } /** * Receive data from the UART. * * @param output: Container for data to read into. * @param size: Number of bytes expected to be read. * @return: True if the expected number of bytes was read. */ uint8_t TFminiPlus::receive_uart(uint8_t *output, uint8_t size, unsigned long timeout) { bool packet_start_found = false; unsigned long start_time = millis(); uint8_t bytes_read = 0; // Discard data until a valid packet header is found (0x5a) while ((millis() - start_time) < timeout and not packet_start_found) { if (_stream->available() >= size) { if (_stream->read() == TFMINI_PLUS_FRAME_START) { if (_stream->read() == size) { packet_start_found = true; output[0] = TFMINI_PLUS_FRAME_START; output[1] = size; bytes_read = _stream->readBytes(&output[2], size - 2) + 2; } } } } return bytes_read; } /** * Receive data from the I2C bus. * * @param output: Container for data to read into. * @param size: Number of bytes expected to be read. * @return: True if the expected number of bytes was read. */ uint8_t TFminiPlus::receive_i2c(uint8_t *output, uint8_t size) { Wire.requestFrom(_address, size, true); uint8_t bytes_read = 0; for (size_t i = 0; (i < size) and Wire.available(); i++) { uint8_t c = Wire.read(); output[i] = c; bytes_read++; } return bytes_read; } /** * Get a data packet from UART. * Data packets can be received at any time, so a synchronised packet start is not guaranteed. * This function discards received data until a valid packet is found. * Only the first valid packet is read. More packets may be available in the stream's buffer. * * @param output: Container to read data into. * @param size: Number of bytes that are expected to be received * @return: True if the expected number of bytes were received. */ bool TFminiPlus::uart_receive_data(uint8_t *output, uint8_t size, unsigned long timeout) { bool packet_start_found = false; unsigned long start_time = millis(); // Discard data until a valid packet header is found (0x5959) while ((millis() - start_time) < timeout and not packet_start_found) { if (_stream->available() >= 9) { if (_stream->read() == TFMINI_PLUS_RESPONSE_FRAME_HEADER and _stream->read() == TFMINI_PLUS_RESPONSE_FRAME_HEADER) { output[0] = TFMINI_PLUS_RESPONSE_FRAME_HEADER; output[1] = TFMINI_PLUS_RESPONSE_FRAME_HEADER; packet_start_found = true; } } } // Read in the rest of the packet uint8_t bytes_read = _stream->readBytes(&output[2], size - 2) + 2; return bytes_read == size; } /////////////////////////////////////////////////////////////////////////////// /** * Check if the calculate checksum of a data packet matches the sent checksum byte. * * @param data: Container of received packet. * @param size: Number of bytes contained in the packet, including headers and checksum. * @return: True if the checksums match. */ bool TFminiPlus::compare_checksum(uint8_t *data, uint8_t size) { uint8_t checksum = calculate_checksum(data, size - 1); bool checksums_match = checksum == data[size - 1]; return checksums_match; } /** * Calculate the checksum for a container. * * @param data: Container with data to calculate checksum. * @param size: Number of bytes in container. * @return: Checksum of data in the container. */ uint8_t TFminiPlus::calculate_checksum(uint8_t *data, uint8_t size) { uint8_t checksum = 0; for (size_t i = 0; i < size; i++) { checksum += data[i]; } return checksum; } /** * Wait for the lidar to process a command. * This wait is only required when using the I2C bus. * This wait is also not required when requesting a data packet on either communication mode. */ void TFminiPlus::do_i2c_wait() { if (_communications_mode == TFMINI_PLUS_I2C) delay(150); } /////////////////////////////////////////////////////////////////////////////// /** * Start communication with the lidar in I2C mode. * @param address: I2C address of the lidar. Defaults to 0x10. */ void TFminiPlus::begin(uint8_t address) { _communications_mode = TFMINI_PLUS_I2C; _address = address & 0x7F; } /** * Start communication with the lidar in UART mode. * @param stream: Pointer to a stream object for communication (eg. HardwareSerial or SoftwareSerial) */ void TFminiPlus::begin(Stream *stream) { _communications_mode = TFMINI_PLUS_UART; _stream = stream; _stream->flush(); } /** * Set the I2C address of the lidar. * This will change the slave address of the lidar so the device is mapped to a separate logical location. * Changes will take effect immediately upon confirmation that the address has been received correctly. * * @param address: I2C slave address to change the lidar to. (0x01 - 0x7F) * @param return: True if the address change was successful. * */ bool TFminiPlus::set_i2c_address(uint8_t address) { bool result = false; send_command(TFMINI_PLUS_SET_I2C_ADDRESS, &address, TFMINI_PLUS_PACK_LENGTH_SET_I2C_ADDRESS); do_i2c_wait(); // Only commit the changes if the correct address is echoed back uint8_t response[TFMINI_PLUS_PACK_LENGTH_SET_I2C_ADDRESS]; if (receive(response, sizeof(response)) and response[3] == address) { result = save_settings(); if (result) { _address = address; } } return result; } /** * Get the firmware version of the lidar. * * @return: Version information of lidar firmware. [major, minor, revision] */ tfminiplus_version_t TFminiPlus::get_version() { tfminiplus_version_t version; send_command(TFMINI_PLUS_GET_VERSION); do_i2c_wait(); uint8_t response[TFMINI_PLUS_PACK_LENGTH_VERSION_RESPONSE]; if (receive(response, sizeof(response)) and response[TFMINI_PLUS_PACKET_POS_COMMAND] == TFMINI_PLUS_GET_VERSION) { version.revision = response[3]; version.minor = response[4]; version.major = response[5]; } return version; } /** * Set the framerate of the lidar. * The datasheet recommends that the refresh rate stay below 100Hz when using I2C mode. * Changes will not take effect until settings have been saved. * * @param framerate: Framerate to set the lidar to in Hz. * @return: True if the framerate change was successfully received. */ bool TFminiPlus::set_framerate(tfminiplus_framerate_t framerate) { bool result = false; uint8_t argument[2]; argument[0] = framerate & 0xFF; argument[1] = framerate >> 8; send_command(TFMINI_PLUS_SET_FRAME_RATE, argument, TFMINI_PLUS_PACK_LENGTH_SET_FRAME_RATE); do_i2c_wait(); uint8_t response[TFMINI_PLUS_PACK_LENGTH_SET_FRAME_RATE]; if (receive(response, sizeof(response))) { if (argument[0] == response[3] and argument[1] == response[4]) result = true; } return result; } /** * Set the baudrate of the lidar. * Changes will not take effect until settings have been saved. * * @param baudrate: Baudrate to set UART communications to. * @return: True if the baudrate change was successfully received. */ bool TFminiPlus::set_baudrate(tfminiplus_baudrate_t baudrate) { bool result = false; uint8_t argument[4]; argument[0] = baudrate & 0xFF; argument[1] = baudrate >> 8; argument[2] = baudrate >> 16; argument[3] = baudrate >> 24; send_command(TFMINI_PLUS_SET_BAUD_RATE, argument, TFMINI_PLUS_PACK_LENGTH_SET_BAUD_RATE); do_i2c_wait(); // Verify the echoed baudrate uint8_t response[TFMINI_PLUS_PACK_LENGTH_SET_BAUD_RATE]; if (receive(response, sizeof(response))) { if (argument[0] == response[3] and argument[1] == response[4] and argument[2] == response[5] and argument[3] == response[6]) result = true; } return result; } /** * Set the output format of the lidar. * The output format changes the output units or enables a pixhawk-compatible stream. * Changes must be saved to take effect. * * @param format: Format option to change the lidar output to. * @result: True if the format change was received succesfully. */ bool TFminiPlus::set_output_format(tfminiplus_output_format_t format) { bool result = false; send_command(TFMINI_PLUS_SET_OUTPUT_FORMAT, (uint8_t *)&format, TFMINI_PLUS_PACK_LENGTH_SET_OUTPUT_FORMAT); do_i2c_wait(); uint8_t response[TFMINI_PLUS_PACK_LENGTH_SET_OUTPUT_FORMAT]; if (receive(response, sizeof(response))) { if (format == response[3]) result = true; } return result; } /** * Take a manual reading of the lidar. * This method is useful when the framerate has been changed to 0 Hz * and readings are taken on an on-demand basis. * * @param data: Data container to read the lidar output into. * @return: True if a data output frame was received successfully. */ bool TFminiPlus::read_manual_reading(tfminiplus_data_t &data) { trigger_manual_reading(); return read_data(data); } /** * Request the lidar to do a manual read. * Useful for on-demand measurements. */ void TFminiPlus::trigger_manual_reading() { send_command(TFMINI_PLUS_TRIGGER_DETECTION); } /** * Take a manual reading of the lidar. * This method is useful when the framerate has been changed to 0 Hz * and readings are taken on an on-demand basis. * * @return: Data container that includes distance, strength, and temperature measurements. */ tfminiplus_data_t TFminiPlus::get_manual_reading() { tfminiplus_data_t data; read_manual_reading(data); return data; } /** * Take a manual reading of the lidar. * This method is useful when the framerate has been changed to 0 Hz * and readings are taken on an on-demand basis. * * @return: Distance in cm/mm (depending on configuration). */ uint16_t TFminiPlus::get_manual_distance() { return get_manual_reading().distance; } /** * Read a data frame from the lidar. * If using the UART interface, frames are continually sent and do not need to be specifically requested. * * @param data: Data container to read output frame into. * @param in_mm_format: True to request the data frame in mm units (I2C only). * @return: True if the data frame was received successfully. */ bool TFminiPlus::read_data(tfminiplus_data_t &data, bool in_mm_format) { uint8_t command = 1 + 5 * in_mm_format; if (_communications_mode == TFMINI_PLUS_I2C) send_command(TFMINI_PLUS_GET_DATA, &command, TFMINI_PLUS_PACK_LENGTH_GET_DATA); do_i2c_wait(); return read_data_response(data); } /** * Read a data frame from the lidar. * If using the UART interface, frames are continually sent and do not need to be specifically requested. * * @param in_mm_format: True to request the data frame in mm units (I2C only). * @return: Data container that includes distance, strength, and temperature measurements. */ tfminiplus_data_t TFminiPlus::get_data(bool in_mm_format) { tfminiplus_data_t data; read_data(data, in_mm_format); return data; } /** * Read a data frame from the lidar. * If using the UART interface, frames are continually sent and do not need to be specifically requested. * * @param in_mm_format: True to request the data frame in mm units (I2C only). * @return: Distance in cm/mm (depending on configuration). */ uint16_t TFminiPlus::get_distance(bool in_mm_format) { return get_data(in_mm_format).distance; } /** * Read in a response frame from the lidar. * Data frames are read in normally with I2C mode after a request. * In UART mode, frames are sent in when available. * * @param data: Data frame to read the lidar output into. * @return: True if the response was received correctly. */ bool TFminiPlus::read_data_response(tfminiplus_data_t &data) { bool result = false; // Grab the data uint8_t response[TFMINI_PLUS_PACK_LENGTH_DATA_RESPONSE]; if (_communications_mode == TFMINI_PLUS_UART) { result = uart_receive_data(response, sizeof(response)); } else { result = receive(response, sizeof(response)); } // Put the data into the proper format data.distance = response[2] + (response[3] << 8); result &= data.distance > 0; data.strength = response[4] + (response[5] << 8); result &= data.strength > 0 and data.strength != 65535; data.temperature = (response[6] + (response[7] << 8)) / 8.0 - 256; result &= data.temperature < 100; return result; } /** * Set the IO mode of the lidar. * Changes will not occur until settings have been saved. * Modes: * 0 - Standard: Output is transmitted over UART or I2C. * 1 - IO LN/HF - Output pin is high if the measured distance is above the defined distance; otherwise low. * 2 - IO HN/LF - Output pin is low if the measured distance is above the defined distance; otherwise high. * * @param mode: Output mode of the lidar [0-2]. * @param critical_distance: Threshold distance in cm for the near/far zones when using IO modes. * @param hysteresis: Hysteresis in cm used when switching between near/far zones when using IO modes. * @return: True if the mode change was received successfully. */ bool TFminiPlus::set_io_mode(tfminiplus_mode_t mode, uint16_t critical_distance, uint16_t hysteresis) { uint8_t arguments[5]; arguments[0] = mode; arguments[1] = uint8_t(critical_distance); arguments[2] = critical_distance >> 8; arguments[3] = uint8_t(hysteresis); arguments[4] = hysteresis >> 8; return send_command(TFMINI_PLUS_SET_IO_MODE, arguments, TFMINI_PLUS_PACK_LENGTH_SET_IO_MODE); } /** * Set the communication mode for the lidar. * Changes are applied immediately. * The library will switch to use the mode specified if the change was successfully applied. * * @param mode: Communication mode. [UART, I2C] * @return: True if the settings were saved correctly. */ bool TFminiPlus::set_communication_interface(tfminiplus_communication_mode_t mode) { bool result; send_command(TFMINI_PLUS_SET_COMMUNICATION_INTERFACE, (uint8_t *)&mode, TFMINI_PLUS_PACK_LENGTH_SET_COMMUNICATION_INTERFACE); result = save_settings(); if (result) { _communications_mode = mode; } return result; } /** * Enable or disable the lidar output. * The datasheet is unclear as to whether the lidar will still respond to communication or data requests if output * is disabled. * Changes must be saved to be applied. * * @param output_enabled: True to enable output; False to disable. * @return: True if the command was received successfully. */ bool TFminiPlus::enable_output(bool output_enabled) { bool result = false; send_command(TFMINI_PLUS_ENABLE_DATA_OUTPUT, (uint8_t *)&output_enabled, TFMINI_PLUS_PACK_LENGTH_ENABLE_DATA_OUTPUT); do_i2c_wait(); uint8_t response[TFMINI_PLUS_PACK_LENGTH_ENABLE_DATA_OUTPUT]; if (receive(response, sizeof(response))) { if (output_enabled == response[3]) result = true; } return result; } /** * Apply written settings to the lidar. * The datasheet is unclear as to whether saved settings are persistent across power cycles. * * @return: True is settings were save successfully. */ bool TFminiPlus::save_settings() { bool result = false; send_command(TFMINI_PLUS_SAVE_SETTINGS); do_i2c_wait(); uint8_t response[TFMINI_PLUS_PACK_LENGTH_SAVE_SETTINGS_RESPONSE]; if (receive(response, sizeof(response))) { if (response[3] == 0) { result = true; } } return result; } /** * Reset the lidar. * Not sure what this does exactly... * * @return: True if reset occurred? */ bool TFminiPlus::reset_system() { bool result = false; send_command(TFMINI_PLUS_SYSTEM_RESET); do_i2c_wait(); uint8_t response[TFMINI_PLUS_PACK_LENGTH_SYSTEM_RESET_RESPONSE]; if (receive(response, sizeof(response))) { if (response[3] == 0) result = true; } return result; } /** * Reset the lidar's settings back to their factory defaults. * The factory reset does not affect the communication mode. * * @return: True if the factory reset was successful. */ bool TFminiPlus::factory_reset() { bool result = false; send_command(TFMINI_PLUS_RESTORE_FACTORY_SETTINGS); do_i2c_wait(); uint8_t response[TFMINI_PLUS_PACK_LENGTH_RESTORE_FACTORY_SETTINGS_RESPONSE]; if (receive(response, sizeof(response))) { if (response[3] == 0) result = true; } return result; } /** * Calculate the effective accuracy of the lidar. * * @param strength: Strength of the last reading. * @param frequency: Framerate of the lidar. * @return: Effective accuracy of the lidar in cm. */ float TFminiPlus::get_effective_accuracy(uint16_t strength, uint16_t frequency) { float x = log10(strength); float y = log10(frequency); float ranging_accuracy = TFMINI_PLUS_P00 + TFMINI_PLUS_P10 * x + TFMINI_PLUS_P01 * y + TFMINI_PLUS_P20 * x * x + TFMINI_PLUS_P11 * x * y; return ranging_accuracy; } void TFminiPlus::dump_serial_cache() { while (_stream->available()) { _stream->read(); } _stream->flush(); }
33.561129
147
0.692742
[ "object" ]
f76f7bfcd81df81fa4d72642ab725e2a4b07c015
7,324
cpp
C++
src/gui/src/axes_grid.cpp
Ruzzyy/anysim
6bc590056754e7dc89a1078ab4c41823075088d2
[ "MIT" ]
4
2019-05-13T11:51:27.000Z
2019-09-25T15:18:03.000Z
src/gui/src/axes_grid.cpp
Ruzzyy/anysim
6bc590056754e7dc89a1078ab4c41823075088d2
[ "MIT" ]
null
null
null
src/gui/src/axes_grid.cpp
Ruzzyy/anysim
6bc590056754e7dc89a1078ab4c41823075088d2
[ "MIT" ]
3
2019-06-08T12:46:13.000Z
2020-01-09T10:35:22.000Z
// // Created by egi on 5/23/19. // #include "axes_grid.h" #include "cpp/common_funcs.h" #include "core/gpu/coloring.cuh" #include <QPainter> axes_grid::axes_grid () : QOpenGLFunctions (), font ("Arial", 10) { } void axes_grid::initialize_gl (QObject *parent) { initializeOpenGLFunctions (); program = new QOpenGLShaderProgram (parent); if (!program->isLinked ()) { program->addShaderFromSourceFile (QOpenGLShader::Vertex, ":/shaders/axes_grid.vert"); program->addShaderFromSourceFile (QOpenGLShader::Fragment, ":/shaders/axes_grid.frag"); program->link (); } attribute_coord2d = program->attributeLocation ("coord2d"); glGenBuffers (1, &vbo_vertices); } void axes_grid::prepare ( float left_x_arg, float right_x_arg, float bottom_y_arg, float top_y_arg) { top_y = top_y_arg; left_x = left_x_arg; right_x = right_x_arg; bottom_y = bottom_y_arg; x_size = (right_x - left_x); y_size = (top_y - bottom_y); } void axes_grid::init_data () { const unsigned int points_per_line = 2; const unsigned int coords_per_point = 2; const unsigned int coords_per_oxs = 2 * x_tics * points_per_line * coords_per_point; const unsigned int coords_per_oys = 2 * y_tics * points_per_line * coords_per_point; const unsigned int border_coords = 8 * coords_per_point; const unsigned int tiks_coords = coords_per_oxs + coords_per_oys; total_coords = border_coords + tiks_coords; coords.reset (); coords = std::make_unique<GLfloat[]> (total_coords); coords[tiks_coords + 0] = left_x; coords[tiks_coords + 1] = bottom_y; coords[tiks_coords + 2] = left_x; coords[tiks_coords + 3] = top_y; coords[tiks_coords + 4] = left_x; coords[tiks_coords + 5] = top_y; coords[tiks_coords + 6] = right_x; coords[tiks_coords + 7] = top_y; coords[tiks_coords + 8] = right_x; coords[tiks_coords + 9] = top_y; coords[tiks_coords + 10] = right_x; coords[tiks_coords + 11] = bottom_y; coords[tiks_coords + 12] = right_x; coords[tiks_coords + 13] = bottom_y; coords[tiks_coords + 14] = left_x; coords[tiks_coords + 15] = bottom_y; float dy = (top_y - bottom_y) / (y_tics - 1); float *p_coords = coords.get (); const bool in = false; /// Tics are inside model const short int dir = in ? -1 : 1; for (unsigned int y = 0; y < y_tics; y++) { const float ts = y % long_tic_each == 0 ? long_tic_size : tic_size; p_coords[0] = left_x; p_coords[1] = bottom_y + dy * y; p_coords[2] = left_x - dir * ts; p_coords[3] = bottom_y + dy * y; p_coords[4] = right_x; p_coords[5] = bottom_y + dy * y; p_coords[6] = right_x + dir * ts; p_coords[7] = bottom_y + dy * y; p_coords += 8; } float dx = (right_x - left_x) / (x_tics - 1); for (unsigned int x = 0; x < x_tics; x++) { const float ts = x % long_tic_each == 0 ? long_tic_size : tic_size; p_coords[0] = left_x + dx * x; p_coords[1] = bottom_y; p_coords[2] = left_x + dx * x; p_coords[3] = bottom_y - dir * ts; p_coords[4] = left_x + dx * x; p_coords[5] = top_y; p_coords[6] = left_x + dx * x; p_coords[7] = top_y + dir * ts; p_coords += 8; } glBindBuffer (GL_ARRAY_BUFFER, vbo_vertices); glBufferData (GL_ARRAY_BUFFER, sizeof (GLfloat) * total_coords, coords.get (), GL_DYNAMIC_DRAW); } void axes_grid::resize (int window_width_arg, int window_height_arg) { window_width = window_width_arg; window_height = window_height_arg; } void axes_grid::draw (const QMatrix4x4 &mvp, QPainter &painter) { QFontMetrics fm (font); painter.beginNativePainting (); const char *format = "%.2e"; const double x_max_number = x_size; QVector4D lbc (left_x, bottom_y, 0.0, 1.0); QVector4D rtc (right_x, top_y, 0.0, 1.0); lbc = mvp * lbc; rtc = mvp * rtc; // TODO Get ticks count unsigned int new_tick_count_x = 1; unsigned int new_tick_count_y = 1; { int size = std::snprintf (nullptr, 0, format, x_max_number); buf.resize (size + 1); std::snprintf (buf.data (), buf.size (), format, x_max_number); const int max_text_height = fm.height (); const int max_text_width = fm.width (QString::fromStdString (buf.data ())); const float right_bottom_corner_x = map (rtc.x (), -1.0, 1.0, 0.0, static_cast<float> (window_width)); const float right_bottom_corner_y = map (lbc.y (), -1.0, 1.0, 0.0, static_cast<float> (window_height)); const float left_top_corner_x = map (lbc.x (), -1.0, 1.0, 0.0, static_cast<float> (window_width)); const float left_top_corner_y = map (rtc.y (), -1.0, 1.0, 0.0, static_cast<float> (window_height)); const int screen_width = (right_bottom_corner_x - left_top_corner_x); const int screen_height = (left_top_corner_y - right_bottom_corner_y); const int text_fits_y = screen_height / max_text_height; const int text_fits_x = screen_width / max_text_width; new_tick_count_x = long_tic_each * text_fits_x / 2; new_tick_count_y = long_tic_each * text_fits_y / 2; } if (new_tick_count_x != x_tics || new_tick_count_y != y_tics) { x_tics = new_tick_count_x; y_tics = new_tick_count_y; init_data (); } program->bind(); program->setUniformValue ("MVP", mvp); glEnableVertexAttribArray (attribute_coord2d); glBindBuffer (GL_ARRAY_BUFFER, vbo_vertices); glVertexAttribPointer (attribute_coord2d, 2, GL_FLOAT, GL_FALSE, 0, 0); glLineWidth (2.2); glDrawArrays (GL_LINES, 0, total_coords); glDisableVertexAttribArray (attribute_coord2d); glBindBuffer (GL_ARRAY_BUFFER, 0); program->release (); painter.endNativePainting (); painter.setPen(Qt::black); painter.setFont(font); const float dx = x_size / (x_tics - 1); const float dy = y_size / (y_tics - 1); float *p_coords = coords.get (); for (unsigned int y = 0; y < y_tics; y+=long_tic_each) { const double number = y * dy; const int size = std::snprintf (nullptr, 0, format, number); buf.resize (size + 1); std::snprintf (buf.data (), buf.size (), format, number); QVector4D v (p_coords[2] - long_tic_size / 4, p_coords[3], 0.0, 1.0); v = mvp * v; const int right_bottom_corner_x = map (v.x (), -1.0, 1.0, 0.0, static_cast<float> (window_width)); const int right_bottom_corner_y = map (v.y (), 1.0, -1.0, 0.0, static_cast<float> (window_height)) + fm.height () / 2; painter.drawText (QRect (0, 0, right_bottom_corner_x, right_bottom_corner_y), Qt::AlignRight | Qt::AlignBottom, QString::fromStdString (buf.data ())); p_coords += 8 * long_tic_each; } p_coords = coords.get () + 8 * y_tics; for (unsigned int x = 0; x < x_tics; x+=long_tic_each) { const double number = x * dx; const int size = std::snprintf (nullptr, 0, format, number); buf.resize (size + 1); std::snprintf (buf.data (), buf.size (), format, number); QVector4D v (p_coords[2], p_coords[3] - long_tic_size / 4, 0.0, 1.0); v = mvp * v; const int right_bottom_corner_x = map (v.x (), -1.0, 1.0, 0.0, static_cast<float> (window_width)); const int right_bottom_corner_y = map (v.y (), 1.0, -1.0, 0.0, static_cast<float> (window_height)); painter.drawText (QRect (right_bottom_corner_x, right_bottom_corner_y, window_width, window_height), Qt::AlignLeft | Qt::AlignTop, QString::fromStdString (buf.data ())); p_coords += 8 * long_tic_each; } }
31.843478
173
0.668624
[ "model" ]
f7733eadd44bab27aca9c353fb372c16ef05e77a
1,027
cpp
C++
codeforces/gym/2019-2020 ACM-ICPC Brazil Subregional Programming Contest/d.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
4
2020-10-05T19:24:10.000Z
2021-07-15T00:45:43.000Z
codeforces/gym/2019-2020 ACM-ICPC Brazil Subregional Programming Contest/d.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
codeforces/gym/2019-2020 ACM-ICPC Brazil Subregional Programming Contest/d.cpp
tysm/cpsols
262212646203e516d1706edf962290de93762611
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define int long long #define ii pair<int, int> #define ff first #define ss second #define vi vector<int> #define vii vector<ii> #define pb push_back #define MAX (int32_t(1e6)+1) #define INF (int32_t(1e9)+1) using namespace std; vi adj[MAX]; vii leafs; void dfs(int s, int nvl){ if(adj[s].empty()) leafs.pb({nvl, s}); for(auto i:adj[s]) dfs(i, nvl+1); } int32_t main(){ int n, k; cin >> n >> k; int p[MAX] = {}; for(int i=2; i<=n; ++i){ cin >> p[i]; adj[p[i]].pb(i); } dfs(1, 0); sort(leafs.rbegin(), leafs.rend()); vi outs, vis(MAX, 0); for(auto l:leafs){ int i = l.ss, res = 1; vis[i] = true; while(p[i] and !vis[p[i]]){ i = p[i]; vis[i] = true; res++; } outs.pb(res); } sort(outs.rbegin(), outs.rend()); int ans = 0; for(int i=0; i<min(k, (int)outs.size()); ++i) ans += outs[i]; cout << ans << endl; return 0; }
20.137255
49
0.491723
[ "vector" ]
f779cb8852c657de66150b25838c65cd5d8b7a17
9,614
cpp
C++
isis/src/mro/objs/HiCal/LoadCSV.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
134
2018-01-18T00:16:24.000Z
2022-03-24T03:53:33.000Z
isis/src/mro/objs/HiCal/LoadCSV.cpp
kdl222/ISIS3
aab0e63088046690e6c031881825596c1c2cc380
[ "CC0-1.0" ]
3,825
2017-12-11T21:27:34.000Z
2022-03-31T21:45:20.000Z
isis/src/mro/objs/HiCal/LoadCSV.cpp
jlaura/isis3
2c40e08caed09968ea01d5a767a676172ad20080
[ "CC0-1.0" ]
164
2017-11-30T21:15:44.000Z
2022-03-23T10:22:29.000Z
/** This is free and unencumbered software released into the public domain. The authors of ISIS do not claim copyright on the contents of this file. For more details about the LICENSE terms and the AUTHORS, you will find files of those names at the top level of this repository. **/ /* SPDX-License-Identifier: CC0-1.0 */ #include <QString> #include <vector> #include <numeric> #include <iostream> #include <sstream> #include "LoadCSV.h" #include "FileName.h" #include "IException.h" using namespace std; namespace Isis { LoadCSV::LoadCSV() : _base(), _csvSpecs("LoadCSV"), _data(0,0), _history() { } LoadCSV::LoadCSV(const QString &base, const HiCalConf &conf, const DbProfile &profile) : _base(), _csvSpecs("LoadCSV"), _data(0,0), _history() { load(base, conf, profile); } void LoadCSV::load(const QString &base, const HiCalConf &conf, const DbProfile &profile) { // Initialize the object with necessary info init(base, conf, profile); // Set up access to the CSV table. Note that HiCalConf.getMatrixSource() // method is typically used, but the parsing has been broken up here for // implementation purposes. QString csvfile(conf.filepath(getValue())); addHistory("File", csvfile); CSVReader csv; // Retrieve information regarding the format within the CSV bool colHeader(IsEqual(ConfKey(_csvSpecs,makeKey("Header"), QString("FALSE")), "TRUE")); bool rowHeader(colHeader); // Both default to state of the {BASE}Header if (IsEqual(getValue("ColumnHeader"), "TRUE")) colHeader = true; if (IsEqual(getValue("RowHeader"), "TRUE")) rowHeader = true; if (_csvSpecs.exists(makeKey("ColumnName"))) colHeader = true; if (_csvSpecs.exists(makeKey("RowName") )) rowHeader = true; // Skip lines, comment headers and separator int skip = toInt(ConfKey(_csvSpecs, makeKey("SkipLines"), QString("0"))); addHistory("SkipLines", ToString(skip)); bool comments = IsEqual(ConfKey(_csvSpecs, makeKey("IgnoreComments"), QString("TRUE"))); QString separator = ConfKey(_csvSpecs, makeKey("Separator"), QString(",")); if (separator.isEmpty()) separator = ","; // Guarantees content // Apply conditions csv.setComment(comments); csv.setSkip(skip); csv.setHeader(colHeader); csv.setDelimiter(separator[0].toLatin1()); if (separator[0] == ' ') csv.setSkipEmptyParts(); // Now read the file FileName csvF(csvfile); csvfile = csvF.expanded(); try { csv.read(csvfile); } catch (IException &ie) { QString mess = "Could not read CSV file \'" + csvfile + "\'"; throw IException(ie, IException::User, mess, _FILEINFO_); } // Now get the data from the CSV table int ncols = csv.columns(); int nrows = csv.rows(); // Initial conditions selects all rows and columns int startColumn((rowHeader) ? 1 : 0), endColumn(ncols-1); int startRow(0), endRow(nrows-1); // Update columns QString colName(getValue("ColumnName")); if (!colName.isEmpty()) { addHistory("ColumnName", colName); CSVReader::CSVAxis chead = csv.getHeader(); startColumn = getAxisIndex(colName, chead); if (startColumn < 0) { QString mess = "Column name " + colName + " not found in CSV file " + csvfile; throw IException(IException::User, mess, _FILEINFO_); } endColumn = startColumn; addHistory("ColumnIndex", ToString(startColumn)); } else if (!(getValue("ColumnIndex").isEmpty())) { startColumn = ToInteger(getValue("ColumnIndex")) + ((rowHeader) ? 1 : 0); endColumn = startColumn; addHistory("ColumnStart", ToString(startColumn)); addHistory("ColumnEnd", ToString(endColumn)); } // Update row indicies QString rowName(getValue("RowName")); if (!rowName.isEmpty()) { addHistory("RowName", rowName); if (!rowHeader) { QString mess = "Row name given but config does not specify presence of row header!"; throw IException(IException::User, mess, _FILEINFO_); } CSVReader::CSVAxis rhead = csv.getColumn(0); startRow = getAxisIndex(rowName, rhead); if (startRow < 0) { QString mess = "Row name " + rowName + " not found in CSV file " + csvfile; throw IException(IException::User, mess, _FILEINFO_); } endRow = startRow; addHistory("RowIndex", ToString(startRow)); } else if (!(getValue("RowIndex").isEmpty())) { startRow = ToInteger(getValue("RowIndex")); if (rowHeader) startRow++; endRow = startRow; addHistory("RowStart", ToString(startRow)); addHistory("RowEnd", ToString(endRow)); } // Now ready to read all row/columns and convert to matrix int drows(endRow-startRow+1); int dcols(endColumn-startColumn+1); HiMatrix d(drows, dcols); vector<QString> errors; for (int r = startRow, hr = 0 ; r <= endRow ; r++, hr++) { CSVReader::CSVAxis row = csv.getRow(r); for (int c = startColumn, hc = 0 ; c <= endColumn ; c++, hc++) { try { d[hr][hc] = ToDouble(row[c]); } catch (...) { std::ostringstream mess; mess << "Invalid real value (" << row[c] << ") in row index " << r; if (!rowName.isEmpty()) mess << " (Name:" << rowName << ")"; mess << ", column index " << c; if (!colName.isEmpty()) mess << " (Name:" << colName << ")"; errors.push_back(mess.str().c_str()); d[hr][hc] = Null; } } } // Save data anyway _data = d; // Check for errors if (errors.size() > 0) { //iException::Clear(); Not sure how this could ever do anything std::ostringstream mess; mess << "Conversion errors in CSV file " + csvfile + ": Errors: "; std::vector<QString>::const_iterator it = errors.begin(); while (it != errors.end()) { mess << *it << "; "; it++; } throw IException(IException::User, mess.str().c_str(), _FILEINFO_); } return; } QString LoadCSV::filename() const { return (getValue()); } int LoadCSV::size() const { return (_data.dim1() * _data.dim2()); } bool LoadCSV::validateSize(const int &expected, const bool &throw_on_error) const { if (expected != size()) { if (!throw_on_error) return (false); ostringstream mess; mess << "Invalid count (Expected: " << expected << ", Received: " << size() << ") in CSV file " << getValue(); throw IException(IException::User, mess.str(), _FILEINFO_); } return (true); } HiVector LoadCSV::getVector() const { HiVector v(size(), const_cast<double *> (_data[0])); return (v.copy()); } HiMatrix LoadCSV::getMatrix() const { return (_data.copy()); } void LoadCSV::History(HiHistory &history) const { std::ostringstream mess; mess << "LoadCSV("; QString comma(""); for (unsigned int i = 0 ; i < _history.size() ; i++) { mess << comma << _history[i]; comma = ","; } mess << ")"; history.add(mess.str().c_str()); return; } void LoadCSV::init(const QString &base, const HiCalConf &conf, const DbProfile &profile) { _base = base; _csvSpecs = ResolveKeys(base, conf, profile); _history.clear(); return; } void LoadCSV::addHistory(const QString &element, const QString &desc) { std::ostringstream mess; mess << element << "[" << desc << "]"; _history.push_back(mess.str().c_str()); } void LoadCSV::getKeyList(const QString &base, std::vector<QString> &keys) const { keys.clear(); keys.push_back(base); keys.push_back(base+"IgnoreComments"); keys.push_back(base+"ColumnHeader"); keys.push_back(base+"ColumnName"); keys.push_back(base+"ColumnIndex"); keys.push_back(base+"RowHeader"); keys.push_back(base+"RowName"); keys.push_back(base+"RowIndex"); keys.push_back(base+"SkipLines"); keys.push_back(base+"Header"); keys.push_back(base+"Separator"); return; } DbProfile LoadCSV::ResolveKeys(const QString &base, const HiCalConf &conf, const DbProfile &prof) const { vector<QString> keys; getKeyList(base, keys); DbProfile keyprof("LoadCSV"); for (unsigned int i = 0 ; i < keys.size() ; i++) { QString kvalue = ParsedKey(keys[i], conf, prof); if (!kvalue.isEmpty()) keyprof.add(keys[i], kvalue); } return (keyprof); } QString LoadCSV::ParsedKey(const QString &key, const HiCalConf &conf, const DbProfile &prof) const { QString value(""); if (prof.exists(key)) { value = conf.resolve(prof(key), prof); } return (value); } QString LoadCSV::makeKey(const QString &suffix) const { QString key = _base + suffix; return (key); } QString LoadCSV::getValue(const QString &suffix) const { QString key = makeKey(suffix); QString value(""); if (_csvSpecs.exists(key)) value = _csvSpecs(key); return (value); } int LoadCSV::getAxisIndex(const QString &name, const CSVReader::CSVAxis &header) const { QString head = name.trimmed(); for (int i = 0 ; i < header.dim() ; i++) { if (head.toLower() == header[i].toLower().trimmed()) { return (i); } } return (-1); } } // namespace ISIS
32.47973
92
0.601103
[ "object", "vector" ]
f77f97081916ae993a1d737dfbae917c28ca8dfa
19,456
cpp
C++
OREAnalytics/orea/scenario/crossassetmodelscenariogenerator.cpp
nvolfango/Engine
a5ee0fc09d5a50ab36e50d55893b6e484d6e7004
[ "BSD-3-Clause" ]
1
2021-03-30T17:24:17.000Z
2021-03-30T17:24:17.000Z
OREAnalytics/orea/scenario/crossassetmodelscenariogenerator.cpp
zhangjiayin/Engine
a5ee0fc09d5a50ab36e50d55893b6e484d6e7004
[ "BSD-3-Clause" ]
null
null
null
OREAnalytics/orea/scenario/crossassetmodelscenariogenerator.cpp
zhangjiayin/Engine
a5ee0fc09d5a50ab36e50d55893b6e484d6e7004
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (C) 2016 Quaternion Risk Management Ltd All rights reserved. This file is part of ORE, a free-software/open-source library for transparent pricing and risk analysis - http://opensourcerisk.org ORE is free software: you can redistribute it and/or modify it under the terms of the Modified BSD License. You should have received a copy of the license along with this program. The license is also available online at <http://opensourcerisk.org> This program is distributed on the basis that it will form a useful contribution to risk analytics and model standardisation, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include <orea/scenario/crossassetmodelscenariogenerator.hpp> #include <ored/utilities/log.hpp> #include <ored/utilities/parsers.hpp> #include <qle/indexes/inflationindexobserver.hpp> #include <qle/models/dkimpliedyoyinflationtermstructure.hpp> #include <qle/models/dkimpliedzeroinflationtermstructure.hpp> #include <qle/models/lgmimpliedyieldtermstructure.hpp> using namespace QuantLib; using namespace QuantExt; using namespace std; namespace ore { namespace analytics { using namespace QuantExt::CrossAssetModelTypes; CrossAssetModelScenarioGenerator::CrossAssetModelScenarioGenerator( boost::shared_ptr<QuantExt::CrossAssetModel> model, boost::shared_ptr<QuantExt::MultiPathGeneratorBase> pathGenerator, boost::shared_ptr<ScenarioFactory> scenarioFactory, boost::shared_ptr<ScenarioSimMarketParameters> simMarketConfig, Date today, boost::shared_ptr<DateGrid> grid, boost::shared_ptr<ore::data::Market> initMarket, const std::string& configuration) : ScenarioPathGenerator(today, grid->dates(), grid->timeGrid()), model_(model), pathGenerator_(pathGenerator), scenarioFactory_(scenarioFactory), simMarketConfig_(simMarketConfig), initMarket_(initMarket), configuration_(configuration) { QL_REQUIRE(initMarket != NULL, "CrossAssetScenarioGenerator: initMarket is null"); QL_REQUIRE(timeGrid_.size() == dates_.size() + 1, "date/time grid size mismatch"); // TODO, curve tenors might be overwritten by dates in simMarketConfig_, here we just take the tenors // Cache yield curve keys Size n_ccy = model_->components(IR); discountCurveKeys_.reserve(n_ccy * simMarketConfig_->yieldCurveTenors("").size()); for (Size j = 0; j < model_->components(IR); j++) { std::string ccy = model_->irlgm1f(j)->currency().code(); ten_dsc_.push_back(simMarketConfig_->yieldCurveTenors(ccy)); Size n_ten = ten_dsc_.back().size(); for (Size k = 0; k < n_ten; k++) discountCurveKeys_.emplace_back(RiskFactorKey::KeyType::DiscountCurve, ccy, k); // j * n_ten + k } // Cache index curve keys Size n_indices = simMarketConfig_->indices().size(); indexCurveKeys_.reserve(n_indices * simMarketConfig_->yieldCurveTenors("").size()); for (Size j = 0; j < n_indices; ++j) { ten_idx_.push_back(simMarketConfig_->yieldCurveTenors(simMarketConfig_->indices()[j])); Size n_ten = ten_idx_.back().size(); for (Size k = 0; k < n_ten; ++k) { indexCurveKeys_.emplace_back(RiskFactorKey::KeyType::IndexCurve, simMarketConfig_->indices()[j], k); } } // Cache yield curve keys Size n_curves = simMarketConfig_->yieldCurveNames().size(); yieldCurveKeys_.reserve(n_curves * simMarketConfig_->yieldCurveTenors("").size()); for (Size j = 0; j < n_curves; ++j) { ten_yc_.push_back(simMarketConfig_->yieldCurveTenors(simMarketConfig_->yieldCurveNames()[j])); Size n_ten = ten_yc_.back().size(); for (Size k = 0; k < n_ten; ++k) { yieldCurveKeys_.emplace_back(RiskFactorKey::KeyType::YieldCurve, simMarketConfig_->yieldCurveNames()[j], k); } } // Cache FX rate keys fxKeys_.reserve(n_ccy - 1); for (Size k = 0; k < n_ccy - 1; k++) { const string& foreign = model_->irlgm1f(k + 1)->currency().code(); // Is this safe? const string& domestic = model_->irlgm1f(0)->currency().code(); fxKeys_.emplace_back(RiskFactorKey::KeyType::FXSpot, foreign + domestic); // k } // set up CrossAssetModelImpliedFxVolTermStructures if (simMarketConfig_->simulateFXVols()) { LOG("CrossAssetModel is simulating FX vols"); for (Size k = 0; k < simMarketConfig_->fxVolCcyPairs().size(); k++) { // Calculating the index is messy const string pair = simMarketConfig_->fxVolCcyPairs()[k]; LOG("Set up CrossAssetModelImpliedFxVolTermStructures for " << pair); QL_REQUIRE(pair.size() == 6, "Invalid ccypair " << pair); const string& domestic = pair.substr(0, 3); const string& foreign = pair.substr(3); QL_REQUIRE(domestic == model_->irlgm1f(0)->currency().code(), "Only DOM-FOR fx vols supported"); Size index = model->ccyIndex(parseCurrency(foreign)); // will throw if foreign not there QL_REQUIRE(index > 0, "Invalid index for ccy " << foreign << " should be > 0"); // fxVols_ are indexed by ccyPairs LOG("Pair " << pair << " index " << index); // index - 1 to convert "IR" index into an "FX" index fxVols_.push_back(boost::make_shared<CrossAssetModelImpliedFxVolTermStructure>(model_, index - 1)); LOG("Set up CrossAssetModelImpliedFxVolTermStructures for " << pair << " done"); } } // Cache EQ rate keys Size n_eq = model_->components(EQ); eqKeys_.reserve(n_eq); for (Size k = 0; k < n_eq; k++) { const string& eqName = model_->eqbs(k)->name(); eqKeys_.emplace_back(RiskFactorKey::KeyType::EquitySpot, eqName); } // equity vols if (simMarketConfig_->equityVolNames().size() > 0 && simMarketConfig_->simulateEquityVols()) { LOG("CrossAssetModel is simulating EQ vols"); for (Size k = 0; k < simMarketConfig_->equityVolNames().size(); k++) { // Calculating the index is messy const string equityName = simMarketConfig_->equityVolNames()[k]; LOG("Set up CrossAssetModelImpliedEqVolTermStructures for " << equityName); Size eqIndex = model->eqIndex(equityName); // eqVols_ are indexed by ccyPairs LOG("EQ Vol Name = " << equityName << ", index = " << eqIndex); // index - 1 to convert "IR" index into an "FX" index eqVols_.push_back(boost::make_shared<CrossAssetModelImpliedEqVolTermStructure>(model_, eqIndex)); LOG("Set up CrossAssetModelImpliedEqVolTermStructures for " << equityName << " done"); } } // Cache INF rate keys0 Size n_inf = model_->components(INF); if (n_inf > 0) { cpiKeys_.reserve(n_inf); for (Size j = 0; j < n_inf; ++j) { cpiKeys_.emplace_back(RiskFactorKey::KeyType::CPIIndex, model->infdk(j)->name()); } Size n_zeroinf = simMarketConfig_->zeroInflationIndices().size(); if (n_zeroinf > 0) { zeroInflationKeys_.reserve(n_zeroinf * simMarketConfig_->zeroInflationTenors("").size()); for (Size j = 0; j < n_zeroinf; ++j) { ten_zinf_.push_back(simMarketConfig_->zeroInflationTenors(simMarketConfig_->zeroInflationIndices()[j])); Size n_ten = ten_zinf_.back().size(); for (Size k = 0; k < n_ten; ++k) { zeroInflationKeys_.emplace_back(RiskFactorKey::KeyType::ZeroInflationCurve, simMarketConfig_->zeroInflationIndices()[j], k); } } } Size n_yoyinf = simMarketConfig_->yoyInflationIndices().size(); if (n_yoyinf > 0) { yoyInflationKeys_.reserve(n_yoyinf * simMarketConfig_->yoyInflationTenors("").size()); for (Size j = 0; j < n_yoyinf; ++j) { ten_yinf_.push_back(simMarketConfig_->yoyInflationTenors(simMarketConfig_->yoyInflationIndices()[j])); Size n_ten = ten_yinf_.back().size(); for (Size k = 0; k < n_ten; ++k) { yoyInflationKeys_.emplace_back(RiskFactorKey::KeyType::YoYInflationCurve, simMarketConfig_->yoyInflationIndices()[j], k); } } } } } std::vector<boost::shared_ptr<Scenario>> CrossAssetModelScenarioGenerator::nextPath() { std::vector<boost::shared_ptr<Scenario>> scenarios(dates_.size()); Sample<MultiPath> sample = pathGenerator_->next(); Size n_ccy = model_->components(IR); Size n_eq = model_->components(EQ); Size n_inf = model_->components(INF); Size n_indices = simMarketConfig_->indices().size(); Size n_curves = simMarketConfig_->yieldCurveNames().size(); Size n_zeroinf = simMarketConfig_->zeroInflationIndices().size(); Size n_yoyinf = simMarketConfig_->yoyInflationIndices().size(); vector<boost::shared_ptr<QuantExt::LgmImpliedYieldTermStructure>> curves, fwdCurves, yieldCurves; vector<boost::shared_ptr<QuantExt::DkImpliedZeroInflationTermStructure>> zeroInfCurves; vector<boost::shared_ptr<QuantExt::DkImpliedYoYInflationTermStructure>> yoyInfCurves; vector<boost::shared_ptr<IborIndex>> indices; vector<Currency> yieldCurveCurrency; vector<boost::shared_ptr<QuantExt::LgmImpliedYieldTermStructure>> equityForecastCurves; vector<Currency> equityForecastCurrency; vector<string> zeroInflationIndex, yoyInflationIndex; DayCounter dc = model_->irlgm1f(0)->termStructure()->dayCounter(); for (Size j = 0; j < n_ccy; ++j) { curves.push_back(boost::make_shared<QuantExt::LgmImpliedYieldTermStructure>(model_->lgm(j), dc, true)); } for (Size j = 0; j < n_indices; ++j) { std::string indexName = simMarketConfig_->indices()[j]; boost::shared_ptr<IborIndex> index = *initMarket_->iborIndex(indexName, configuration_); Handle<YieldTermStructure> fts = index->forwardingTermStructure(); auto impliedFwdCurve = boost::make_shared<LgmImpliedYtsFwdFwdCorrected>( model_->lgm(model_->ccyIndex(index->currency())), fts, dc, false); fwdCurves.push_back(impliedFwdCurve); indices.push_back(index->clone(Handle<YieldTermStructure>(impliedFwdCurve))); } for (Size j = 0; j < n_curves; ++j) { std::string curveName = simMarketConfig_->yieldCurveNames()[j]; Currency ccy = ore::data::parseCurrency(simMarketConfig_->yieldCurveCurrencies().at(curveName)); Handle<YieldTermStructure> yts = initMarket_->yieldCurve(curveName, configuration_); auto impliedYieldCurve = boost::make_shared<LgmImpliedYtsFwdFwdCorrected>(model_->lgm(model_->ccyIndex(ccy)), yts, dc, false); yieldCurves.push_back(impliedYieldCurve); yieldCurveCurrency.push_back(ccy); } for (Size j = 0; j < n_zeroinf; ++j) { zeroInfCurves.push_back(boost::make_shared<QuantExt::DkImpliedZeroInflationTermStructure>(model_, j)); } for (Size j = 0; j < n_yoyinf; ++j) { yoyInfCurves.push_back(boost::make_shared<QuantExt::DkImpliedYoYInflationTermStructure>(model_, j)); } for (Size j = 0; j < n_eq; ++j) { std::string curveName = simMarketConfig_->equityNames()[j]; Currency ccy = model_->eqbs(j)->currency(); equityForecastCurrency.push_back(ccy); } for (Size i = 0; i < dates_.size(); i++) { Real t = timeGrid_[i + 1]; // recall: time grid has inserted t=0 scenarios[i] = scenarioFactory_->buildScenario(dates_[i]); // Set numeraire, numeraire currency and the (deterministic) domestic discount // Asset index 0 in sample.value[0][i+1] refers to the domestic currency process. Real z0 = sample.value[0][i + 1]; // domestic LGM factor, second index = 0 holds initial values scenarios[i]->setNumeraire(model_->numeraire(0, t, z0)); // Discount curves for (Size j = 0; j < n_ccy; j++) { // LGM factor value, second index = 0 holds initial values Real z = sample.value[model_->pIdx(IR, j)][i + 1]; curves[j]->move(t, z); for (Size k = 0; k < ten_dsc_[j].size(); k++) { Date d = dates_[i] + ten_dsc_[j][k]; Time T = dc.yearFraction(dates_[i], d); Real discount = std::max(curves[j]->discount(T), 0.00001); scenarios[i]->add(discountCurveKeys_[j * ten_dsc_[j].size() + k], discount); } } // Index curves and Index fixings for (Size j = 0; j < n_indices; ++j) { Real z = sample.value[model_->pIdx(IR, model_->ccyIndex(indices[j]->currency()))][i + 1]; fwdCurves[j]->move(dates_[i], z); for (Size k = 0; k < ten_idx_[j].size(); ++k) { Date d = dates_[i] + ten_idx_[j][k]; Time T = dc.yearFraction(dates_[i], d); Real discount = std::max(fwdCurves[j]->discount(T), 0.00001); scenarios[i]->add(indexCurveKeys_[j * ten_idx_[j].size() + k], discount); } } // Yield curves for (Size j = 0; j < n_curves; ++j) { Real z = sample.value[model_->pIdx(IR, model_->ccyIndex(yieldCurveCurrency[j]))][i + 1]; yieldCurves[j]->move(dates_[i], z); for (Size k = 0; k < ten_yc_[j].size(); ++k) { Date d = dates_[i] + ten_yc_[j][k]; Time T = dc.yearFraction(dates_[i], d); Real discount = std::max(yieldCurves[j]->discount(T), 0.00001); scenarios[i]->add(yieldCurveKeys_[j * ten_yc_[j].size() + k], discount); } } // FX rates for (Size k = 0; k < n_ccy - 1; k++) { // if (i == 0) { // construct the labels at the first scenario date only // const string& foreign = model_->irlgm1f(k+1)->currency().code(); // Is this safe? // const string& domestic = model_->irlgm1f(0)->currency().code(); // ccyPairs[k] = foreign + domestic; // x USDEUR means 1 USD is worth x EUR // } Real fx = std::exp(sample.value[model_->pIdx(FX, k)][i + 1]); // multiplies USD amount to get EUR scenarios[i]->add(fxKeys_[k], fx); } // FX vols if (simMarketConfig_->simulateFXVols()) { const vector<Period>& expires = simMarketConfig_->fxVolExpiries(); for (Size k = 0; k < simMarketConfig_->fxVolCcyPairs().size(); k++) { const string ccyPair = simMarketConfig_->fxVolCcyPairs()[k]; Size fxIndex = fxVols_[k]->fxIndex(); Real zFor = sample.value[fxIndex + 1][i + 1]; Real logFx = sample.value[n_ccy + fxIndex][i + 1]; // multiplies USD amount to get EUR fxVols_[k]->move(dates_[i], z0, zFor, logFx); for (Size j = 0; j < expires.size(); j++) { Real vol = fxVols_[k]->blackVol(dates_[i] + expires[j], Null<Real>(), true); scenarios[i]->add(RiskFactorKey(RiskFactorKey::KeyType::FXVolatility, ccyPair, j), vol); } } } // Equity spots for (Size k = 0; k < n_eq; k++) { Real eqSpot = std::exp(sample.value[model_->pIdx(EQ, k)][i + 1]); scenarios[i]->add(eqKeys_[k], eqSpot); } // Equity vols if (simMarketConfig_->simulateEquityVols()) { const vector<Period>& expiries = simMarketConfig_->equityVolExpiries(); for (Size k = 0; k < simMarketConfig_->equityVolNames().size(); k++) { const string equityName = simMarketConfig_->equityVolNames()[k]; Size eqIndex = eqVols_[k]->equityIndex(); Size eqCcyIdx = eqVols_[k]->eqCcyIndex(); Real z_eqIr = sample.value[eqCcyIdx][i + 1]; Real logEq = sample.value[eqIndex][i + 1]; eqVols_[k]->move(dates_[i], z_eqIr, logEq); for (Size j = 0; j < expiries.size(); j++) { Real vol = eqVols_[k]->blackVol(dates_[i] + expiries[j], Null<Real>(), true); scenarios[i]->add(RiskFactorKey(RiskFactorKey::KeyType::EquityVolatility, equityName, j), vol); } } } // Inflation curves for (Size j = 0; j < n_inf; j++) { // LGM factor value, second index = 0 holds initial values Real z = sample.value[model_->pIdx(INF, j, 0)][i + 1]; Real y = sample.value[model_->pIdx(INF, j, 1)][i + 1]; // update fixing manage with fixing for base date boost::shared_ptr<ZeroInflationIndex> index = *initMarket_->zeroInflationIndex(model_->infdk(j)->name()); Date baseDate = index->zeroInflationTermStructure()->baseDate(); Time relativeTime = inflationYearFraction(index->zeroInflationTermStructure()->frequency(), index->zeroInflationTermStructure()->indexIsInterpolated(), index->zeroInflationTermStructure()->dayCounter(), baseDate, dates_[i] - index->zeroInflationTermStructure()->observationLag()); std::pair<Real, Real> ii = model_->infdkI(j, relativeTime, relativeTime, z, y); Real baseCPI = index->fixing(baseDate); scenarios[i]->add(cpiKeys_[j], baseCPI * ii.first); } for (Size j = 0; j < n_zeroinf; ++j) { std::string indexName = simMarketConfig_->zeroInflationIndices()[j]; Real z = sample.value[model_->pIdx(INF, model_->infIndex(indexName), 0)][i + 1]; Real y = sample.value[model_->pIdx(INF, model_->infIndex(indexName), 1)][i + 1]; zeroInfCurves[j]->move(dates_[i], z, y); for (Size k = 0; k < ten_zinf_[j].size(); k++) { Date d = dates_[i] + ten_zinf_[j][k]; Time T = dc.yearFraction(dates_[i], d); Real zero = zeroInfCurves[j]->zeroRate(T); scenarios[i]->add(zeroInflationKeys_[j * ten_zinf_[j].size() + k], zero); } } for (Size j = 0; j < n_yoyinf; ++j) { std::string indexName = simMarketConfig_->yoyInflationIndices()[j]; Size ccy = model_->ccyIndex(model_->infdk(j)->currency()); Real z = sample.value[model_->pIdx(INF, model_->infIndex(indexName), 0)][i + 1]; Real y = sample.value[model_->pIdx(INF, model_->infIndex(indexName), 1)][i + 1]; Real ir_z = sample.value[model_->pIdx(IR, ccy)][i + 1]; yoyInfCurves[j]->move(dates_[i], z, y, ir_z); vector<Date> d_yinf; for (Size k = 0; k < ten_yinf_[j].size(); k++) d_yinf.push_back(dates_[i] + ten_yinf_[j][k]); map<Date, Real> yoyRates = yoyInfCurves[j]->yoyRates(d_yinf); for (Size l = 0; l < d_yinf.size(); l++) { scenarios[i]->add(yoyInflationKeys_[j * ten_yinf_[j].size() + l], yoyRates[d_yinf[l]]); } } // TODO: Further risk factor classes are added here } return scenarios; } } // namespace analytics } // namespace ore
50.015424
120
0.611174
[ "vector", "model" ]
f78ac0a848a0e42b3fb982ecd01b11763a50b045
4,788
cpp
C++
openEAR-0.1.0/src/nnlPlugin.cpp
trimlab/Voice-Emotion-Detection
c7272dd2f70e2d4b8eee304e68578494d7ef624c
[ "MIT" ]
null
null
null
openEAR-0.1.0/src/nnlPlugin.cpp
trimlab/Voice-Emotion-Detection
c7272dd2f70e2d4b8eee304e68578494d7ef624c
[ "MIT" ]
null
null
null
openEAR-0.1.0/src/nnlPlugin.cpp
trimlab/Voice-Emotion-Detection
c7272dd2f70e2d4b8eee304e68578494d7ef624c
[ "MIT" ]
null
null
null
/*F****************************************************************************** * * openSMILE - open Speech and Music Interpretation by Large-space Extraction * the open-source Munich Audio Feature Extraction Toolkit * Copyright (C) 2008-2009 Florian Eyben, Martin Woellmer, Bjoern Schuller * * * Institute for Human-Machine Communication * Technische Universitaet Muenchen (TUM) * D-80333 Munich, Germany * * * If you use openSMILE or any code from openSMILE in your research work, * you are kindly asked to acknowledge the use of openSMILE in your publications. * See the file CITING.txt for details. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ******************************************************************************E*/ /* openSMILE component: example dataSink writes data to data memory... */ #include <nnlPlugin.hpp> #define MODULE "nnlPlugin" #undef class #ifdef HAVE_RTNNLLIB #include <nn/engine/NetController.h> #include <nn/netcdf/NetcdfDataset.h> #include <smileCommon.hpp> #include <smileComponent.hpp> #include <stdio.h> SMILECOMPONENT_STATICS(nnlPlugin) SMILECOMPONENT_REGCOMP(nnlPlugin) { SMILECOMPONENT_REGCOMP_INIT scname = COMPONENT_NAME_NNLSINK; sdescription = COMPONENT_DESCRIPTION_NNL; // we inherit cDataSink configType and extend it: SMILECOMPONENT_INHERIT_CONFIGTYPE("cDataSink") SMILECOMPONENT_IFNOTREGAGAIN( ct->setField("netconfigFile","net configuration: xml generated by nnl",""); ct->setField("dataDimensionsFile","file with the data dimensions generated by DataDimensionsGen of rt_nnl",""); ct->setField("standardizeFile","mean and variance of the test data to use for standardization of the input",""); ) SMILECOMPONENT_MAKEINFO(nnlPlugin); } SMILECOMPONENT_CREATE(nnlPlugin) //----- nnlPlugin::nnlPlugin(const char *_name) : cDataSink(_name) { means = NULL; stddevs = NULL; } void nnlPlugin::fetchConfig() { cDataSink::fetchConfig(); SMILE_IMSG(3,"configuring nnlPlugin..\n"); netconfigFile = getStr("netconfigFile"); //printf("netconfigFile=%s\n",netconfigFilename); SMILE_IDBG(2,"netconfigFile = '%s'",netconfigFile); dataDimensionsFile = getStr("dataDimensionsFile"); SMILE_IDBG(2,"dataDimensionsFile = '%s'",dataDimensionsFile); standardizeFile = getStr("standardizeFile"); SMILE_IDBG(2,"standardizeFile = '%s'",standardizeFile); } /* int nnlPlugin::myConfigureInstance() { int ret=1; ret *= cDataSink::myConfigureInstance(); return ret; } */ int nnlPlugin::myFinaliseInstance() { int ret=1; ret *= cDataSink::myFinaliseInstance(); if (ret) { controller = new NetController(); char* ddFile = new char[sizeof(dataDimensionsFile)]; strcpy(ddFile,dataDimensionsFile); ((NetController*)controller)->init(netconfigFile,ddFile); } return ret; } int nnlPlugin::myTick(long long t){ SMILE_DBG(4,"tick # %i, reading value vector:",t); //cVector *vec= reader->getNextFrame(); cVector *vec= reader->getFrameRel(0); if (vec == NULL) return 0; //else reader->nextFrame(); float* standardizedInputs = new float[vec->N]; std::string standardizeFileName(standardizeFile); if (!standardizeFileName.empty()){ if (means==NULL){ initStandardizationValues(vec->N); } //the input dimensions are not known at the time of the plugin initialization //unless we try to read the dataDims-File, but this is the responsibility of the nnl-core for (int i=0; i<vec->N; i++){ standardizedInputs[i] = (vec->dataF[i] - means[i])/stddevs[i]; } }else{ standardizedInputs = vec->dataF; } string result = ((NetController*)controller)->recognize(standardizedInputs); if (!result.empty()){ cout << result << " "; cout.flush(); } // tick success return 1; } /** dim: input dimension*/ void nnlPlugin::initStandardizationValues(long dim) { FILE *nd = fopen(standardizeFile,"rb"); means = new double[dim]; stddevs = new double[dim]; if (nd != NULL) { fread(means, sizeof(double)*dim, 1, nd); fread(stddevs, sizeof(double)*dim, 1, nd); fclose(nd); } } nnlPlugin::~nnlPlugin(){ } #endif //HAVE_RTNNLLIB
26.748603
115
0.694862
[ "vector" ]
f78b54fbd16ac17ad07e748046078fbee442b4c9
18,431
cpp
C++
Windows/WListDataDialog.cpp
cas-nctu/multispec
0bc840bdb073b5feaeec650c2da762cfa34ee37d
[ "Apache-2.0" ]
11
2020-03-10T02:06:00.000Z
2022-02-17T19:59:50.000Z
Windows/WListDataDialog.cpp
cas-nctu/multispec
0bc840bdb073b5feaeec650c2da762cfa34ee37d
[ "Apache-2.0" ]
null
null
null
Windows/WListDataDialog.cpp
cas-nctu/multispec
0bc840bdb073b5feaeec650c2da762cfa34ee37d
[ "Apache-2.0" ]
5
2020-05-30T00:59:22.000Z
2021-12-06T01:37:05.000Z
// MultiSpec // // Copyright 1988-2020 Purdue Research Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at: https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. // // MultiSpec is curated by the Laboratory for Applications of Remote Sensing at // Purdue University in West Lafayette, IN and licensed by Larry Biehl. // // File: WListDataDialog.cpp : implementation file // // Authors: Larry L. Biehl // // Revision date: 08/08/2019 // // Language: C++ // // System: Windows Operating System // // Brief description: This file contains functions that relate to the // CMListDataDialog class. // //------------------------------------------------------------------------------------ #include "SMultiSpec.h" #include "WMultiSpec.h" #include "WListDataDialog.h" extern ListDataSpecsPtr gListDataSpecsPtr; #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif BEGIN_MESSAGE_MAP (CMListDataDialog, CMDialog) //{{AFX_MSG_MAP (CMListDataDialog) ON_BN_CLICKED (IDC_Area, OnArea) ON_BN_CLICKED (IDC_Classes, OnClasses) ON_BN_CLICKED (IDC_GraphData, OnGraphData) ON_BN_CLICKED (IDEntireImage, ToEntireImage) ON_BN_CLICKED (IDSelectedImage, ToSelectedImage) ON_CBN_SELENDOK (IDC_ChannelCombo, OnSelendokChannelCombo) ON_CBN_SELENDOK (IDC_ClassCombo, OnSelendokClassCombo) ON_CBN_SELENDOK (IDC_ListChannelsFormatCombo, OnCbnSelendokListchannelsformatcombo) ON_EN_CHANGE(IDC_ColumnEnd, CheckColumnEnd) ON_EN_CHANGE(IDC_ColumnStart, CheckColumnStart) ON_EN_CHANGE(IDC_LineEnd, CheckLineEnd) ON_EN_CHANGE(IDC_LineStart, CheckLineStart) //}}AFX_MSG_MAP END_MESSAGE_MAP () CMListDataDialog::CMListDataDialog ( CWnd* pParent /*=NULL*/) : CMDialog (CMListDataDialog::IDD, pParent) { //{{AFX_DATA_INIT(CMListDataDialog) m_areaFlag = FALSE; m_classFlag = FALSE; m_diskFileFlag = FALSE; m_graphDataFlag = FALSE; m_includeClassFieldFlag = FALSE; m_includeLineColumnFlag = FALSE; m_includeLatLongFlag = FALSE; m_textWindowFlag = FALSE; m_trainingFlag = FALSE; m_testFlag = FALSE; m_listDataFormatCode = -1; m_numberDecimalPlaces = 2; //}}AFX_DATA_INIT m_initializedFlag = CMDialog::m_initializedFlag; if (m_initializedFlag) { // Get pointer to memory for temporary storage of channel list. m_localFeaturesPtr = (UInt16*)MNewPointer ( (UInt32)gImageWindowInfoPtr->totalNumberChannels * sizeof (UInt16)); m_initializedFlag = (m_localFeaturesPtr != NULL); } // end "if (m_initializedFlag)" if (m_initializedFlag && gListDataSpecsPtr->projectFlag) { // Get memory for the local class list vector. m_classListPtr = (UInt16*)MNewPointer ( (UInt32)gProjectInfoPtr->numberStatisticsClasses * sizeof (UInt16)); m_initializedFlag = (m_classListPtr != NULL); } // end "if (m_initializedFlag && ...->projectFlag)" m_latLongPossibleFlag = FALSE; } // end "CMListDataDialog" CMListDataDialog::~CMListDataDialog (void) { m_classListPtr = CheckAndDisposePtr (m_classListPtr); m_localFeaturesPtr = CheckAndDisposePtr (m_localFeaturesPtr); } // end "~CMListDataDialog" void CMListDataDialog::CheckClassItems ( Boolean listClassDataFlag) { if (listClassDataFlag) { MShowDialogItem (this, IDC_ClassCombo); MShowDialogItem (this, IDC_IncludeClassField); MShowDialogItem (this, IDC_Training); MShowDialogItem (this, IDC_Test); } // end "if (listClassDataFlag)" else // !listClassDataFlag { MHideDialogItem (this, IDC_ClassCombo); MHideDialogItem (this, IDC_IncludeClassField); MHideDialogItem (this, IDC_Training); MHideDialogItem (this, IDC_Test); } // end "else !listClassDataFlag" } // end "CheckClassItems" void CMListDataDialog::CheckOKButton (void) { if (m_areaFlag || m_classFlag) SetDLogControlHilite (this, IDOK, 0); else // !m_areaFlag && !m_classFlag SetDLogControlHilite (this, IDOK, 255); } // end "CheckOKButton" void CMListDataDialog::DoDataExchange ( CDataExchange* pDX) { CDialog::DoDataExchange (pDX); //{{AFX_DATA_MAP (CMListDataDialog) DDX_Check (pDX, IDC_Area, m_areaFlag); DDX_Check (pDX, IDC_Classes, m_classFlag); DDX_Check (pDX, IDC_DiskFile, m_diskFileFlag); DDX_Check (pDX, IDC_GraphData, m_graphDataFlag); DDX_Check (pDX, IDC_IncludeClassField, m_includeClassFieldFlag); DDX_Check (pDX, IDC_IncludeLineColumn, m_includeLineColumnFlag); DDX_Check (pDX, IDC_IncludeLatitudeLongitude, m_includeLatLongFlag); DDX_Check (pDX, IDC_TextWindow, m_textWindowFlag); DDX_Check (pDX, IDC_Training, m_trainingFlag); DDX_Check (pDX, IDC_Test, m_testFlag); DDX_Text (pDX, IDC_LineEnd, m_LineEnd); DDV_MinMaxLong (pDX, m_LineEnd, 1, m_maxNumberLines); DDX_Text (pDX, IDC_LineInterval, m_LineInterval); DDV_MinMaxLong (pDX, m_LineInterval, 1, m_maxNumberLines); DDX_Text (pDX, IDC_LineStart, m_LineStart); DDV_MinMaxLong (pDX, m_LineStart, 1, m_maxNumberLines); DDX_Text (pDX, IDC_ColumnEnd, m_ColumnEnd); DDV_MinMaxLong (pDX, m_ColumnEnd, 1, m_maxNumberColumns); DDX_Text (pDX, IDC_ColumnInterval, m_ColumnInterval); DDV_MinMaxLong (pDX, m_ColumnInterval, 1, m_maxNumberColumns); DDX_Text (pDX, IDC_ColumnStart, m_ColumnStart); DDV_MinMaxLong (pDX, m_ColumnStart, 1, m_maxNumberColumns); DDX_CBIndex (pDX, IDC_ChannelCombo, m_channelSelection); DDX_CBIndex (pDX, IDC_ClassCombo, m_classSelection); DDX_CBIndex (pDX, IDC_ListChannelsFormatCombo, m_listDataFormatCode); DDX_Text (pDX, IDC_NumberDecimalPlaces, m_numberDecimalPlaces); DDV_MinMaxLong (pDX, m_numberDecimalPlaces, 0, 9); //}}AFX_DATA_MAP // Verify that the line and column values make sense VerifyLineColumnStartEndValues (pDX); } // end "DoDataExchange" //----------------------------------------------------------------------------- // Copyright 1988-2020 Purdue Research Foundation // // Function name: void DoDialog // // Software purpose: The purpose of this routine is to present the list // data specification dialog box to the user and copy the // revised back to the list data specification structure if // the user selected OK. // // Parameters in: None // // Parameters out: None // // Value Returned: None // // Called By: ListDataDialog in SLstData.cpp // // Coded By: Larry L. Biehl Date: 05/28/97 // Revised By: Larry L. Biehl Date: 05/28/97 SInt16 CMListDataDialog::DoDialog (void) { INT_PTR returnCode; Boolean continueFlag = FALSE; // Make sure intialization has been completed. if (!m_initializedFlag) return (FALSE); returnCode = DoModal (); if (returnCode == IDOK) { DialogSelectArea dialogSelectArea; continueFlag = TRUE; dialogSelectArea.lineStart = m_LineStart; dialogSelectArea.lineEnd = m_LineEnd; dialogSelectArea.lineInterval = m_LineInterval; dialogSelectArea.columnStart = m_ColumnStart; dialogSelectArea.columnEnd = m_ColumnEnd; dialogSelectArea.columnInterval = m_ColumnInterval; ListDataDialogOK (gListDataSpecsPtr, m_classFlag, m_classSelection, m_localNumberClasses, m_classListPtr, m_areaFlag, &dialogSelectArea, m_channelSelection, m_localActiveNumberFeatures, m_localFeaturesPtr, m_includeLineColumnFlag, m_includeLatLongFlag, m_includeClassFieldFlag, m_textWindowFlag, m_diskFileFlag, m_trainingFlag, m_testFlag, m_graphDataFlag, (UInt16)m_numberDecimalPlaces, m_listDataFormatCode + 1); } // end "if (returnCode == IDOK)" return (continueFlag); } // end "DoDialog" void CMListDataDialog::OnArea () { UInt16 selectItem; DDX_Check (m_dialogFromPtr, IDC_Area, m_areaFlag); if (m_areaFlag) { ShowSomeAreaSelectionItems (); selectItem = IDC_LineStart; } // end "if (m_areaFlag)" else // !m_areaFlag { HideSomeAreaSelectionItems (); selectItem = IDC_LineInterval; } // end "else !m_areaFlag" SelectDialogItemText (this, selectItem, 0, SInt16_MAX); CheckOKButton (); } // end "OnArea" void CMListDataDialog::OnCbnSelendokListchannelsformatcombo () { DDX_CBIndex (m_dialogFromPtr, IDC_ListChannelsFormatCombo, m_listDataFormatCode); if (m_listDataFormatCode == 0 && m_latLongPossibleFlag) MShowDialogItem (this, IDC_IncludeLatitudeLongitude); else // m_listDataFormatCode == 1 || ... MHideDialogItem (this, IDC_IncludeLatitudeLongitude); } // end "OnCbnSelendokListchannelsformatcombo" void CMListDataDialog::OnClasses () { DDX_Check (m_dialogFromPtr, IDC_Classes, m_classFlag); CheckClassItems (m_classFlag); CheckOKButton (); } // end "OnClasses" void CMListDataDialog::OnGraphData () { DDX_Check (m_dialogFromPtr, IDC_GraphData, m_localGraphDataFlag); } // end "OnGraphData" BOOL CMListDataDialog::OnInitDialog () { UInt32 index; UInt16 selectItem; CDialog::OnInitDialog (); // Make sure that we have the bitmaps for the entire image buttons. VERIFY (toEntireButton.AutoLoad (IDEntireImage, this)); VERIFY (toSelectedButton.AutoLoad (IDSelectedImage, this)); // Update the modal dialog with the default settings // Set check box for "Classes". m_classFlag = gListDataSpecsPtr->listClassesDataFlag; if (!gListDataSpecsPtr->projectFlag) MHideDialogItem (this, IDC_Classes); m_classSelection = gListDataSpecsPtr->classSet; m_localNumberClasses = gListDataSpecsPtr->numberClasses; UInt16* classPtr = (UInt16*)GetHandlePointer (gListDataSpecsPtr->classHandle); if (gListDataSpecsPtr->projectFlag) { for (index=0; index<m_localNumberClasses; index++) m_classListPtr[index] = classPtr[index]; } // end "if (gListDataSpecsPtr->projectFlag)" CheckClassItems (gListDataSpecsPtr->listClassesDataFlag); // Selected area for list data // Initialize selected area structure. InitializeDialogSelectArea (&m_dialogSelectArea, gImageWindowInfoPtr, gActiveImageWindow, gListDataSpecsPtr->columnStart, gListDataSpecsPtr->columnEnd, gListDataSpecsPtr->columnInterval, gListDataSpecsPtr->lineStart, gListDataSpecsPtr->lineEnd, gListDataSpecsPtr->lineInterval, 13, 11, kDontAdjustToBaseImage); m_LineStart = gListDataSpecsPtr->lineStart; m_LineEnd = gListDataSpecsPtr->lineEnd; m_LineInterval = gListDataSpecsPtr->lineInterval; m_ColumnStart = gListDataSpecsPtr->columnStart; m_ColumnEnd = gListDataSpecsPtr->columnEnd; m_ColumnInterval = gListDataSpecsPtr->columnInterval; // Set check box for area. m_areaFlag = gListDataSpecsPtr->listSelectedAreaDataFlag; if (gListDataSpecsPtr->listSelectedAreaDataFlag) { ShowSomeAreaSelectionItems (); selectItem = IDC_LineStart; } // end "if (gListDataSpecsPtr->listSelectedAreaDataFlag)" else // !gListDataSpecsPtr->listSelectedAreaDataFlag { HideSomeAreaSelectionItems (); selectItem = IDC_LineInterval; } // end "else !gListDataSpecsPtr->listSelectedAreaDataFlag" // Set the All/Subset channels list item m_channelSelection = gListDataSpecsPtr->channelSet; m_localNumberFeatures = gListDataSpecsPtr->numberChannels; SInt16* channelsPtr = (SInt16*)GetHandlePointer (gListDataSpecsPtr->featureHandle); for (index=0; index<m_localNumberFeatures; index++) m_localFeaturesPtr[index] = channelsPtr[index]; // Set feature parameters m_localActiveNumberFeatures = m_localNumberFeatures; m_localActiveFeaturesPtr = m_localFeaturesPtr; if (gImageFileInfoPtr->thematicType) { MHideDialogItem (this, IDC_ChannelPrompt); MHideDialogItem (this, IDC_ChannelCombo); } // end "if (gImageFileInfoPtr->thematicType)" else // !gImageFileInfoPtr->thematicType { MShowDialogItem (this, IDC_ChannelPrompt); MShowDialogItem (this, IDC_ChannelCombo); } // end "else !gImageFileInfoPtr->thematicType" // Set check box for "Include line and column values". m_includeLineColumnFlag = gListDataSpecsPtr->includeLineColumnValuesFlag; // Set check box for "Include latitude and longitude values". if (DetermineIfLatLongPossible (gListDataSpecsPtr->windowInfoHandle)) { m_latLongPossibleFlag = TRUE; m_includeLatLongFlag = gListDataSpecsPtr->includeLatLongValuesFlag; ShowDialogItem (this, IDC_IncludeLatitudeLongitude); } // end "if (DetermineIfLatLongPossible (...->windowInfoHandle))" else // !DetermineIfLatLongPossible (...->windowInfoHandle) { m_latLongPossibleFlag = FALSE; HideDialogItem (this, IDC_IncludeLatitudeLongitude); } // end "else !DetermineIfLatLongPossible (...->windowInfoHandle))" // Set check box for "Inlude class and field codes". m_includeClassFieldFlag = gListDataSpecsPtr->includeClassFieldFlag; // Set check box for "text output window". if (gListDataSpecsPtr->outputStorageType & 0x0001) m_textWindowFlag = TRUE; // Set check box for "disk file". if (gListDataSpecsPtr->outputStorageType & 0x0002) m_diskFileFlag = TRUE; // Set control for including training fields. if (gListDataSpecsPtr->fieldTypeCode & kTrainingType) m_trainingFlag = TRUE; // Set control for including test fields. if (gListDataSpecsPtr->fieldTypeCode & kTestingType) m_testFlag = TRUE; if (gProjectInfoPtr != NULL && gProjectInfoPtr->numberStatTestFields <= 0) { SetDLogControlHilite (this, IDC_Test, 255); m_testFlag = FALSE; } // end "if (gProjectInfoPtr != NULL && ..." // Set check box for "Graph data values". m_localGraphDataFlag = gListDataSpecsPtr->graphDataFlag; if (gNumberOfGWindows < kMaxNumberGWindows && m_channelSelection == kAllMenuItem) { m_graphDataFlag = gListDataSpecsPtr->graphDataFlag; } // if (gNumberOfGWindows < kMaxNumberGWindows) else // gNumberOfGWindows >= kMaxNumberGWindows SetDLogControlHilite (this, IDC_GraphData, 255); m_listDataFormatCode = gListDataSpecsPtr->outputFormatCode - 1; m_numberDecimalPlaces = gListDataSpecsPtr->numberFDecimalDigits; if (gImageFileInfoPtr->dataTypeCode == kIntegerType) { HideDialogItem (this, IDC_NumberDecimalPlacesPrompt); HideDialogItem (this, IDC_NumberDecimalPlaces); } // end "if (gImageFileInfoPtr->dataTypeCode == kIntegerType)" else // gImageFileInfoPtr->dataTypeCode == kRealType { ShowDialogItem (this, IDC_NumberDecimalPlacesPrompt); ShowDialogItem (this, IDC_NumberDecimalPlaces); } // end "if (gImageFileInfoPtr->dataTypeCode == kIntegerType)" if (UpdateData (FALSE)) PositionDialogWindow (); // Set default text selection to first edit text item SelectDialogItemText (this, selectItem, 0, SInt16_MAX); return FALSE; // return TRUE unless you set the focus to a control } // end "OnInitDialog" void CMListDataDialog::OnSelendokChannelCombo () { HandleChannelsMenu (IDC_ChannelCombo, kNoTransformation, (SInt16)gImageWindowInfoPtr->totalNumberChannels, 1, TRUE); DDX_CBIndex (m_dialogFromPtr, IDC_ChannelCombo, m_channelSelection); if (gNumberOfGWindows < kMaxNumberGWindows && m_channelSelection == kAllMenuItem) { DDX_Check (m_dialogToPtr, IDC_GraphData, m_localGraphDataFlag); SetDLogControlHilite (this, IDC_GraphData, 0); } // end "if (m_channelSelection == kAllMenuItem)" else // m_channelSelection == kSubsetMenuItem { BOOL localGraphDataFlag = FALSE; DDX_Check (m_dialogToPtr, IDC_GraphData, localGraphDataFlag); SetDLogControlHilite (this, IDC_GraphData, 255); } // end "else m_channelSelection == kSubsetMenuItem" } // end "OnSelendokChannelCombo" void CMListDataDialog::OnSelendokClassCombo () { HandleClassesMenu (&m_localNumberClasses, (SInt16*)m_classListPtr, 1, (SInt16)gProjectInfoPtr->numberStatisticsClasses, IDC_ClassCombo, &m_classSelection); } // end "OnSelendokClassCombo"
30.667221
120
0.648473
[ "vector" ]
f78f9214f59f749dd8b17a33972e21b1d045d64a
1,747
cpp
C++
tc 160+/HandsShaking.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/HandsShaking.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/HandsShaking.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> #include <cstring> using namespace std; long long dp[51]; long long go(int n) { if (n == 0) return 1; if (dp[n] != -1) return dp[n]; dp[n] = 0; for (int i=1; i<n; ++i) dp[n] += go(i-1)*go(n-1-i); return dp[n]; } class HandsShaking { public: long long countPerfect(int n) { memset(dp, 0xff, sizeof dp); return go(n); } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const long long &Expected, const long long &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 2; long long Arg1 = 1LL; verify_case(0, Arg1, countPerfect(Arg0)); } void test_case_1() { int Arg0 = 4; long long Arg1 = 2LL; verify_case(1, Arg1, countPerfect(Arg0)); } void test_case_2() { int Arg0 = 8; long long Arg1 = 14LL; verify_case(2, Arg1, countPerfect(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { HandsShaking ___test; ___test.run_test(-1); } // END CUT HERE
29.116667
321
0.576989
[ "vector" ]
f7903f1e0e8432587227c498be596950bb408386
32,245
cpp
C++
Final_Project/EyeGazeTrackingSystem_speedUp_vf/EyeGazeTrackingSystem_speedUp_vf/MappingFunction.cpp
Coslate/Parallel_Programming
0b76be74426d25f9bd020f65d2051cf43bea7f40
[ "MIT" ]
null
null
null
Final_Project/EyeGazeTrackingSystem_speedUp_vf/EyeGazeTrackingSystem_speedUp_vf/MappingFunction.cpp
Coslate/Parallel_Programming
0b76be74426d25f9bd020f65d2051cf43bea7f40
[ "MIT" ]
null
null
null
Final_Project/EyeGazeTrackingSystem_speedUp_vf/EyeGazeTrackingSystem_speedUp_vf/MappingFunction.cpp
Coslate/Parallel_Programming
0b76be74426d25f9bd020f65d2051cf43bea7f40
[ "MIT" ]
null
null
null
#include "MappingFunction.h" inline Point2d* normalize_edge_pointSet(double &dis_scale, Point2d &nor_center, const int &ep_num , const vector<Point> &feature_point) { const float sqrt_2 = 1.414213; double sumx = 0, sumy = 0; double sumdis = 0; Point edge; Point original(0, 0); //#pragma omp parallel for for (int i = 0; i < ep_num; ++i){ edge = feature_point.at(i); sumx += edge.x; sumy += edge.y; sumdis += sqrtf((float)(edge.x*edge.x + edge.y*edge.y)); //sumdis+=DistanceCaculate(edge, original); } dis_scale = sqrt_2*ep_num/sumdis; nor_center.x = sumx*1.0/ep_num; nor_center.y = sumy*1.0/ep_num; Point2d *edge_point_nor = new Point2d[ep_num]; for (int i = 0; i < ep_num; ++i){ edge = feature_point.at(i); edge_point_nor[i].x = ((float)edge.x - nor_center.x)*dis_scale; edge_point_nor[i].y = ((float)edge.y - nor_center.y)*dis_scale; } return edge_point_nor; } inline Point2d* normalize_edge_pointSetRevise(double &dis_scale, Point2d &nor_center, const int &ep_num , const vector<Point> &feature_point) { const float sqrt_2 = 1.414213; double sumx = 0, sumy = 0; double sumdis = 0; Point edge; Point original(0, 0); //#pragma omp parallel for for (int i = 0; i < ep_num; ++i){ sumx += feature_point[i].x; sumy += feature_point[i].y; //sumdis += sqrtf((float)(edge.x*edge.x + edge.y*edge.y)); //sumdis+=DistanceCaculate(edge, original); } nor_center.x = sumx/(double)ep_num; nor_center.y = sumy/(double)ep_num; Point2d *edge_point_nor = new Point2d[ep_num]; for (int i = 0; i < ep_num; ++i){ edge_point_nor[i].x = ((double)feature_point[i].x - nor_center.x); edge_point_nor[i].y = ((double)feature_point[i].y - nor_center.y); sumdis += sqrtf((double)(edge_point_nor[i].x*edge_point_nor[i].x + edge_point_nor[i].y*edge_point_nor[i].y)); } dis_scale = sqrt_2*ep_num/sumdis; for(int i=0;i<ep_num;++i){ edge_point_nor[i].x = ((double)feature_point[i].x - nor_center.x)*dis_scale; edge_point_nor[i].y = ((double)feature_point[i].y - nor_center.y)*dis_scale; } return edge_point_nor; } inline bool MappingEyeToGaze_X(double* &mapping_paramX , const int &numberOfVar , const int &n_order , const vector<Point> &scenePoints_Set_in , const vector<Point> &eyePoints_Set_in , const Point2d * const eye_nor , const Point2d* const scene_nor , Mat &A_CoeffMatrix) { mapping_paramX = new double [numberOfVar](); if(scenePoints_Set_in.empty() || eyePoints_Set_in.empty()){ printf("There is no calibration points in MappingEyeToGaze_X()!\n"); return false; }else if(scenePoints_Set_in.size()<numberOfVar || eyePoints_Set_in.size()<numberOfVar){ printf("There is no enough calibration points in MappingEyeToGaze_X()!\n"); return false; } //Matrix Construction [A][Coeff] = [0] int M = numberOfVar; int N = numberOfVar; A_CoeffMatrix = Mat::zeros(M , N , CV_64F); Mat sceneMatrix(M , 1 , CV_64F); Mat W , U , Vt; Mat Ut , V , W_inv; Mat result; SVD svd_opencv; for(int i=0;i<A_CoeffMatrix.rows;++i){ A_CoeffMatrix.at<double>(i , A_CoeffMatrix.cols-1) = 1; } for (int i=0; i<A_CoeffMatrix.rows; ++i){ int pos_horiz = 0; for(int p=1;p<n_order+1;++p){ for(int k=0;k<p+1;++k){ A_CoeffMatrix.at<double>(i , pos_horiz) = powf(eye_nor[i].x , p-k)*powf(eye_nor[i].y , k); ++pos_horiz; } } } for(int i=0;i<sceneMatrix.rows;++i){ sceneMatrix.at<double>(i , 0) = scene_nor[i].x; } //SVD svd_opencv.compute(A_CoeffMatrix, W , U, Vt, SVD::FULL_UV); //Caculate result = V*W_inv*Ut*sceneMatrix Mat wMat = Mat::zeros(M, N , CV_64F); for(int i=0;i<M;++i){ for(int j=0;j<N;++j){ if(i==j){ wMat.at<double>(i , j) = W.at<double>(i); } } } W_inv = wMat.inv(); transpose(U , Ut); transpose(Vt , V); result = V*W_inv*Ut*sceneMatrix; for(int i=0;i<numberOfVar;++i){ mapping_paramX[i] = result.at<double>(i , 0); } return true; } inline bool MappingEyeToGaze_Y(double* &mapping_paramY , const int &numberOfVar , const int &n_order , const vector<Point> &scenePoints_Set_in , const vector<Point> &eyePoints_Set_in , const Point2d * const eye_nor , const Point2d* const scene_nor , const Mat &A_CoeffMatrix) { mapping_paramY = new double [numberOfVar](); if(scenePoints_Set_in.empty() || eyePoints_Set_in.empty()){ printf("There is no calibration points in MappingEyeToGaze_Y()!\n"); return false; }else if(scenePoints_Set_in.size()<numberOfVar || eyePoints_Set_in.size()<numberOfVar){ printf("There is no enough calibration points in MappingEyeToGaze_Y()!\n"); return false; } //Matrix Construction [A][Coeff] = [0] int M = numberOfVar; int N = numberOfVar; Mat sceneMatrix(M , 1 , CV_64F); Mat W , U , Vt; Mat Ut , V , W_inv; Mat result; SVD svd_opencv; for(int i=0;i<sceneMatrix.rows;++i){ sceneMatrix.at<double>(i , 0) = scene_nor[i].y; } //SVD svd_opencv.compute(A_CoeffMatrix, W , U, Vt, SVD::FULL_UV); //Caculate result = V*W_inv*Ut*sceneMatrix Mat wMat = Mat::zeros(M, N , CV_64F); for(int i=0;i<M;++i){ for(int j=0;j<N;++j){ if(i==j){ wMat.at<double>(i , j) = W.at<double>(i); } } } W_inv = wMat.inv(); transpose(U , Ut); transpose(Vt , V); result = V*W_inv*Ut*sceneMatrix; for(int i=0;i<numberOfVar;++i){ mapping_paramY[i] = result.at<double>(i , 0); } return true; } inline bool MappingEyeToGaze_X_ALLCaculated(double* &mapping_paramX , const int &numberOfVar , const int &n_order , const vector<Point> &scenePoints_Set_in , const vector<Point> &eyePoints_Set_in , const Point2d * const eye_nor , const Point2d* const scene_nor , Mat &A_CoeffMatrix) { mapping_paramX = new double [numberOfVar](); if(scenePoints_Set_in.empty() || eyePoints_Set_in.empty()){ printf("There is no calibration points in MappingEyeToGaze_X()!\n"); return false; }else if(scenePoints_Set_in.size()<numberOfVar || eyePoints_Set_in.size()<numberOfVar){ printf("There is no enough calibration points in MappingEyeToGaze_X()!\n"); return false; } //Matrix Construction [A][Coeff] = [0] int M = scenePoints_Set_in.size(); int N = numberOfVar; A_CoeffMatrix = Mat::zeros(M , N , CV_64F); Mat sceneMatrix(M , 1 , CV_64F); Mat W , U , Vt; Mat Ut , V , W_inv; Mat result; SVD svd_opencv; for(int i=0;i<A_CoeffMatrix.rows;++i){ A_CoeffMatrix.at<double>(i , A_CoeffMatrix.cols-1) = 1; } for (int i=0; i<A_CoeffMatrix.rows; ++i){ int pos_horiz = 0; for(int p=1;p<n_order+1;++p){ for(int k=0;k<p+1;++k){ A_CoeffMatrix.at<double>(i , pos_horiz) = powf(eye_nor[i].x , p-k)*powf(eye_nor[i].y , k); ++pos_horiz; } } } for(int i=0;i<sceneMatrix.rows;++i){ sceneMatrix.at<double>(i , 0) = scene_nor[i].x; } //SVD svd_opencv.compute(A_CoeffMatrix, W , U, Vt, SVD::FULL_UV); //Caculate result = V*W_inv*Ut*sceneMatrix Mat wMat = Mat::zeros(M, N , CV_64F); for(int i=0;i<M;++i){ for(int j=0;j<N;++j){ if(i==j){ wMat.at<double>(i , j) = W.at<double>(i); } } } W_inv = wMat.inv(DECOMP_SVD); transpose(U , Ut); transpose(Vt , V); result = V*W_inv*Ut*sceneMatrix; for(int i=0;i<numberOfVar;++i){ mapping_paramX[i] = result.at<double>(i , 0); } return true; } inline bool MappingEyeToGaze_Y_ALLCaculated(double* &mapping_paramY , const int &numberOfVar , const int &n_order , const vector<Point> &scenePoints_Set_in , const vector<Point> &eyePoints_Set_in , const Point2d * const eye_nor , const Point2d* const scene_nor , const Mat &A_CoeffMatrix) { mapping_paramY = new double [numberOfVar](); if(scenePoints_Set_in.empty() || eyePoints_Set_in.empty()){ printf("There is no calibration points in MappingEyeToGaze_Y()!\n"); return false; }else if(scenePoints_Set_in.size()<numberOfVar || eyePoints_Set_in.size()<numberOfVar){ printf("There is no enough calibration points in MappingEyeToGaze_Y()!\n"); return false; } //Matrix Construction [A][Coeff] = [0] int M = scenePoints_Set_in.size(); int N = numberOfVar; Mat sceneMatrix(M , 1 , CV_64F); Mat W , U , Vt; Mat Ut , V , W_inv; Mat result; SVD svd_opencv; for(int i=0;i<sceneMatrix.rows;++i){ sceneMatrix.at<double>(i , 0) = scene_nor[i].y; } //SVD svd_opencv.compute(A_CoeffMatrix, W , U, Vt, SVD::FULL_UV); //Caculate result = V*W_inv*Ut*sceneMatrix Mat wMat = Mat::zeros(M, N , CV_64F); for(int i=0;i<M;++i){ for(int j=0;j<N;++j){ if(i==j){ wMat.at<double>(i , j) = W.at<double>(i); } } } W_inv = wMat.inv(DECOMP_SVD); transpose(U , Ut); transpose(Vt , V); result = V*W_inv*Ut*sceneMatrix; for(int i=0;i<numberOfVar;++i){ mapping_paramY[i] = result.at<double>(i , 0); } return true; } inline bool get_randomPts_Num(const int &max_num , const int &numofPts , int* &rand_num){ int rand_index = 0; int r; bool is_new = 1; rand_num = new int [numofPts](); srand(time(NULL)); if(max_num<numofPts-1){ printf("Doesn't get enough eye-gaze points pairs for calibration precedure.\n"); return false; } if (max_num == numofPts-1) { for (int i = 0; i < numofPts; ++i) { rand_num[i] = i; } return true; } while (rand_index < numofPts){ is_new = true; r = (int)((rand()*1.0/RAND_MAX) * max_num); for (int i = 0; i < rand_index; ++i){ if (r == rand_num[i]) { is_new = false; break; } } if (is_new) { rand_num[rand_index] = r; ++rand_index; } } return true; } inline void EstimateErrorOfModel(const vector<Point> &calibratedEyeRefinedCenter , const vector<Point> &calibratedCalPoints , const Mat &EyePtsTransformMat , const Mat &ScenePtsTransformMat , const double *const mapping_paramX , const double *const mapping_paramY , const int &numberOfVar , const int &n_order , double &meanSquareError) { meanSquareError = 0; for(int i=0;i<calibratedCalPoints.size();++i){ double est_x = 0; double est_y = 0; Mat eyeNormalzed(3 , 1 , CV_64F); Mat eyeOriginal(3 , 1 , CV_64F); Mat SceneNormalized(3 , 1 , CV_64F); Mat SceneDeNormalized(3 , 1 , CV_64F); Mat A_CoeffMatrix(1 , numberOfVar , CV_64F); eyeOriginal.at<double>(0 , 0) = calibratedEyeRefinedCenter[i].x; eyeOriginal.at<double>(1 , 0) = calibratedEyeRefinedCenter[i].y; eyeOriginal.at<double>(2 , 0) = 1; eyeNormalzed = EyePtsTransformMat*eyeOriginal; int pos_horiz = 0; for(int p=1;p<n_order+1;++p){ for(int k=0;k<p+1;++k){ A_CoeffMatrix.at<double>(0 , pos_horiz) = powf(eyeNormalzed.at<double>(0 , 0) , p-k)*powf(eyeNormalzed.at<double>(1 , 0) , k); ++pos_horiz; } } A_CoeffMatrix.at<double>(0 , numberOfVar - 1) = 1; for(int i=0;i<numberOfVar;++i){ est_x+= mapping_paramX[i]*A_CoeffMatrix.at<double>(0 , i); est_y+= mapping_paramY[i]*A_CoeffMatrix.at<double>(0 , i); } SceneNormalized.at<double>(0 , 0) = est_x; SceneNormalized.at<double>(1 , 0) = est_y; SceneNormalized.at<double>(2 , 0) = 1; SceneDeNormalized = ScenePtsTransformMat.inv()*SceneNormalized; meanSquareError += sqrtf(powf(SceneDeNormalized.at<double>(0 , 0)/SceneDeNormalized.at<double>(2 , 0) - calibratedCalPoints[i].x , 2) + powf(SceneDeNormalized.at<double>(1 , 0)/SceneDeNormalized.at<double>(2 , 0) - calibratedCalPoints[i].y , 2)); } meanSquareError/=calibratedCalPoints.size(); } inline double NumFactorial(const int &n){ double sum = 1; if(n==0 || n==1){ sum = 1; }else{ for(int i=n;i>0;--i){ sum*=i; } } return sum; } bool MappingEyeGaze_PolyNomialRANSAC(const std::vector<Point> &calibratedEyeRefinedCenter , const std::vector<Point> &calibratedCalPoints , double* &mapping_paramOptX , double* &mapping_paramOptY , const int &mappingOrder , int &numberOfVar , Mat &EyePtsTransformMat_Opt , Mat &ScenePtsTransformMat_Opt) { EyePtsTransformMat_Opt = Mat::zeros(3 , 3 , CV_64F); ScenePtsTransformMat_Opt = Mat::zeros(3 , 3 , CV_64F); int numOfAllCalPts = calibratedCalPoints.size(); double minError = DBL_MAX; int countRANSAC_times = 0; bool mappingDone = true; bool mappingX = false; bool mappingY = false; numberOfVar = (mappingOrder+3)*mappingOrder/2+1; int sample_num = NumFactorial(calibratedCalPoints.size())/(NumFactorial(numberOfVar)*NumFactorial(calibratedCalPoints.size() - numberOfVar)); mapping_paramOptX = new double [numberOfVar](); mapping_paramOptY = new double [numberOfVar](); while(countRANSAC_times<sample_num){ int *rand_num; Point2d scene_center, eye_center, *eye_nor, *scene_nor; double dis_scale_scene, dis_scale_eye; double *mapping_paramX; double *mapping_paramY; double meanSquareError; std::vector<Point> scenePoints_Set_in; std::vector<Point> eyePoints_Set_in; Mat A_CoeffMatrix; Mat EyePtsTransformMat = Mat::zeros(3 , 3 , CV_64F); Mat ScenePtsTransformMat = Mat::zeros(3 , 3 , CV_64F); //Get random numberOfVar pts if(!get_randomPts_Num(numOfAllCalPts - 1 , numberOfVar , rand_num)){ mappingDone = false; break; } //Normalize for(int i=0;i<numberOfVar;++i){ scenePoints_Set_in.push_back(calibratedCalPoints[rand_num[i]]); eyePoints_Set_in.push_back(calibratedEyeRefinedCenter[rand_num[i]]); } scene_nor = normalize_edge_pointSet(dis_scale_scene, scene_center, numberOfVar , scenePoints_Set_in); eye_nor = normalize_edge_pointSet(dis_scale_eye, eye_center, numberOfVar , eyePoints_Set_in); //Forming transform matrix EyePtsTransformMat.at<double>(0 , 0) = dis_scale_eye; EyePtsTransformMat.at<double>(1 , 1) = dis_scale_eye; EyePtsTransformMat.at<double>(0 , 2) = -dis_scale_eye*eye_center.x; EyePtsTransformMat.at<double>(1 , 2) = -dis_scale_eye*eye_center.y; EyePtsTransformMat.at<double>(2 , 2) = 1; ScenePtsTransformMat.at<double>(0 , 0) = dis_scale_scene; ScenePtsTransformMat.at<double>(1 , 1) = dis_scale_scene; ScenePtsTransformMat.at<double>(0 , 2) = -dis_scale_scene*scene_center.x; ScenePtsTransformMat.at<double>(1 , 2) = -dis_scale_scene*scene_center.y; ScenePtsTransformMat.at<double>(2 , 2) = 1; //Caculate mapping function mappingX = MappingEyeToGaze_X(mapping_paramX , numberOfVar , mappingOrder , scenePoints_Set_in , eyePoints_Set_in , eye_nor , scene_nor , A_CoeffMatrix); mappingY = MappingEyeToGaze_Y(mapping_paramY , numberOfVar , mappingOrder , scenePoints_Set_in , eyePoints_Set_in , eye_nor , scene_nor , A_CoeffMatrix); if(!(mappingX&mappingY)){ mappingDone = false; break; } //Estimate error of the model EstimateErrorOfModel(calibratedEyeRefinedCenter , calibratedCalPoints , EyePtsTransformMat , ScenePtsTransformMat , mapping_paramX , mapping_paramY , numberOfVar , mappingOrder , meanSquareError); if(meanSquareError<minError){ minError = meanSquareError; for(int i=0;i<numberOfVar;++i){ mapping_paramOptX[i] = mapping_paramX[i]; mapping_paramOptY[i] = mapping_paramY[i]; } EyePtsTransformMat_Opt = EyePtsTransformMat.clone(); ScenePtsTransformMat_Opt = ScenePtsTransformMat.clone(); } ++countRANSAC_times; if(countRANSAC_times>3000)break; }//end while if(mappingDone){ cout<<"minError = "<<minError<<endl; } return mappingDone; } bool MappingEyeGaze_PolyNomialALLPtsCaculated(const std::vector<Point> &calibratedEyeRefinedCenter , const std::vector<Point> &calibratedCalPoints , double* &mapping_paramOptX , double* &mapping_paramOptY , const int &mappingOrder , int &numberOfVar , Mat &EyePtsTransformMat_Opt , Mat &ScenePtsTransformMat_Opt , double &meanSquareError) { EyePtsTransformMat_Opt = Mat::zeros(3 , 3 , CV_64F); ScenePtsTransformMat_Opt = Mat::zeros(3 , 3 , CV_64F); int numOfAllCalPts = calibratedCalPoints.size(); bool mappingDone = true; bool mappingX = false; bool mappingY = false; Point2d scene_center, eye_center, *eye_nor, *scene_nor; double dis_scale_scene, dis_scale_eye; std::vector<Point> scenePoints_Set_in; std::vector<Point> eyePoints_Set_in; Mat A_CoeffMatrix; numberOfVar = (mappingOrder+3)*mappingOrder/2+1; //Normalize for(int i=0;i<calibratedCalPoints.size();++i){ scenePoints_Set_in.push_back(calibratedCalPoints[i]); eyePoints_Set_in.push_back(calibratedEyeRefinedCenter[i]); } scene_nor = normalize_edge_pointSet(dis_scale_scene, scene_center, calibratedCalPoints.size(), scenePoints_Set_in); eye_nor = normalize_edge_pointSet(dis_scale_eye, eye_center, calibratedCalPoints.size() , eyePoints_Set_in); //Forming transform matrix EyePtsTransformMat_Opt.at<double>(0 , 0) = dis_scale_eye; EyePtsTransformMat_Opt.at<double>(1 , 1) = dis_scale_eye; EyePtsTransformMat_Opt.at<double>(0 , 2) = -dis_scale_eye*eye_center.x; EyePtsTransformMat_Opt.at<double>(1 , 2) = -dis_scale_eye*eye_center.y; EyePtsTransformMat_Opt.at<double>(2 , 2) = 1; ScenePtsTransformMat_Opt.at<double>(0 , 0) = dis_scale_scene; ScenePtsTransformMat_Opt.at<double>(1 , 1) = dis_scale_scene; ScenePtsTransformMat_Opt.at<double>(0 , 2) = -dis_scale_scene*scene_center.x; ScenePtsTransformMat_Opt.at<double>(1 , 2) = -dis_scale_scene*scene_center.y; ScenePtsTransformMat_Opt.at<double>(2 , 2) = 1; //Caculate mapping function mappingX = MappingEyeToGaze_X_ALLCaculated(mapping_paramOptX , numberOfVar , mappingOrder , scenePoints_Set_in , eyePoints_Set_in , eye_nor , scene_nor , A_CoeffMatrix); mappingY = MappingEyeToGaze_Y_ALLCaculated(mapping_paramOptY , numberOfVar , mappingOrder , scenePoints_Set_in , eyePoints_Set_in , eye_nor , scene_nor , A_CoeffMatrix); if(!(mappingX&mappingY)){ mappingDone = false; } //Estimate error of the model if(mappingDone){ EstimateErrorOfModel(calibratedEyeRefinedCenter , calibratedCalPoints , EyePtsTransformMat_Opt , ScenePtsTransformMat_Opt , mapping_paramOptX , mapping_paramOptY , numberOfVar , mappingOrder , meanSquareError); } return mappingDone; } bool MappingEyeGaze_PolyNomialALLOrderCaculated(const std::vector<Point> &calibratedEyeRefinedCenter , const std::vector<Point> &calibratedCalPoints , double* &mapping_paramOptX , double* &mapping_paramOptY , int &numberOfVarOpt , Mat &EyePtsTransformMat_Opt , Mat &ScenePtsTransformMat_Opt , const int &calPtsLength , int &orderOpt , int &calibrationPts_space) { int numOfCalPts; bool stopInputOrder = false; int orderCount = 0; vector<int> possibleOrder; double minErr = FLT_MAX; vector<double> collectMapping_paramX; vector<double> collectMapping_paramY; if(calibrationPts_space==calibrationPattern::Step_space_two){ if(calPtsLength%2==0){ numOfCalPts = calPtsLength/2*calPtsLength; }else{ int qUse = calPtsLength/2; int rUse = 1; numOfCalPts = calPtsLength*qUse + ceil(calPtsLength/2); } }else{ numOfCalPts = calPtsLength*calPtsLength; } while(!stopInputOrder){ ++orderCount; if((orderCount+3)*orderCount/2 + 1<=numOfCalPts){ possibleOrder.push_back(orderCount); }else{ stopInputOrder = true; } } ofstream fileOut(".//PolyOrder.txt"); for(int i=0;i<possibleOrder.size();++i){ int numberOfVar; Mat EyePtsTransformMat; Mat ScenePtsTransformMat; double meanSquareError; double *mapping_paramX; double *mapping_paramY; fileOut<<"order = "<<possibleOrder[i]<<" : "<<endl; if(MappingEyeGaze_PolyNomialALLPtsCaculated(calibratedEyeRefinedCenter , calibratedCalPoints , mapping_paramX , mapping_paramY , possibleOrder[i] , numberOfVar , EyePtsTransformMat , ScenePtsTransformMat , meanSquareError)) { fileOut<<"numberOfVar = "<<numberOfVar<<endl; fileOut<<endl; fileOut<<"mapping_paramX = "<<endl; for(int j=0;j<numberOfVar;++j){ fileOut<<mapping_paramX[j]<<" "; } fileOut<<endl; fileOut<<"mapping_paramY = "<<endl; for(int j=0;j<numberOfVar;++j){ fileOut<<mapping_paramY[j]<<" "; } fileOut<<endl; fileOut<<"EyePtsTransformMat = "<<endl; for(int j=0;j<EyePtsTransformMat.rows;++j){ for(int k=0;k<EyePtsTransformMat.cols;++k){ fileOut<<EyePtsTransformMat.at<double>(j , k)<<" "; } fileOut<<endl; } fileOut<<endl; fileOut<<"ScenePtsTransformMat = "<<endl; for(int j=0;j<ScenePtsTransformMat.rows;++j){ for(int k=0;k<ScenePtsTransformMat.cols;++k){ fileOut<<ScenePtsTransformMat.at<double>(j , k)<<" "; } fileOut<<endl; } fileOut<<"meanSquareError = "<<meanSquareError<<endl; fileOut<<"================================="<<endl; if(meanSquareError<minErr){ collectMapping_paramX.clear(); collectMapping_paramY.clear(); orderOpt = possibleOrder[i]; numberOfVarOpt = numberOfVar; EyePtsTransformMat_Opt = EyePtsTransformMat.clone(); ScenePtsTransformMat_Opt = ScenePtsTransformMat.clone(); for(int k=0;k<numberOfVarOpt;++k){ collectMapping_paramX.push_back(mapping_paramX[k]); collectMapping_paramY.push_back(mapping_paramY[k]); } } } } mapping_paramOptX = new double[numberOfVarOpt](); mapping_paramOptY = new double[numberOfVarOpt](); for(int i=0;i<numberOfVarOpt;++i){ mapping_paramOptX[i] = collectMapping_paramX[i]; mapping_paramOptY[i] = collectMapping_paramY[i]; } return true; } //bool MappingEyeGaze_SVR(const std::vector<Point> &calibratedEyeRefinedCenter // , const std::vector<Point> &calibratedCalPoints // , dlib::decision_function<kernel_type> &svr_model_X // , dlib::decision_function<kernel_type> &svr_model_Y) //{ // std::vector<sample_type> samples; // std::vector<double> targets_x; // std::vector<double> targets_y; // // //Prepare training set // sample_type m; // for(int i=0;i<calibratedCalPoints.size();++i){ // targets_x.push_back(calibratedCalPoints[i].x); // targets_y.push_back(calibratedCalPoints[i].y); // } // for(int i=0;i<calibratedEyeRefinedCenter.size();++i){ // m(0 , 0) = calibratedEyeRefinedCenter[i].x; // m(1 , 0) = calibratedEyeRefinedCenter[i].y; // samples.push_back(m); // } // // // Now setup a SVR trainer object. It has three parameters, the kernel and // // two parameters specific to SVR. // dlib::svr_trainer<kernel_type> trainer; // trainer.set_kernel(kernel_type(0.01)); // // // This parameter is the usual regularization parameter. It determines the trade-off // // between trying to reduce the training error or allowing more errors but hopefully // // improving the generalization of the resulting function. Larger values encourage exact // // fitting while smaller values of C may encourage better generalization. // trainer.set_c(10); // // // Epsilon-insensitive regression means we do regression but stop trying to fit a data // // point once it is "close enough" to its target value. This parameter is the value that // // controls what we mean by "close enough". In this case, I'm saying I'm happy if the // // resulting regression function gets within 0.001 of the target value. // trainer.set_epsilon_insensitivity(0.001); // // // Now do the training and save the results // svr_model_X = trainer.train(samples, targets_x); // svr_model_Y = trainer.train(samples, targets_y); // // return true; //} bool MappingEyeGaze_HomographySlice(std::vector<sliceMapElement> &mappingSliceMap , const std::vector<Point> &calibratedCalPoints) { bool constructDone = true; for(int i=0;i<mappingSliceMap.size();++i){ if(!mappingSliceMap[i].mappingHomographyConstruction(calibratedCalPoints)){ printf("\nHomography model of %d model in mappingSliceMap failed.\n" , i); return false; } } return constructDone; } //----------------sliceMapElement function implementation-----------------// int sliceMapElement::testOut = 0; inline bool SolveHomography(const Point2d * const scene_nor , const Point2d *const eye_nor , const int &correspPtsNum , const Mat &EyePtsTransformMat_Opt , const Mat &ScenePtsTransformMat_Opt , Mat &Map_Matrix_return) { const int valNum = 8; int M = correspPtsNum*2; int N = valNum; Mat Map_matrix(3 , 3 , CV_64F); Mat A_CoeffMatrix = Mat::zeros(M , N , CV_64F); Mat sceneMatrix(M , 1 , CV_64F); Mat W , U , Vt; Mat Ut , V , W_inv; Mat Result; SVD svd_opencv; if(M<N){ printf("\n Don't have enough correspondence through calibration. \n"); return false; } //Forming A Matrix , Ax = b for(int j = 0; j < correspPtsNum; ++j){ int i = 2 * j; A_CoeffMatrix.at<double>(i, 0) = A_CoeffMatrix.at<double>(i, 1) = A_CoeffMatrix.at<double>(i, 2) = 0.0f; A_CoeffMatrix.at<double>(i, 3) = eye_nor[j].x; A_CoeffMatrix.at<double>(i, 4) = eye_nor[j].y; A_CoeffMatrix.at<double>(i, 5) = 1.0f; A_CoeffMatrix.at<double>(i, 6) = -scene_nor[j].y * eye_nor[j].x; A_CoeffMatrix.at<double>(i, 7) = -scene_nor[j].y * eye_nor[j].y; A_CoeffMatrix.at<double>(i + 1, 0) = eye_nor[j].x; A_CoeffMatrix.at<double>(i + 1, 1) = eye_nor[j].y; A_CoeffMatrix.at<double>(i + 1, 2) = 1; A_CoeffMatrix.at<double>(i + 1, 3) = A_CoeffMatrix.at<double>(i + 1, 4) = A_CoeffMatrix.at<double>(i + 1, 5) = 0.0f; A_CoeffMatrix.at<double>(i + 1, 6) = -scene_nor[j].x * eye_nor[j].x; A_CoeffMatrix.at<double>(i + 1, 7) = -scene_nor[j].x * eye_nor[j].y; sceneMatrix.at<double>(i) = scene_nor[j].y; sceneMatrix.at<double>(i + 1) = scene_nor[j].x; } //SVD svd_opencv.compute(A_CoeffMatrix, W , U, Vt, SVD::FULL_UV); //Caculate result = V*W_inv*Ut*sceneMatrix Mat wMat = Mat::zeros(M, N , CV_64F); for(int i=0;i<M;++i){ for(int j=0;j<N;++j){ if(i==j){ wMat.at<double>(i , j) = W.at<double>(i); } } } W_inv = wMat.inv(DECOMP_SVD); transpose(U , Ut); transpose(Vt , V); Result = V*W_inv*Ut*sceneMatrix; for (int i = 0; i < M; ++i) { Map_matrix.at<double>(i/3 , i%3) = Result.at<double>(i , 0); //the column of v that corresponds to the smallest singular value, //which is the solution of the equations } Map_matrix.at<double>(2 , 2) = 1; //Denormalise Map_Matrix_return = ScenePtsTransformMat_Opt.inv(DECOMP_SVD)*Map_matrix*EyePtsTransformMat_Opt; return true; } bool sliceMapElement::mappingHomographyConstructionSelfDefined(const std::vector<Point> &calibratedCalPoints){ Mat EyePtsTransformMat_Opt = Mat::zeros(3 , 3 , CV_64F); Mat ScenePtsTransformMat_Opt = Mat::zeros(3 , 3 , CV_64F); bool mappingDone = false; Point2d scene_center, eye_center, *eye_nor, *scene_nor; double dis_scale_scene, dis_scale_eye; std::vector<Point> scenePoints_Set_in; std::vector<Point> eyePoints_Set_in; //Normalize scenePoints_Set_in.push_back(calibratedCalPoints[leftAnchorPt.second]); eyePoints_Set_in.push_back(leftAnchorPt.first); scenePoints_Set_in.push_back(calibratedCalPoints[upAnchorPt.second]); eyePoints_Set_in.push_back(upAnchorPt.first); scenePoints_Set_in.push_back(calibratedCalPoints[rightAnchorPt.second]); eyePoints_Set_in.push_back(rightAnchorPt.first); scenePoints_Set_in.push_back(calibratedCalPoints[downAnchorPt.second]); eyePoints_Set_in.push_back(downAnchorPt.first); scene_nor = normalize_edge_pointSet(dis_scale_scene, scene_center, 4 , scenePoints_Set_in); eye_nor = normalize_edge_pointSet(dis_scale_eye, eye_center, 4 , eyePoints_Set_in); //Forming transform matrix EyePtsTransformMat_Opt.at<double>(0 , 0) = dis_scale_eye; EyePtsTransformMat_Opt.at<double>(1 , 1) = dis_scale_eye; EyePtsTransformMat_Opt.at<double>(0 , 2) = -dis_scale_eye*eye_center.x; EyePtsTransformMat_Opt.at<double>(1 , 2) = -dis_scale_eye*eye_center.y; EyePtsTransformMat_Opt.at<double>(2 , 2) = 1; ScenePtsTransformMat_Opt.at<double>(0 , 0) = dis_scale_scene; ScenePtsTransformMat_Opt.at<double>(1 , 1) = dis_scale_scene; ScenePtsTransformMat_Opt.at<double>(0 , 2) = -dis_scale_scene*scene_center.x; ScenePtsTransformMat_Opt.at<double>(1 , 2) = -dis_scale_scene*scene_center.y; ScenePtsTransformMat_Opt.at<double>(2 , 2) = 1; //Solve Homography Mapping mappingDone = SolveHomography(scene_nor , eye_nor , 4 , EyePtsTransformMat_Opt , ScenePtsTransformMat_Opt , HomoTransMatrix); char test_file[MAX_WORD_LEN]; sprintf(test_file , "HomoClass_%d.txt" , testOut); ofstream out_Homo(test_file); out_Homo<<"scenePoints_Set_in = "<<endl; for(int i=0;i<scenePoints_Set_in.size();++i){ out_Homo<<scenePoints_Set_in[i]<<endl; } out_Homo<<"eyePoints_Set_in = "<<endl; for(int i=0;i<eyePoints_Set_in.size();++i){ out_Homo<<eyePoints_Set_in[i]<<endl; } out_Homo<<"scene_nor:"<<endl; for(int i=0;i<4;++i){ out_Homo<<scene_nor[i]<<endl; } out_Homo<<"eye_nor:"<<endl; for(int i=0;i<4;++i){ out_Homo<<eye_nor[i]<<endl; } out_Homo<<"EyePtsTransformMat_Opt = "<<endl<<EyePtsTransformMat_Opt<<endl; out_Homo<<"ScenePtsTransformMat_Opt = "<<endl<<ScenePtsTransformMat_Opt<<endl; out_Homo<<"HomoTransMatrix = "<<endl<<HomoTransMatrix<<endl; ++testOut; return mappingDone; } bool sliceMapElement::mappingHomographyConstruction(const std::vector<Point> &calibratedCalPoints){ std::vector<Point2d> scenePoints_Set_in; std::vector<Point2d> eyePoints_Set_in; scenePoints_Set_in.push_back(calibratedCalPoints[leftAnchorPt.second]); eyePoints_Set_in.push_back(leftAnchorPt.first); scenePoints_Set_in.push_back(calibratedCalPoints[upAnchorPt.second]); eyePoints_Set_in.push_back(upAnchorPt.first); scenePoints_Set_in.push_back(calibratedCalPoints[rightAnchorPt.second]); eyePoints_Set_in.push_back(rightAnchorPt.first); scenePoints_Set_in.push_back(calibratedCalPoints[downAnchorPt.second]); eyePoints_Set_in.push_back(downAnchorPt.first); HomoTransMatrix = findHomography( eyePoints_Set_in, scenePoints_Set_in, RANSAC ); char test_file[MAX_WORD_LEN]; sprintf(test_file , "HomoClass_%d.txt" , testOut); ofstream out_Homo(test_file); out_Homo<<"scenePoints_Set_in = "<<endl; for(int i=0;i<scenePoints_Set_in.size();++i){ out_Homo<<scenePoints_Set_in[i]<<endl; } out_Homo<<"eyePoints_Set_in = "<<endl; for(int i=0;i<eyePoints_Set_in.size();++i){ out_Homo<<eyePoints_Set_in[i]<<endl; } out_Homo<<"HomoTransMatrix = "<<endl<<HomoTransMatrix<<endl; ++testOut; return true; }
33.379917
145
0.650892
[ "object", "vector", "model", "transform" ]
f7903ff34c73c32165bc53e980c11b1e1689238f
3,367
cpp
C++
lib/scudo/scudo_utils.cpp
andestech/riscv-compiler-rt
2409b3d2f11ab6c9f357f7158f217c7e5b4a952f
[ "MIT" ]
4
2017-09-11T16:48:00.000Z
2021-03-21T17:10:27.000Z
lib/scudo/scudo_utils.cpp
andestech/riscv-compiler-rt
2409b3d2f11ab6c9f357f7158f217c7e5b4a952f
[ "MIT" ]
null
null
null
lib/scudo/scudo_utils.cpp
andestech/riscv-compiler-rt
2409b3d2f11ab6c9f357f7158f217c7e5b4a952f
[ "MIT" ]
1
2017-10-05T01:07:38.000Z
2017-10-05T01:07:38.000Z
//===-- scudo_utils.cpp -----------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// Platform specific utility functions. /// //===----------------------------------------------------------------------===// #include "scudo_utils.h" #include <errno.h> #include <fcntl.h> #include <stdarg.h> #include <unistd.h> #if defined(__x86_64__) || defined(__i386__) # include <cpuid.h> #endif #if defined(__arm__) || defined(__aarch64__) # include <sys/auxv.h> #endif // TODO(kostyak): remove __sanitizer *Printf uses in favor for our own less // complicated string formatting code. The following is a // temporary workaround to be able to use __sanitizer::VSNPrintf. namespace __sanitizer { extern int VSNPrintf(char *buff, int buff_length, const char *format, va_list args); } // namespace __sanitizer namespace __scudo { FORMAT(1, 2) void NORETURN dieWithMessage(const char *Format, ...) { // Our messages are tiny, 256 characters is more than enough. char Message[256]; va_list Args; va_start(Args, Format); __sanitizer::VSNPrintf(Message, sizeof(Message), Format, Args); va_end(Args); RawWrite(Message); Die(); } #if defined(__x86_64__) || defined(__i386__) // i386 and x86_64 specific code to detect CRC32 hardware support via CPUID. // CRC32 requires the SSE 4.2 instruction set. typedef struct { u32 Eax; u32 Ebx; u32 Ecx; u32 Edx; } CPUIDRegs; static void getCPUID(CPUIDRegs *Regs, u32 Level) { __get_cpuid(Level, &Regs->Eax, &Regs->Ebx, &Regs->Ecx, &Regs->Edx); } CPUIDRegs getCPUFeatures() { CPUIDRegs VendorRegs = {}; getCPUID(&VendorRegs, 0); bool IsIntel = (VendorRegs.Ebx == signature_INTEL_ebx) && (VendorRegs.Edx == signature_INTEL_edx) && (VendorRegs.Ecx == signature_INTEL_ecx); bool IsAMD = (VendorRegs.Ebx == signature_AMD_ebx) && (VendorRegs.Edx == signature_AMD_edx) && (VendorRegs.Ecx == signature_AMD_ecx); // Default to an empty feature set if not on a supported CPU. CPUIDRegs FeaturesRegs = {}; if (IsIntel || IsAMD) { getCPUID(&FeaturesRegs, 1); } return FeaturesRegs; } #ifndef bit_SSE4_2 # define bit_SSE4_2 bit_SSE42 // clang and gcc have different defines. #endif bool testCPUFeature(CPUFeature Feature) { CPUIDRegs FeaturesRegs = getCPUFeatures(); switch (Feature) { case CRC32CPUFeature: // CRC32 is provided by SSE 4.2. return !!(FeaturesRegs.Ecx & bit_SSE4_2); default: break; } return false; } #elif defined(__arm__) || defined(__aarch64__) // For ARM and AArch64, hardware CRC32 support is indicated in the // AT_HWVAL auxiliary vector. #ifndef HWCAP_CRC32 # define HWCAP_CRC32 (1<<7) // HWCAP_CRC32 is missing on older platforms. #endif bool testCPUFeature(CPUFeature Feature) { uptr HWCap = getauxval(AT_HWCAP); switch (Feature) { case CRC32CPUFeature: return !!(HWCap & HWCAP_CRC32); default: break; } return false; } #else bool testCPUFeature(CPUFeature Feature) { return false; } #endif // defined(__x86_64__) || defined(__i386__) } // namespace __scudo
26.511811
80
0.644194
[ "vector" ]
f799ada2adfc246fbfcba405c4ba8d81843d5a4d
10,775
cpp
C++
src/sysCommonU/mapCode.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
33
2021-12-08T11:10:59.000Z
2022-03-26T19:59:37.000Z
src/sysCommonU/mapCode.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
6
2021-12-22T17:54:31.000Z
2022-01-07T21:43:18.000Z
src/sysCommonU/mapCode.cpp
projectPiki/pikmin2
a431d992acde856d092889a515ecca0e07a3ea7c
[ "Unlicense" ]
2
2022-01-04T06:00:49.000Z
2022-01-26T07:27:28.000Z
#include "types.h" #include "mapCode.h" #include "Sys/TriangleTable.h" /* Generated from dpostproc .section .rodata # 0x804732E0 - 0x8049E220 .global lbl_804997B8 lbl_804997B8: .asciz "# %d/%d\r\n" .skip 0x6 .section .data, "wa" # 0x8049E220 - 0x804EFC20 .global __vt__Q37MapCode3Mgr9CodeArray __vt__Q37MapCode3Mgr9CodeArray: .4byte 0 .4byte 0 .4byte __dt__Q37MapCode3Mgr9CodeArrayFv .4byte getChildCount__5CNodeFv .4byte "getObject__26Container<Q27MapCode4Code>FPv" .4byte "getNext__31ArrayContainer<Q27MapCode4Code>FPv" .4byte "getStart__31ArrayContainer<Q27MapCode4Code>Fv" .4byte "getEnd__31ArrayContainer<Q27MapCode4Code>Fv" .4byte "get__31ArrayContainer<Q27MapCode4Code>FPv" .4byte "getAt__31ArrayContainer<Q27MapCode4Code>Fi" .4byte "getTo__31ArrayContainer<Q27MapCode4Code>Fv" .4byte writeObject__Q37MapCode3Mgr9CodeArrayFR6StreamRQ27MapCode4Code .4byte readObject__Q37MapCode3Mgr9CodeArrayFR6StreamRQ27MapCode4Code .4byte "write__31ArrayContainer<Q27MapCode4Code>FR6Stream" .4byte "read__31ArrayContainer<Q27MapCode4Code>FR6Stream" .4byte "alloc__31ArrayContainer<Q27MapCode4Code>Fi" .4byte "addOne__31ArrayContainer<Q27MapCode4Code>FRQ27MapCode4Code" .4byte "setArray__31ArrayContainer<Q27MapCode4Code>FPQ27MapCode4Codei" .global "__vt__31ArrayContainer<Q27MapCode4Code>" "__vt__31ArrayContainer<Q27MapCode4Code>": .4byte 0 .4byte 0 .4byte "__dt__31ArrayContainer<Q27MapCode4Code>Fv" .4byte getChildCount__5CNodeFv .4byte "getObject__26Container<Q27MapCode4Code>FPv" .4byte "getNext__31ArrayContainer<Q27MapCode4Code>FPv" .4byte "getStart__31ArrayContainer<Q27MapCode4Code>Fv" .4byte "getEnd__31ArrayContainer<Q27MapCode4Code>Fv" .4byte "get__31ArrayContainer<Q27MapCode4Code>FPv" .4byte "getAt__31ArrayContainer<Q27MapCode4Code>Fi" .4byte "getTo__31ArrayContainer<Q27MapCode4Code>Fv" .4byte "writeObject__31ArrayContainer<Q27MapCode4Code>FR6StreamRQ27MapCode4Code" .4byte "readObject__31ArrayContainer<Q27MapCode4Code>FR6StreamRQ27MapCode4Code" .4byte "write__31ArrayContainer<Q27MapCode4Code>FR6Stream" .4byte "read__31ArrayContainer<Q27MapCode4Code>FR6Stream" .4byte "alloc__31ArrayContainer<Q27MapCode4Code>Fi" .4byte "addOne__31ArrayContainer<Q27MapCode4Code>FRQ27MapCode4Code" .4byte "setArray__31ArrayContainer<Q27MapCode4Code>FPQ27MapCode4Codei" .global "__vt__26Container<Q27MapCode4Code>" "__vt__26Container<Q27MapCode4Code>": .4byte 0 .4byte 0 .4byte "__dt__26Container<Q27MapCode4Code>Fv" .4byte getChildCount__5CNodeFv .4byte "getObject__26Container<Q27MapCode4Code>FPv" .4byte 0 .4byte 0 .4byte 0 .4byte 0 .4byte "getAt__26Container<Q27MapCode4Code>Fi" .4byte "getTo__26Container<Q27MapCode4Code>Fv" .4byte 0 .section .sdata2, "a" # 0x80516360 - 0x80520E40 .global lbl_805203A8 lbl_805203A8: .asciz "\r\n" .skip 0x1 .4byte 0x00000000 */ /* * --INFO-- * Address: 8041C434 * Size: 00000C */ u8 MapCode::Code::getAttribute(void) { // return m_attribute & 0xf; return m_contents & ATTR_MASK; } /* * --INFO-- * Address: ........ * Size: 000018 */ char* MapCode::Code::getAttributeName() { // UNUSED FUNCTION return nullptr; } /* * --INFO-- * Address: 8041C440 * Size: 00000C */ u8 MapCode::Code::getSlipCode() { return m_contents >> 4 & SLIPCODE_MASK; } /* * --INFO-- * Address: ........ * Size: 000018 */ char* MapCode::Code::getSlipCodeName() { // UNUSED FUNCTION return nullptr; } /* * --INFO-- * Address: 8041C44C * Size: 00000C */ bool MapCode::Code::isBald() { return m_contents >> 6 & 1; } /* * --INFO-- * Address: ........ * Size: 00002C */ void MapCode::Code::write(Stream& output) { // UNUSED FUNCTION output.writeByte(m_contents); } /* * --INFO-- * Address: ........ * Size: 000034 */ void MapCode::Code::read(Stream& input) { // UNUSED FUNCTION m_contents = input.readByte(); } /* * --INFO-- * Address: 8041C458 * Size: 000024 */ void MapCode::Code::setCode(int attribute, int slipCode, bool isBald) { m_contents = (attribute & ATTR_MASK) | (u8)(slipCode << 4) | (u8)(isBald << 6); /* .loc_0x0: rlwinm r6,r6,0,24,31 rlwinm r5,r5,4,0,27 neg r0, r6 or r0, r0, r6 rlwimi r5,r4,0,28,31 rlwinm r0,r0,7,25,25 or r0, r5, r0 stb r0, 0x0(r3) blr */ } /* * __ct__Q27MapCode3MgrFv * --INFO-- * Address: 8041C47C * Size: 00007C */ MapCode::Mgr::Mgr() : m_codeArray() { } /** * @generated{__dt__Q37MapCode3Mgr9CodeArrayFv} * @generated{__dt__31ArrayContainer<Q27MapCode4Code>Fv} * @generated{__dt__26Container<Q27MapCode4Code>Fv} */ // /* // * --INFO-- // * Address: 8041C4F8 // * Size: 000090 // */ // MapCode::Mgr::CodeArray::~CodeArray(void) // { // } // /* // * --INFO-- // * Address: 8041C588 // * Size: 000080 // */ // ArrayContainer<MapCode::Code>::~ArrayContainer() // { // } // /* // * --INFO-- // * Address: 8041C608 // * Size: 000070 // */ // Container<MapCode::Code>::~Container() // { // } /* * --INFO-- * Address: ........ * Size: 000094 */ inline MapCode::Mgr::~Mgr(void) { // UNUSED FUNCTION } /* * TODO * * --INFO-- * Address: ........ * Size: 00002C */ void MapCode::Mgr::write(Stream& stream) { // UNUSED FUNCTION m_codeArray.write(stream); } /** * @generated{write__31ArrayContainer<Q27MapCode4Code>FR6Stream} * @generated{writeObject__31ArrayContainer<Q27MapCode4Code>FR6StreamRQ27MapCode4Code} */ /* * --INFO-- * Address: 8041C678 * Size: 0000E4 */ // template <> void ArrayContainer<MapCode::Code>::write(Stream& stream) // { // stream.textBeginGroup(m_name); // stream.addTab(); // stream.writeInt(m_count); // stream.textWriteText("\r\n"); // for (int i = 0; i < m_count; i++) { // stream.addTab(); // writeObject(stream, m_objects[i]); // stream.textWriteText("# %d/%d\r\n", i, m_count); // } // } /* * --INFO-- * Address: 8041C75C * Size: 000004 */ // template <> void ArrayContainer<MapCode::Code>::writeObject(Stream&, MapCode::Code&) { } /* * read__Q27MapCode3MgrFR6Stream * --INFO-- * Address: 8041C760 * Size: 00002C */ void MapCode::Mgr::read(Stream& stream) { m_codeArray.read(stream); } /** * @generated{read__31ArrayContainer<Q27MapCode4Code>FR6Stream} * @generated{readObject__31ArrayContainer<Q27MapCode4Code>FR6StreamRQ27MapCode4Code} * @generated{alloc__31ArrayContainer<Q27MapCode4Code>Fi} */ // /* // * --INFO-- // * Address: 8041C78C // * Size: 0000A0 // */ // template <> void ArrayContainer<MapCode::Code>::read(Stream& stream) // { // m_limit = stream.readInt(); // alloc(m_limit); // m_count = m_limit; // for (int i = 0; i < m_limit; ++i) { // readObject(stream, m_objects[i]); // } // } // /* // * --INFO-- // * Address: 8041C82C // * Size: 000004 // */ // void ArrayContainer<MapCode::Code>::readObject(Stream&, MapCode::Code&) { } // /* // * --INFO-- // * Address: 8041C830 // * Size: 00004C // */ // void ArrayContainer<MapCode::Code>::alloc(int count) // { // m_objects = new MapCode::Code[count]; // m_limit = count; // m_count = 0; // } /* * --INFO-- * Address: 8041C87C * Size: 000044 */ void MapCode::Mgr::attachCodes(Sys::TriangleTable* table) { for (int i = 0; i < m_codeArray.m_limit; i++) { Code obj = m_codeArray.m_objects[i]; table->m_objects[i].m_code = obj; } } /* * writeObject__Q37MapCode3Mgr9CodeArrayFR6StreamRQ27MapCode4Code * --INFO-- * Address: 8041C8C0 * Size: 00002C */ void MapCode::Mgr::CodeArray::writeObject(Stream& output, MapCode::Code& object) { object.write(output); /* .loc_0x0: stwu r1, -0x10(r1) mflr r0 mr r3, r4 stw r0, 0x14(r1) lbz r0, 0x0(r5) mr r4, r0 bl -0x7268 lwz r0, 0x14(r1) mtlr r0 addi r1, r1, 0x10 blr */ } /* * readObject__Q37MapCode3Mgr9CodeArrayFR6StreamRQ27MapCode4Code * --INFO-- * Address: 8041C8EC * Size: 000034 */ void MapCode::Mgr::CodeArray::readObject(Stream& input, MapCode::Code& object) { object.read(input); } /** * @generated{addOne__31ArrayContainer<Q27MapCode4Code>FRQ27MapCode4Code} * @generated{setArray__31ArrayContainer<Q27MapCode4Code>FPQ27MapCode4Codei} * @generated{get__31ArrayContainer<Q27MapCode4Code>FPv} * @generated{getNext__31ArrayContainer<Q27MapCode4Code>FPv} * @generated{getStart__31ArrayContainer<Q27MapCode4Code>Fv} * @generated{getEnd__31ArrayContainer<Q27MapCode4Code>Fv} * @generated{getAt__31ArrayContainer<Q27MapCode4Code>Fi} * @generated{getTo__31ArrayContainer<Q27MapCode4Code>Fv} * @generated{getObject__26Container<Q27MapCode4Code>FPv} * @generated{getAt__26Container<Q27MapCode4Code>Fi} * @generated{getTo__26Container<Q27MapCode4Code>Fv} */ // /* // * --INFO-- // * Address: 8041C920 // * Size: 000028 // */ // template <> void ArrayContainer<MapCode::Code>::addOne(MapCode::Code& object) // { // } // /* // * --INFO-- // * Address: 8041C948 // * Size: 000010 // */ // template <> // void ArrayContainer<MapCode::Code>::setArray(MapCode::Code* objects, int count) // { // } // /* // * --INFO-- // * Address: 8041C958 // * Size: 00000C // */ // template <> MapCode::Code* ArrayContainer<MapCode::Code>::get(void* index) // { // } // /* // * --INFO-- // * Address: 8041C964 // * Size: 000008 // */ // template <> int ArrayContainer<MapCode::Code>::getNext(void* index) // { // } // /* // * --INFO-- // * Address: 8041C96C // * Size: 000008 // */ // template <> u32 ArrayContainer<MapCode::Code>::getStart() { return 0x0; } // /* // * --INFO-- // * Address: 8041C974 // * Size: 000008 // */ // template <> int ArrayContainer<MapCode::Code>::getEnd() // { // } // /* // * --INFO-- // * Address: 8041C97C // * Size: 00000C // */ // template <> MapCode::Code* ArrayContainer<MapCode::Code>::getAt(int index) // { // } // /* // * --INFO-- // * Address: 8041C988 // * Size: 000008 // */ // template <> int ArrayContainer<MapCode::Code>::getTo() // { // } // /* // * --INFO-- // * Address: 8041C990 // * Size: 00002C // */ // template <> MapCode::Code* Container<MapCode::Code>::getObject(void* index) // { // } // /* // * --INFO-- // * Address: 8041C9BC // * Size: 000008 // */ // template <> u32 Container<MapCode::Code>::getAt(int) { return 0x0; } // /* // * --INFO-- // * Address: 8041C9C4 // * Size: 000008 // */ // template <> u32 Container<MapCode::Code>::getTo() { return 0x0; }
22.974414
102
0.643248
[ "object" ]
f79ff1422de2b5e13a6df0646df5d50d7ee3efa1
5,239
cpp
C++
GLFW_gltut/Tut04/Aspect Ratio/AspectRatio.cpp
captainadamo/glfw_gltut
7be37447beaef8f97df748855ea532d014dd05b6
[ "MIT" ]
1
2020-11-09T05:03:38.000Z
2020-11-09T05:03:38.000Z
GLFW_gltut/Tut04/Aspect Ratio/AspectRatio.cpp
captainadamo/glfw_gltut
7be37447beaef8f97df748855ea532d014dd05b6
[ "MIT" ]
null
null
null
GLFW_gltut/Tut04/Aspect Ratio/AspectRatio.cpp
captainadamo/glfw_gltut
7be37447beaef8f97df748855ea532d014dd05b6
[ "MIT" ]
null
null
null
#include "Scene.h" #include "helpers.h" const char *tutorialName = "Tutorial 04 Aspect Ratio"; const float vertexData[] = { 0.25f, 0.25f, -1.25f, 1.0f, 0.25f, -0.25f, -1.25f, 1.0f, -0.25f, 0.25f, -1.25f, 1.0f, 0.25f, -0.25f, -1.25f, 1.0f, -0.25f, -0.25f, -1.25f, 1.0f, -0.25f, 0.25f, -1.25f, 1.0f, 0.25f, 0.25f, -2.75f, 1.0f, -0.25f, 0.25f, -2.75f, 1.0f, 0.25f, -0.25f, -2.75f, 1.0f, 0.25f, -0.25f, -2.75f, 1.0f, -0.25f, 0.25f, -2.75f, 1.0f, -0.25f, -0.25f, -2.75f, 1.0f, -0.25f, 0.25f, -1.25f, 1.0f, -0.25f, -0.25f, -1.25f, 1.0f, -0.25f, -0.25f, -2.75f, 1.0f, -0.25f, 0.25f, -1.25f, 1.0f, -0.25f, -0.25f, -2.75f, 1.0f, -0.25f, 0.25f, -2.75f, 1.0f, 0.25f, 0.25f, -1.25f, 1.0f, 0.25f, -0.25f, -2.75f, 1.0f, 0.25f, -0.25f, -1.25f, 1.0f, 0.25f, 0.25f, -1.25f, 1.0f, 0.25f, 0.25f, -2.75f, 1.0f, 0.25f, -0.25f, -2.75f, 1.0f, 0.25f, 0.25f, -2.75f, 1.0f, 0.25f, 0.25f, -1.25f, 1.0f, -0.25f, 0.25f, -1.25f, 1.0f, 0.25f, 0.25f, -2.75f, 1.0f, -0.25f, 0.25f, -1.25f, 1.0f, -0.25f, 0.25f, -2.75f, 1.0f, 0.25f, -0.25f, -2.75f, 1.0f, -0.25f, -0.25f, -1.25f, 1.0f, 0.25f, -0.25f, -1.25f, 1.0f, 0.25f, -0.25f, -2.75f, 1.0f, -0.25f, -0.25f, -2.75f, 1.0f, -0.25f, -0.25f, -1.25f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.8f, 0.8f, 0.8f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, }; GLuint vertexBufferObject; GLuint offsetUniform; GLuint perspectiveMatrixUnif; float perspectiveMatrix[16]; const float frustumScale = 1.0f; void reshape(GLFWwindow* window, int width, int height) { perspectiveMatrix[0] = frustumScale / (width / float(height)); perspectiveMatrix[5] = frustumScale; glUseProgram(theProgram); glUniformMatrix4fv(perspectiveMatrixUnif, 1, GL_FALSE, perspectiveMatrix); glUseProgram(0); glViewport(0, 0, (GLsizei) width, (GLsizei) height); display(); glfwSwapBuffers(window); } void InitializeVertexBuffer() { glGenBuffers(1, &vertexBufferObject); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); } void InitializeProgram() { std::vector<GLuint> shaderList; shaderList.push_back(LoadShader(GL_VERTEX_SHADER, "MatrixPerspective.vert")); shaderList.push_back(LoadShader(GL_FRAGMENT_SHADER, "StandardColors.frag")); theProgram = CreateProgram(shaderList); offsetUniform = glGetUniformLocation(theProgram, "offset"); perspectiveMatrixUnif = glGetUniformLocation(theProgram, "perspectiveMatrix"); float zNear = 1.0f; float zFar = 3.0f; memset(perspectiveMatrix, 0, sizeof(float) * 16); perspectiveMatrix[0] = frustumScale; perspectiveMatrix[5] = frustumScale; perspectiveMatrix[10] = (zFar + zNear) / (zNear - zFar); perspectiveMatrix[14] = (2 *zFar * zNear) / (zNear - zFar); perspectiveMatrix[11] = -1.0f; glUseProgram(theProgram); glUniformMatrix4fv(perspectiveMatrixUnif, 1, GL_FALSE, perspectiveMatrix); glUseProgram(0); std::for_each(shaderList.begin(), shaderList.end(), glDeleteShader); } void init() { InitializeProgram(); InitializeVertexBuffer(); glGenVertexArrays(1, &vao); glBindVertexArray(vao); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glFrontFace(GL_CW); } void display() { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(theProgram); glUniform2f(offsetUniform, 1.5f, 0.5f); size_t colorData = sizeof(vertexData) / 2; glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, (void*)colorData); glDrawArrays(GL_TRIANGLES, 0, 36); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glUseProgram(0); } void keyStateChanged(int key, int mods) { }
25.556098
82
0.565948
[ "vector" ]
f7a1bee5c381a7cfe884c89e90f5aaecf05face4
1,168
cpp
C++
Online-Judges/CodeForces/1100/158B.Taxi.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
3
2021-06-15T01:19:23.000Z
2022-03-16T18:23:53.000Z
Online-Judges/CodeForces/1100/158B.Taxi.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
null
null
null
Online-Judges/CodeForces/1100/158B.Taxi.cpp
shihab4t/Competitive-Programming
e8eec7d4f7d86bfa1c00b7fbbedfd6a1518f19be
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long int llint; typedef unsigned long long int ullint; typedef short int sint; #define endn "\n" #define umap unordered_map #define uset unordered_set bool cmp(int a, int b) { return a > b; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int n; cin >> n; vector<int> groups; int temp; while (n--){ cin >> temp; groups.push_back(temp); } int ct = 0, i; vector<int> v(5, 0); for (i = 0; i < groups.size(); i++) { if (groups[i] == 4) { v[4]++; } else if (groups[i] == 3) { v[3]++; } else if (groups[i] == 2) { v[2]++; } else { v[1]++; } } ct += v[4]; ct += v[3]; v[1] > v[3] ? v[1] = v[1] - v[3] : v[1] = 0; ct += v[2] / 2; v[2] = v[2] % 2; ct += v[2]; v[1] > (v[2]*2) ? v[1] = v[1] - (v[2]*2) : v[1] = 0; ct += v[1] / 4; v[1] % 4 == 0 ? ct : ct += 1; cout << ct << endn; } // Solved By: shihab4t // Thursday, July 15, 2021 | 12:46:06 PM (+06)
18.25
56
0.439212
[ "vector" ]
f7a3f4cc0dd09346b1a72c5d4528f94708156e66
2,185
cpp
C++
src/utils/mdc_content_provider.cpp
webosce/umediaserver
988605735c1e35937fbfb7ac28422dee678d70d6
[ "Apache-2.0" ]
8
2018-03-17T22:28:05.000Z
2021-11-16T15:29:06.000Z
src/utils/mdc_content_provider.cpp
webosce/umediaserver
988605735c1e35937fbfb7ac28422dee678d70d6
[ "Apache-2.0" ]
1
2021-05-21T22:51:00.000Z
2021-05-21T22:51:00.000Z
src/utils/mdc_content_provider.cpp
webosce/umediaserver
988605735c1e35937fbfb7ac28422dee678d70d6
[ "Apache-2.0" ]
4
2018-03-22T18:48:22.000Z
2021-11-16T15:29:08.000Z
// Copyright (c) 2008-2018 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 // // test client using uMediaServer API // // Listen Only clients may use MediaChangeListener independently // #include <stdexcept> #include <vector> #include <sstream> #include <stdio.h> #include <cassert> #include <string> #include <algorithm> #include <iterator> #include <iostream> #include <iomanip> #include <cstdlib> #include <deque> #include <list> #include <pthread.h> #include "MDCContentProvider.h" #include <boost/lexical_cast.hpp> // for lexical_cast<string>(number) #include <boost/algorithm/string.hpp> using namespace std; using namespace boost; using namespace uMediaServer; // --- // MAIN int main(int argc, char *argv[]) { string cmd; bool exit = false; try { printf("MDCContentProvider : START\n"); if(argc < 2) { printf("ERROR : <media_id> required.\n"); return false; } MDCContentProvider mdccp(argv[1]); while( !exit ) { printf("COMMANDS: contentReady <true/false>\n"); printf("\tenter command : "); getline(cin, cmd); vector<string> args; args.clear(); split(args, cmd, is_any_of(" ")); // boost string algorithm if(args[0] == "contentReady" ) { bool state; args[1] == "false" ? state=false: state=true; mdccp.mediaContentReady(state); printf("command : %s\n",cmd.c_str()); } else if(args[0] == "exit" || args[0] == "quit" || args[0] == "q") { exit = true; } } } catch (std::exception& e) { printf("Exception Received: %s\n", e.what()); } printf("\nMDC Client exiting : '%s'\n",cmd.c_str()); return 0; }
22.295918
75
0.669108
[ "vector" ]
f7a5310ba14ed929e662a0928d9a36355013aa7b
3,954
cpp
C++
src/DslOdeAccumulator.cpp
canammex-tech/deepstream-driver
36e3175aa53ae6d877d9f7e7700cca4d7797a3e7
[ "MIT" ]
1
2020-05-09T16:18:48.000Z
2020-05-09T16:18:48.000Z
src/DslOdeAccumulator.cpp
jlerasmus/deepstream-services-library
36e3175aa53ae6d877d9f7e7700cca4d7797a3e7
[ "MIT" ]
null
null
null
src/DslOdeAccumulator.cpp
jlerasmus/deepstream-services-library
36e3175aa53ae6d877d9f7e7700cca4d7797a3e7
[ "MIT" ]
null
null
null
/* The MIT License Copyright (c) 2022, Prominence AI, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in- all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Dsl.h" #include "DslOdeAccumulator.h" #include "DslOdeAction.h" namespace DSL { OdeAccumulator::OdeAccumulator(const char* name) : OdeBase(name) { LOG_FUNC(); } OdeAccumulator::~OdeAccumulator() { LOG_FUNC(); RemoveAllActions(); } void OdeAccumulator::HandleOccurrences(DSL_BASE_PTR pOdeTrigger, GstBuffer* pBuffer, std::vector<NvDsDisplayMeta*>& displayMetaData, NvDsFrameMeta* pFrameMeta) { for (const auto &imap: m_pOdeActionsIndexed) { DSL_ODE_ACTION_PTR pOdeAction = std::dynamic_pointer_cast<OdeAction>(imap.second); try { pOdeAction->HandleOccurrence(pOdeTrigger, pBuffer, displayMetaData, pFrameMeta, NULL); } catch(...) { LOG_ERROR("ODE Accumulater '" << GetName() << "' => Action '" << pOdeAction->GetName() << "' threw exception"); } } } bool OdeAccumulator::AddAction(DSL_BASE_PTR pChild) { LOG_FUNC(); if (m_pOdeActions.find(pChild->GetName()) != m_pOdeActions.end()) { LOG_ERROR("ODE Action '" << pChild->GetName() << "' is already a child of OdeAccumulator '" << GetName() << "'"); return false; } // increment next index, assign to the Action, and update parent releationship. pChild->SetIndex(++m_nextActionIndex); pChild->AssignParentName(GetName()); // Add the shared pointer to child to both Maps, by name and index m_pOdeActions[pChild->GetName()] = pChild; m_pOdeActionsIndexed[m_nextActionIndex] = pChild; return true; } bool OdeAccumulator::RemoveAction(DSL_BASE_PTR pChild) { LOG_FUNC(); if (m_pOdeActions.find(pChild->GetName()) == m_pOdeActions.end()) { LOG_WARN("'" << pChild->GetName() <<"' is not a child of OdeAccumulator '" << GetName() << "'"); return false; } // Erase the child from both maps m_pOdeActions.erase(pChild->GetName()); m_pOdeActionsIndexed.erase(pChild->GetIndex()); // Clear the parent relationship and index pChild->ClearParentName(); pChild->SetIndex(0); return true; } void OdeAccumulator::RemoveAllActions() { LOG_FUNC(); for (auto &imap: m_pOdeActions) { LOG_DEBUG("Removing Action '" << imap.second->GetName() <<"' from OdeAccumulator '" << GetName() << "'"); imap.second->ClearParentName(); } m_pOdeActions.clear(); m_pOdeActionsIndexed.clear(); } }
31.887097
87
0.612291
[ "vector" ]
f7a744dca2c09b1f9b0d36b0191140d74bfe10f9
4,279
cpp
C++
src/tcp_command_client.cpp
jaehyuck0103/HesaiLidar_General_SDK
6541573ded3ada108bde70bba0bf7f74c6f32900
[ "BSD-2-Clause" ]
null
null
null
src/tcp_command_client.cpp
jaehyuck0103/HesaiLidar_General_SDK
6541573ded3ada108bde70bba0bf7f74c6f32900
[ "BSD-2-Clause" ]
null
null
null
src/tcp_command_client.cpp
jaehyuck0103/HesaiLidar_General_SDK
6541573ded3ada108bde70bba0bf7f74c6f32900
[ "BSD-2-Clause" ]
null
null
null
#include "tcp_command_client.h" #include <asio.hpp> #include <array> #include <iomanip> #include <iostream> namespace TcpCommand { std::pair<PTC_ErrCode, TC_Command> readCommand(asio::ip::tcp::socket &socket) { std::cout << "tcpCommandReadCommand\n"; asio::error_code ec; socket.wait(socket.wait_read); std::array<uint8_t, 2> buffer1; if (int ret = socket.read_some(asio::buffer(buffer1), ec); ret != buffer1.size() || buffer1.at(0) != 0x47 || buffer1.at(1) != 0x74) { std::cout << "Receive feedback failed!!!\n"; return {PTC_ErrCode::TRANSFER_FAILED, {}}; } std::array<uint8_t, 6> buffer2; if (int ret = socket.read_some(asio::buffer(buffer2), ec); ret != buffer2.size()) { std::cout << "Receive feedback failed!!!\n"; return {PTC_ErrCode::TRANSFER_FAILED, {}}; } // Parsing TC_Command feedback; feedback.cmd = buffer2.at(0); feedback.ret_code = buffer2.at(1); if (feedback.ret_code != 0) { std::cout << "Invalid return code\n"; return {PTC_ErrCode::TRANSFER_FAILED, {}}; } uint32_t len_payload = ((buffer2.at(2) & 0xff) << 24) | ((buffer2.at(3) & 0xff) << 16) | ((buffer2.at(4) & 0xff) << 8) | ((buffer2.at(5) & 0xff) << 0); if (len_payload > 0) { feedback.payload.resize(len_payload); int ret = socket.read_some(asio::buffer(feedback.payload), ec); if (ret != static_cast<int>(len_payload)) { std::cout << "Receive payload failed!!!\n"; return {PTC_ErrCode::TRANSFER_FAILED, {}}; } } return {PTC_ErrCode::NO_ERROR, feedback}; } std::vector<uint8_t> buildHeader(const TC_Command &cmd) { std::cout << "TcpCommand_buildHeader\n"; return { 0x47, 0x74, cmd.cmd, cmd.ret_code, static_cast<uint8_t>((cmd.payload.size() >> 24) & 0xff), static_cast<uint8_t>((cmd.payload.size() >> 16) & 0xff), static_cast<uint8_t>((cmd.payload.size() >> 8) & 0xff), static_cast<uint8_t>((cmd.payload.size() >> 0) & 0xff)}; } std::pair<PTC_ErrCode, TC_Command> sendCmd(std::string device_ip, int device_port, const TC_Command &cmd) { std::cout << "tcpCommandClient_SendCmd\n"; asio::error_code ec; asio::io_context context; asio::ip::tcp::endpoint endpoint{ asio::ip::make_address(device_ip, ec), static_cast<uint16_t>(device_port)}; asio::ip::tcp::socket socket{context}; socket.connect(endpoint, ec); if (!socket.is_open()) { return {PTC_ErrCode::CONNECT_SERVER_FAILED, {}}; } // Send Command std::vector<uint8_t> buffer = buildHeader(cmd); socket.write_some(asio::buffer(buffer), ec); if (ec) { std::cout << "Write header error\n"; std::cout << ec.message() << "\n"; return {PTC_ErrCode::TRANSFER_FAILED, {}}; } if (!cmd.payload.empty()) { socket.write_some(asio::buffer(cmd.payload), ec); if (ec) { std::cout << "Write Payload error\n"; std::cout << ec.message() << "\n"; return {PTC_ErrCode::TRANSFER_FAILED, {}}; } } // Receive Feedback auto ret2 = readCommand(socket); return ret2; } std::pair<PTC_ErrCode, TC_Command> setCalibration(std::string device_ip, int device_port, std::vector<uint8_t> payload) { TC_Command cmd; cmd.cmd = static_cast<uint8_t>(PTC_Command::SET_CALIBRATION); cmd.payload = payload; return sendCmd(device_ip, device_port, cmd); } std::pair<PTC_ErrCode, TC_Command> getCalibration(std::string device_ip, int device_port) { TC_Command cmd; cmd.cmd = static_cast<uint8_t>(PTC_Command::GET_CALIBRATION); return sendCmd(device_ip, device_port, cmd); } std::pair<PTC_ErrCode, TC_Command> getLidarCalibration(std::string device_ip, int device_port) { TC_Command cmd; cmd.cmd = static_cast<uint8_t>(PTC_Command::GET_LIDAR_CALIBRATION); return sendCmd(device_ip, device_port, cmd); } std::pair<PTC_ErrCode, TC_Command> resetCalibration(std::string device_ip, int device_port) { TC_Command cmd; cmd.cmd = static_cast<uint8_t>(PTC_Command::RESET_CALIBRATION); return sendCmd(device_ip, device_port, cmd); } } // namespace TcpCommand
30.564286
96
0.628418
[ "vector" ]
f7afb704d4de60797e785564839485eaa804b18d
1,017
cpp
C++
acpp/chp3/v2_student_grade.cpp
Binary-bug/Cplusplus
48e33d1c572062b34ca57fe61a186ef675a9980b
[ "MIT" ]
null
null
null
acpp/chp3/v2_student_grade.cpp
Binary-bug/Cplusplus
48e33d1c572062b34ca57fe61a186ef675a9980b
[ "MIT" ]
null
null
null
acpp/chp3/v2_student_grade.cpp
Binary-bug/Cplusplus
48e33d1c572062b34ca57fe61a186ef675a9980b
[ "MIT" ]
null
null
null
#include<iomanip> #include<ios> #include<iostream> #include<string> #include<algorithm> using namespace std; int main(){ // ask for and read the students name cout << "Please enter your first name"; string name; cin >> name; cout << "Hello, " << name << "!" << endl; // ask for and read the midterma and final grades cout << "Please enter your midterm and finals grades: "; double midterm, finals; cin >> midterm >> finals; //ask for the homework grades cout << "Enter all your homework grades, " "followed by end of file"; double x; vector<double> homework; while(cin>>x) homework.push_back(x); typedef vector<double>::size_type vec_sz; vec_sz size = homework.size(); //corner cases if(size == 0){ cout<< endl << "You must enter your grades. " "Please try again." << endl; return 1; } // sort the vector sort(homework.begin(),homework.end()); vec_sz mid = size / 2; double median; median = size % 2 == 0 ? (homework[mid] + homework[mid-1]) / 2 : homework[mid]; }
18.833333
80
0.653884
[ "vector" ]
f7b16cdfbf18681528968c2f07b6028059e67426
5,087
hpp
C++
electroslag/renderer/pipeline_descriptor.hpp
jwb1/electroslag
a0f81ec6f8f8485c2418193b2e3d3f5347c92df5
[ "Apache-2.0" ]
1
2018-08-19T11:06:17.000Z
2018-08-19T11:06:17.000Z
electroslag/renderer/pipeline_descriptor.hpp
jwb1/electroslag
a0f81ec6f8f8485c2418193b2e3d3f5347c92df5
[ "Apache-2.0" ]
null
null
null
electroslag/renderer/pipeline_descriptor.hpp
jwb1/electroslag
a0f81ec6f8f8485c2418193b2e3d3f5347c92df5
[ "Apache-2.0" ]
null
null
null
// Electroslag Interactive Graphics System // Copyright 2018 Joshua Buckman // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "electroslag/serialize/serializable_object.hpp" #include "electroslag/serialize/archive_interface.hpp" #include "electroslag/serialize/serializable_map.hpp" #include "electroslag/graphics/shader_field.hpp" #include "electroslag/graphics/shader_program_descriptor.hpp" #include "electroslag/graphics/uniform_buffer_descriptor.hpp" #include "electroslag/graphics/texture_descriptor.hpp" #include "electroslag/renderer/renderer_types.hpp" namespace electroslag { namespace renderer { class pipeline_descriptor : public referenced_object , public serialize::serializable_object<pipeline_descriptor> { public: typedef reference<pipeline_descriptor> ref; static ref create() { return (ref(new pipeline_descriptor())); } virtual ~pipeline_descriptor() {} // Implement serializable_object explicit pipeline_descriptor(serialize::archive_reader_interface* ar); virtual void save_to_archive(serialize::archive_writer_interface* ar); pipeline_type get_pipeline_type() const { return (m_pipeline_type); } void set_pipeline_type(pipeline_type type) { ELECTROSLAG_CHECK(type > pipeline_type_unknown && type < pipeline_type_count); m_pipeline_type = type; } graphics::shader_program_descriptor::ref const& get_shader() const { return (m_shader); } graphics::shader_program_descriptor::ref get_shader() { return (m_shader); } void set_shader(graphics::shader_program_descriptor::ref const& s); serialize::serializable_map::ref const& get_ubo_initializer(graphics::uniform_buffer_descriptor::ref const& ubo) const; serialize::serializable_map::ref get_ubo_initializer(graphics::uniform_buffer_descriptor::ref const& ubo); void set_ubo_initializer( graphics::uniform_buffer_descriptor::ref const& ubo, serialize::serializable_map::ref const& initalizer ); bool is_ubo_static_data(graphics::uniform_buffer_descriptor::ref const& ubo) const; void set_ubo_static_data( graphics::uniform_buffer_descriptor::ref const& ubo, bool static_data ); graphics::depth_test_params const* get_depth_test_params() const { return (&m_depth_test); } void set_depth_test_params(graphics::depth_test_params const* depth_test) { m_depth_test.value = depth_test->value; } bool is_semi_transparent() const { return (m_blending.enable); } graphics::blending_params const* get_blending_params() const { return (&m_blending); } void set_blending_params(graphics::blending_params const* blending) { m_blending.value = blending->value; } private: pipeline_descriptor() : m_pipeline_type(pipeline_type_unknown) {} void gather_ubo(graphics::shader_stage_descriptor::ref& stage); pipeline_type m_pipeline_type; graphics::shader_program_descriptor::ref m_shader; struct uniform_block_value { explicit uniform_block_value( graphics::uniform_buffer_descriptor::ref const& new_ubo ) : ubo(new_ubo) , static_data(false) {} graphics::uniform_buffer_descriptor::ref ubo; serialize::serializable_map::ref initializer; bool static_data; }; typedef std::vector<uniform_block_value> ubo_value_vector; ubo_value_vector m_ubo_value_vector; graphics::depth_test_params m_depth_test; graphics::blending_params m_blending; // Disallowed operations: explicit pipeline_descriptor(pipeline_descriptor const&); pipeline_descriptor& operator =(pipeline_descriptor const&); }; } }
35.573427
131
0.619422
[ "vector" ]
fc908463102c271ba26ef3673f6249d5120cfd3a
16,366
cpp
C++
dash_client_lib/source/api/discoverer.cpp
juergh/dash-sdk
16757836f1f96ee3220992f70bffe92c18e08e76
[ "AMDPLPA" ]
13
2015-08-06T14:55:10.000Z
2021-12-26T04:41:54.000Z
dash_client_lib/source/api/discoverer.cpp
juergh/dash-sdk
16757836f1f96ee3220992f70bffe92c18e08e76
[ "AMDPLPA" ]
null
null
null
dash_client_lib/source/api/discoverer.cpp
juergh/dash-sdk
16757836f1f96ee3220992f70bffe92c18e08e76
[ "AMDPLPA" ]
1
2017-06-17T14:15:41.000Z
2017-06-17T14:15:41.000Z
/* * License Agreement * * Copyright (c) 2007, 2008, 2009 Advanced Micro Devices Inc. * * All rights reserved. * * Redistribution and use in any form of this material and any product thereof including * software in source or binary forms, along with any related documentation, with or * without modification ("this material"), is permitted provided that the following * conditions are met: * * + Redistributions of source code of any software must retain the above copyright * notice and all terms of this license as part of the code. * * + Redistributions in binary form of any software must reproduce the above copyright * notice and all terms of this license in any related documentation and/or other * materials. * * + Neither the names nor trademarks of Advanced Micro Devices, Inc. or any copyright * holders or contributors may be used to endorse or promote products derived from * this material without specific prior written permission. * * + Notice about U.S. Government restricted rights: This material is provided with ? * RESTRICTED RIGHTS.? Use, duplication or disclosure by the U.S. Government is subject * to the full extent of restrictions set forth in FAR52.227 and DFARS252.227 et seq., * or any successor or applicable regulations. Use of this material by the U.S. * Government constitutes acknowledgment of the proprietary rights of * Advanced Micro Devices, Inc. and any copyright holders and contributors. * * + In no event shall anyone redistributing or accessing or using this material * commence or participate in any arbitration or legal action relating to this * material against Advanced Micro Devices, Inc. or any copyright holders or contributors. * The foregoing shall survive any expiration or termination of this license or any * agreement or access or use related to this material. * * + ANY BREACH OF ANY TERM OF THIS LICENSE SHALL RESULT IN THE IMMEDIATE REVOCATION * OF ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE THIS MATERIAL. * * THIS MATERIAL IS PROVIDED BY ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" IN ITS CURRENT CONDITION AND WITHOUT ANY REPRESENTATIONS, GUARANTEE, * OR WARRANTY OF ANY KIND OR IN ANY WAY RELATED TO SUPPORT, INDEMNITY, ERROR FREE OR * UNINTERRUPTED OPERATION, OR THAT IT IS FREE FROM DEFECTS OR VIRUSES. ALL OBLIGATIONS * ARE HEREBY DISCLAIMED - WHETHER EXPRESS, IMPLIED, OR STATUTORY - INCLUDING, BUT NOT * LIMITED TO, ANY IMPLIED WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE, ACCURACY, COMPLETENESS, OPERABILITY, QUALITY OF SERVICE, OR NON-INFRINGEMENT. * IN NO EVENT SHALL ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, REVENUE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * OR BASED ON ANY THEORY OF LIABILITY ARISING IN ANY WAY RELATED TO THIS MATERIAL, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE ENTIRE AND AGGREGATE LIABILITY OF ADVANCED * MICRO DEVICES, INC. AND ANY COPYRIGHT HOLDERS AND CONTRIBUTORS SHALL NOT EXCEED TEN DOLLARS * (US $10.00). ANYONE REDISTRIBUTING OR ACCESSING OR USING THIS MATERIAL ACCEPTS THIS * ALLOCATION OF RISK AND AGREES TO RELEASE ADVANCED MICRO DEVICES, INC. AND ANY COPYRIGHT * HOLDERS AND CONTRIBUTORS FROM ANY AND ALL LIABILITIES, OBLIGATIONS, CLAIMS, OR DEMANDS IN * EXCESS OF TEN DOLLARS (US $10.00). THE FOREGOING ARE ESSENTIAL TERMS OF THIS LICENSE AND, * IF ANY OF THESE TERMS ARE CONSTRUED AS UNENFORCEABLE, FAIL IN ESSENTIAL PURPOSE, OR BECOME * VOID OR DETRIMENTAL TO ADVANCED MICRO DEVICES, INC. OR ANY COPYRIGHT HOLDERS OR CONTRIBUTORS * FOR ANY REASON, THEN ALL RIGHTS TO REDISTRIBUTE, ACCESS OR USE THIS MATERIAL SHALL TERMINATE * IMMEDIATELY. MOREOVER, THE FOREGOING SHALL SURVIVE ANY EXPIRATION OR TERMINATION OF THIS * LICENSE OR ANY AGREEMENT OR ACCESS OR USE RELATED TO THIS MATERIAL. * * NOTICE IS HEREBY PROVIDED, AND BY REDISTRIBUTING OR ACCESSING OR USING THIS MATERIAL SUCH NOTICE * IS ACKNOWLEDGED, THAT THIS MATERIAL MAY BE SUBJECT TO RESTRICTIONS UNDER THE LAWS AND REGULATIONS * OF THE UNITED STATES OR OTHER COUNTRIES, WHICH INCLUDE BUT ARE NOT LIMITED TO, U.S. EXPORT * CONTROL LAWS SUCH AS THE EXPORT ADMINISTRATION REGULATIONS AND NATIONAL SECURITY CONTROLS AS * DEFINED THEREUNDER, AS WELL AS STATE DEPARTMENT CONTROLS UNDER THE U.S. MUNITIONS LIST. THIS * MATERIAL MAY NOT BE USED, RELEASED, TRANSFERRED, IMPORTED, EXPORTED AND/OR RE-EXPORTED IN ANY * MANNER PROHIBITED UNDER ANY APPLICABLE LAWS, INCLUDING U.S. EXPORT CONTROL LAWS REGARDING * SPECIFICALLY DESIGNATED PERSONS, COUNTRIES AND NATIONALS OF COUNTRIES SUBJECT TO NATIONAL SECURITY * CONTROLS. MOREOVER, THE FOREGOING SHALL SURVIVE ANY EXPIRATION OR TERMINATION OF ANY LICENSE * OR AGREEMENT OR ACCESS OR USE RELATED TO THIS MATERIAL. * * This license forms the entire agreement regarding the subject matter hereof and supersedes all * proposals and prior discussions and writings between the parties with respect thereto. This * license does not affect any ownership, rights, title, or interest in, or relating to, this * material. No terms of this license can be modified or waived, and no breach of this license * can be excused, unless done so in a writing signed by all affected parties. Each term of this * license is separately enforceable. If any term of this license is determined to be or becomes * unenforceable or illegal, such term shall be reformed to the minimum extent necessary in order * for this license to remain in effect in accordance with its terms as modified by such reformation. * This license shall be governed by and construed in accordance with the laws of the State of * Texas without regard to rules on conflicts of law of any state or jurisdiction or the United * Nations Convention on the International Sale of Goods. All disputes arising out of this license * shall be subject to the jurisdiction of the federal and state courts in Austin, Texas, and all * defenses are hereby waived concerning personal jurisdiction and venue of these courts. */ /** * discoverer.cpp * CIM MAP Discoverer. **/ #include <cstdlib> #include <dsdk/dsdktypes.h> #include <dsdk/discoverer.h> #include <wsman/dashping.h> #include "util.h" using namespace dsdk; CCIMMAP createMAP (const string& host, const string& port, WSMANIdentifyInfo_T* dashinfo) { CCIMMAP cimmap = CCIMMAP (host, port); if (dashinfo->protocolVersion) { cimmap.setProtocolVersion (dashinfo->protocolVersion); free (dashinfo->protocolVersion); } if (dashinfo->productVersion) { cimmap.setProductVersion (dashinfo->productVersion); free (dashinfo->productVersion); } if (dashinfo->productVendor) { cimmap.setProductVendor (dashinfo->productVendor); free (dashinfo->productVendor); } if (dashinfo->dashVersion) { cimmap.setDASHVersion (dashinfo->dashVersion); free (dashinfo->dashVersion); } int i = 0; vector<string> name; while (dashinfo->securityProfileName[i]) { string str = dashinfo->securityProfileName[i]; name.push_back (str); free (dashinfo->securityProfileName[i]); i++; } cimmap.setSecurityProfileName (name); return cimmap; } /* * discoverMAPs */ vector<CCIMMAP> CDiscoverer::discoverMAPs (const string& start_ip, const string& end_ip, const vector <pair <string, string> >& port_httpscheme , u32 timeout) { u32 start_addr; u32 end_addr; WSMANIdentifyInfo_T dashinfo = { 0 }; if (!strToIP (start_ip, &start_addr)) { throw EDSDKError (DSDK_INVALID_IPADDR); } /* check if end ip is specified */ if (end_ip != "") { if (!strToIP (end_ip, &end_addr)) { throw EDSDKError (DSDK_INVALID_IPADDR); } } else { /* set start ip as end ip */ end_addr = start_addr; } start_addr = ntohl (start_addr); end_addr = ntohl (end_addr); if (start_addr > end_addr) { throw EDSDKError (DSDK_INVALID_IPADDR_RANGE); } g_lapi_verbose_level = g_dsdk_verbose_level; u32 ip_addr = start_addr; vector<CCIMMAP> map; while (1) { string ip_addr_str = ipToStr (htonl (ip_addr)); /* if port specified use the port else use standard port */ if (0 != port_httpscheme.size()) { int port_num; for (size_t i = 0; i < port_httpscheme.size (); i++) { WSMANIdentifyInfo_T dashinfo = { 0 }; string port = port_httpscheme[i].first; string http_scheme = port_httpscheme[i].second; /* if http scheme not specified use the default for default port and http for rest */ if (http_scheme == "") { if (port == "664") { http_scheme = "https"; } else { http_scheme = "http"; } } /* sanity check */ if ((http_scheme != "http") && (http_scheme != "https")) { throw EDSDKError (DSDK_INVALID_HTTP_SCHEME, http_scheme); } /* sanity check */ for (size_t i = 0; i < port.size (); i++) { if (!isdigit (port [i])) { throw EDSDKError (DSDK_INVALID_PORT); } } port_num = atoi (port.c_str ()); if (0 == ::dashPing (ip_addr_str.c_str (),NULL,NULL, NULL, http_scheme.c_str (), port_num, timeout, &dashinfo)) { map.push_back (createMAP (ip_addr_str, port, &dashinfo)); } } } else { if (0 == ::dashPing (ip_addr_str.c_str (), NULL,NULL,NULL, "http", 623, timeout, &dashinfo)) { map.push_back (createMAP (ip_addr_str, "623", &dashinfo)); } if (0 == ::dashPing (ip_addr_str.c_str (), NULL,NULL,NULL, "https", 664, timeout, &dashinfo)) { map.push_back (createMAP (ip_addr_str, "664", &dashinfo)); } } if (ip_addr == end_addr) { break; } else { ip_addr = nextIPAddr (ip_addr); } } return map; } /* * discoverMAP */ vector<CCIMMAP> CDiscoverer::discoverMAP (const string& hostname, const string& port, const string& http_scheme, u32 timeout) { vector<CCIMMAP> map; WSMANIdentifyInfo_T dashinfo = { 0 }; g_lapi_verbose_level = g_dsdk_verbose_level; /* if port specified use the port else use standard port */ if (0 != port.size ()) { int port_num; string scheme = http_scheme; /* if http scheme not specified use the default for default port and http for rest */ if (scheme == "") { if (port == "664") { scheme = "https"; } else { scheme = "http"; } } /* sanity check */ if ((scheme != "http") && (scheme != "https")) { throw EDSDKError (DSDK_INVALID_HTTP_SCHEME, http_scheme); } /* sanity check */ for (size_t i = 0; i < port.size (); i++) { if (!isdigit (port [i])) { throw EDSDKError (DSDK_INVALID_PORT); } } port_num = atoi (port.c_str ()); if (0 == ::dashPing (hostname.c_str (), NULL,NULL,NULL, scheme.c_str (), port_num, timeout, &dashinfo)) { map.push_back (createMAP (hostname, port, &dashinfo)); } } else { if (0 == ::dashPing (hostname.c_str (), NULL,NULL,NULL, "http", 623, timeout, &dashinfo)) { map.push_back (createMAP (hostname, "623", &dashinfo)); } if (0 == ::dashPing (hostname.c_str (), NULL,NULL,NULL, "https", 664, timeout, &dashinfo)) { map.push_back (createMAP (hostname, "664", &dashinfo)); } } return map; } /* * discoverMAPs */ vector<CCIMMAP> CDiscoverer::discoverMAPs ( const string& start_ip, const string& end_ip, const string& username, const string& password, const string& auth, const vector <pair <string, string> >& port_httpscheme , u32 timeout) { u32 start_addr; u32 end_addr; WSMANIdentifyInfo_T dashinfo = { 0 }; if (!strToIP (start_ip, &start_addr)) { throw EDSDKError (DSDK_INVALID_IPADDR); } /* check if end ip is specified */ if (end_ip != "") { if (!strToIP (end_ip, &end_addr)) { throw EDSDKError (DSDK_INVALID_IPADDR); } } else { /* set start ip as end ip */ end_addr = start_addr; } start_addr = ntohl (start_addr); end_addr = ntohl (end_addr); if (start_addr > end_addr) { throw EDSDKError (DSDK_INVALID_IPADDR_RANGE); } g_lapi_verbose_level = g_dsdk_verbose_level; u32 ip_addr = start_addr; vector<CCIMMAP> map; while (1) { string ip_addr_str = ipToStr (htonl (ip_addr)); /* if port specified use the port else use standard port */ if (0 != port_httpscheme.size()) { int port_num; for (size_t i = 0; i < port_httpscheme.size (); i++) { WSMANIdentifyInfo_T dashinfo = { 0 }; string port = port_httpscheme[i].first; string http_scheme = port_httpscheme[i].second; /* if http scheme not specified use the default for default port and http for rest */ if (http_scheme == "") { if (port == "664") { http_scheme = "https"; } else { http_scheme = "http"; } } /* sanity check */ if ((http_scheme != "http") && (http_scheme != "https")) { throw EDSDKError (DSDK_INVALID_HTTP_SCHEME, http_scheme); } /* sanity check */ for (size_t i = 0; i < port.size (); i++) { if (!isdigit (port [i])) { throw EDSDKError (DSDK_INVALID_PORT); } } port_num = atoi (port.c_str ()); if (0 == ::dashPing (ip_addr_str.c_str (), (username == "") ? NULL : username.c_str (),(password == "") ? NULL : password.c_str (),auth.c_str(), http_scheme.c_str (), port_num, timeout, &dashinfo)) { map.push_back (createMAP (ip_addr_str, port, &dashinfo)); } } } else { if (0 == ::dashPing (ip_addr_str.c_str (),(username == "") ? NULL : username.c_str (),(password == "") ? NULL : password.c_str (), auth.c_str(), "http", 623, timeout, &dashinfo)) { map.push_back (createMAP (ip_addr_str, "623", &dashinfo)); } if (0 == ::dashPing (ip_addr_str.c_str (), (username == "") ? NULL : username.c_str (),(password == "") ? NULL : password.c_str (),auth.c_str(), "https", 664, timeout, &dashinfo)) { map.push_back (createMAP (ip_addr_str, "664", &dashinfo)); } } if (ip_addr == end_addr) { break; } else { ip_addr = nextIPAddr (ip_addr); } } return map; } /* * discoverMAP */ vector<CCIMMAP> CDiscoverer::discoverMAP (const string& hostname, const string& username, const string& password, const string& auth, const string& port, const string& http_scheme, u32 timeout) { vector<CCIMMAP> map; WSMANIdentifyInfo_T dashinfo = { 0 }; g_lapi_verbose_level = g_dsdk_verbose_level; /* if port specified use the port else use standard port */ if (0 != port.size ()) { int port_num; string scheme = http_scheme; /* if http scheme not specified use the default for default port and http for rest */ if (scheme == "") { if (port == "664") { scheme = "https"; } else { scheme = "http"; } } /* sanity check */ if ((scheme != "http") && (scheme != "https")) { throw EDSDKError (DSDK_INVALID_HTTP_SCHEME, http_scheme); } /* sanity check */ for (size_t i = 0; i < port.size (); i++) { if (!isdigit (port [i])) { throw EDSDKError (DSDK_INVALID_PORT); } } port_num = atoi (port.c_str ()); if (0 == ::dashPing (hostname.c_str (), (username == "") ? NULL : username.c_str (),(password == "") ? NULL : password.c_str (),auth.c_str(), scheme.c_str (), port_num, timeout, &dashinfo)) { map.push_back (createMAP (hostname, port, &dashinfo)); } } else { if (0 == ::dashPing (hostname.c_str (), (username == "") ? NULL : username.c_str (),(password == "") ? NULL : password.c_str (),auth.c_str(), "http", 623, timeout, &dashinfo)) { map.push_back (createMAP (hostname, "623", &dashinfo)); } if (0 == ::dashPing (hostname.c_str (), (username == "") ? NULL : username.c_str (),(password == "") ? NULL : password.c_str (),auth.c_str(), "https", 664, timeout, &dashinfo)) { map.push_back (createMAP (hostname, "664", &dashinfo)); } } return map; }
32.280079
149
0.667298
[ "vector" ]
fc993ca8e93dd6b54f7eaddfb48aad51b1f8a36f
548
cpp
C++
XGF/Src/Core/Actor.cpp
kadds/XGF
610c98a93c0f287546f97efc654b95dc846721ad
[ "MIT" ]
5
2017-11-09T05:02:52.000Z
2020-06-23T09:50:25.000Z
XGF/Src/Core/Actor.cpp
kadds/XGF
610c98a93c0f287546f97efc654b95dc846721ad
[ "MIT" ]
null
null
null
XGF/Src/Core/Actor.cpp
kadds/XGF
610c98a93c0f287546f97efc654b95dc846721ad
[ "MIT" ]
null
null
null
#include "../../Include/Actor.hpp" #include "../../Include/Container.hpp" namespace XGF{ Actor::Actor():mParent(nullptr) { } Actor::Actor(int id):mId(id), mParent(nullptr) { } Actor::~Actor() { } void Actor::_Update(float deltaTime) { Update(deltaTime); } const SM::Matrix & Actor::GetMixMatrix() { bool c = GetShape()->GetTransform().IsChange() || mParent->HasDFlag(); if (c) mMatrix = GetShape()->GetTransform().GetMatrix() * mParent->GetMixMatrix(); return mMatrix; } void Actor::_Render() { Render(); } }
15.222222
78
0.627737
[ "render" ]
fc9c88f4531ec8d50b29fb23d208e3b9d090a652
2,024
hpp
C++
include/aikido/distance/CartesianProductWeighted.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
181
2016-04-22T15:11:23.000Z
2022-03-26T12:51:08.000Z
include/aikido/distance/CartesianProductWeighted.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
514
2016-04-20T04:29:51.000Z
2022-02-10T19:46:21.000Z
include/aikido/distance/CartesianProductWeighted.hpp
personalrobotics/r3
1303e3f3ef99a0c2249abc7415d19113f0026565
[ "BSD-3-Clause" ]
31
2017-03-17T09:53:02.000Z
2022-03-23T10:35:05.000Z
#ifndef AIKIDO_DISTANCE_CARTESIANPRODUCTWEIGHTED_HPP_ #define AIKIDO_DISTANCE_CARTESIANPRODUCTWEIGHTED_HPP_ #include "aikido/distance/DistanceMetric.hpp" #include "aikido/statespace/CartesianProduct.hpp" namespace aikido { namespace distance { /// Implements a distance metric on a CartesianProduct. /// /// This metric computes the weighted sum of distances on the individual /// components of the statespace. class CartesianProductWeighted : public DistanceMetric { public: /// Constructor. /// /// Default the weights applied to each subspace to 1. /// \param _space The state space /// \param _metrics A vector containing one element for every component of the /// CartesianProduct CartesianProductWeighted( std::shared_ptr<const statespace::CartesianProduct> _space, std::vector<DistanceMetricPtr> _metrics); /// Constructor. /// /// CartesianProduct. The first element of every pair in the vector is the /// metric and the second is the weight to be applied to the metric. The /// weights must all be positive. /// \param _space The state space /// \param _metrics A vector containing one element for every component of the CartesianProductWeighted( std::shared_ptr<statespace::CartesianProduct> _space, std::vector<std::pair<DistanceMetricPtr, double>> _metrics); // Documentation inherited statespace::ConstStateSpacePtr getStateSpace() const override; /// Computes distance between two states as the weighted sum of distances /// between their matching subcomponents. /// /// \param _state1 The first state (type CartesianProduct::State) /// \param _state2 The second state (type CartesianProduct::State) double distance( const statespace::StateSpace::State* _state1, const statespace::StateSpace::State* _state2) const override; private: std::shared_ptr<const statespace::CartesianProduct> mStateSpace; std::vector<std::pair<DistanceMetricPtr, double>> mMetrics; }; } // namespace distance } // namespace aikido #endif
34.305085
80
0.75247
[ "vector" ]
fc9dc335bbb8172b9b57d47432d28361eab2e4c0
7,523
cpp
C++
smart_list_example.cpp
randomInteger/CPlusPlus_Smart_Linked_List
5e606b163a50e1f9047733a8a2b7ed6068243cc6
[ "MIT" ]
null
null
null
smart_list_example.cpp
randomInteger/CPlusPlus_Smart_Linked_List
5e606b163a50e1f9047733a8a2b7ed6068243cc6
[ "MIT" ]
null
null
null
smart_list_example.cpp
randomInteger/CPlusPlus_Smart_Linked_List
5e606b163a50e1f9047733a8a2b7ed6068243cc6
[ "MIT" ]
null
null
null
// // smart_list_example.cpp // A test and demo for the SMART_LIST.hpp class implementation. // // Created by Christopher Gleeson on 1/1/16. // Copyright © 2016 Christopher Gleeson. All rights reserved. // #include "SMART_LIST.hpp" int main(int argc, const char * argv[]) { //Create the list object LinkedList<int> myList; //Check the empty list bool isEmpty = myList.checkEmpty(); if(isEmpty) { std::cout << "List, post creation is empty.\n"; }else{ std::cout << "Something went wrong, the new list should start empty!\n"; } //Add the first element if(myList.insertFront(6)) { int count = 0; int *countptr = &count; myList.getCount(countptr); std::cout << "\nList insertion for key of 6 returned success.\n"; std::cout << "\nNumber of elements in the list is: " << *countptr << "\n"; }else{ std::cout << "\nList insertion returned failure!\n"; } //Peek at the first element int value = 0; int *valptr = &value; bool success = myList.peekFront(valptr); if(success) { std::cout << "\nFirst element in the list has value: " << *valptr << "\n"; }else{ std::cout << "\nFailed to peek at the first element in the list!\n"; } //Peek at the last element (same as the first) success = myList.peekRear(valptr); if(success) { std::cout << "\nLast element in the list has value: " << *valptr << "\n"; }else{ std::cout << "\nFailed to peek at the last element in the list!\n"; } //Perform more insertions std::cout << "\nPerforming 11 insertions...\n\n"; myList.insertFront(5); myList.insertFront(4); myList.insertFront(3); myList.insertFront(2); myList.insertFront(1); myList.insertBack(7); myList.insertBack(8); myList.insertBack(9); myList.insertBack(10); myList.insertBack(11); myList.insertBack(12); //Print the list myList.print(); //Print the count of the list, it should be 12 int count = 0; int *countptr = &count; myList.getCount(countptr); std::cout << "Number of elements in the list is: " << *countptr << "\n"; //Remove the front element of the list myList.remFront(valptr); std::cout << "Removed front element with value: " << *valptr << "\n"; //Print the list myList.print(); myList.getCount(countptr); std::cout << "Number of elements in the list is: " << *countptr << "\n"; //Remove the back element of the list myList.remBack(valptr); std::cout << "Removed rear element with value: " << *valptr << "\n"; //Print the list myList.print(); myList.getCount(countptr); std::cout << "Number of elements in the list is: " << *countptr << "\n"; //Peek at the last element success = myList.peekRear(valptr); if(success) { std::cout << "\nLast element in the list has value: " << *valptr << "\n"; }else{ std::cout << "\nFailed to peek at the last element in the list!\n"; } //Empty the list via remFront std::cout << "Beginning looped front removal...\n"; while(!myList.checkEmpty()) { myList.remFront(valptr); std::cout << "Removed front element with value: " << *valptr << "\n"; } //Print the list myList.print(); *countptr = 0; myList.getCount(countptr); std::cout << "Number of elements in the list is: " << *countptr << "\n"; //Peek again at the first element success = myList.peekFront(valptr); if(success) { std::cout << "\nFirst element in the list has value: " << *valptr << "\n"; }else{ std::cout << "\nFailed to peek at the first element in the list!\n"; } //Peek again at the last element success = myList.peekRear(valptr); if(success) { std::cout << "\nLast element in the list has value: " << *valptr << "\n"; }else{ std::cout << "\nFailed to peek at the last element in the list!\n"; } //Perform more insertions std::cout << "\nPerforming 12 insertions...\n\n"; myList.insertFront(6); myList.insertFront(5); myList.insertFront(4); myList.insertFront(3); myList.insertFront(2); myList.insertFront(1); myList.insertBack(7); myList.insertBack(8); myList.insertBack(9); myList.insertBack(10); myList.insertBack(11); myList.insertBack(12); //Print the list myList.print(); myList.getCount(countptr); std::cout << "Number of elements in the list is: " << *countptr << "\n"; //test search bool searchresult = myList.searchByKey(1); std::cout << "\nSearch for key of 1 returned " << searchresult << "\n"; searchresult = myList.searchByKey(11); std::cout << "\nSearch for key of 11 returned " << searchresult << "\n"; searchresult = myList.searchByKey(99); std::cout << "\nSearch for key of 99 returned " << searchresult << "\n"; //test remove key bool remresult = myList.removeKey(8); std::cout << "\nRemoval for key of 8 returned " << remresult << "\n"; myList.print(); myList.getCount(countptr); std::cout << "Number of elements in the list is: " << *countptr << "\n"; remresult = myList.removeKey(1); std::cout << "\nRemoval for key of 1 returned " << remresult << "\n"; myList.print(); myList.getCount(countptr); std::cout << "Number of elements in the list is: " << *countptr << "\n"; remresult = myList.removeKey(12); std::cout << "\nRemoval for key of 12 returned " << remresult << "\n"; myList.print(); myList.getCount(countptr); std::cout << "Number of elements in the list is: " << *countptr << "\n"; //test remove index remresult = myList.removeIndex(3); std::cout << "\nRemoval for index of 3 (value 5) returned " << remresult << "\n"; myList.print(); myList.getCount(countptr); std::cout << "Number of elements in the list is: " << *countptr << "\n"; remresult = myList.removeIndex(0); std::cout << "\nRemoval for index of 0 (value 2) returned " << remresult << "\n"; myList.print(); myList.getCount(countptr); std::cout << "Number of elements in the list is: " << *countptr << "\n"; remresult = myList.removeIndex(6); std::cout << "\nRemoval for index of 6 (value 11) returned " << remresult << "\n"; myList.print(); myList.getCount(countptr); std::cout << "Number of elements in the list is: " << *countptr << "\n"; //Empty the list via remBack std::cout << "\nBeginning looped rear removal...\n"; while(!myList.checkEmpty()) { myList.remBack(valptr); std::cout << "Removed rear element with value: " << *valptr << "\n"; } //Print the list myList.print(); myList.getCount(countptr); std::cout << "Number of elements in the list is: " << *countptr << "\n"; //Peek again at the first element success = myList.peekFront(valptr); if(success) { std::cout << "\nFirst element in the list has value: " << *valptr << "\n"; }else{ std::cout << "\nFailed to peek at the first element in the list!\n"; } //Peek again at the last element success = myList.peekRear(valptr); if(success) { std::cout << "\nLast element in the list has value: " << *valptr << "\n"; }else{ std::cout << "\nFailed to peek at the last element in the list!\n"; } return 0; }
32.287554
86
0.591386
[ "object" ]
fca2757f85bf0973a138c2e5bb48869eb6085c25
7,776
cc
C++
content/renderer/media/crypto/proxy_media_keys.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/media/crypto/proxy_media_keys.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/media/crypto/proxy_media_keys.cc
hefen1/chromium
52f0b6830e000ca7c5e9aa19488af85be792cc88
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-04-04T13:34:56.000Z
2020-11-04T07:17:52.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/media/crypto/proxy_media_keys.h" #include <vector> #include "base/basictypes.h" #include "base/logging.h" #include "base/stl_util.h" #include "content/renderer/media/crypto/renderer_cdm_manager.h" #include "media/base/cdm_key_information.h" #include "media/base/cdm_promise.h" #include "media/base/key_systems.h" namespace content { scoped_ptr<ProxyMediaKeys> ProxyMediaKeys::Create( const std::string& key_system, const GURL& security_origin, RendererCdmManager* manager, const media::SessionMessageCB& session_message_cb, const media::SessionClosedCB& session_closed_cb, const media::SessionErrorCB& session_error_cb, const media::SessionKeysChangeCB& session_keys_change_cb, const media::SessionExpirationUpdateCB& session_expiration_update_cb) { DCHECK(manager); scoped_ptr<ProxyMediaKeys> proxy_media_keys(new ProxyMediaKeys( manager, session_message_cb, session_closed_cb, session_error_cb, session_keys_change_cb, session_expiration_update_cb)); proxy_media_keys->InitializeCdm(key_system, security_origin); return proxy_media_keys.Pass(); } ProxyMediaKeys::~ProxyMediaKeys() { manager_->DestroyCdm(cdm_id_); manager_->UnregisterMediaKeys(cdm_id_); cdm_promise_adapter_.Clear(); } void ProxyMediaKeys::SetServerCertificate( const uint8* certificate_data, int certificate_data_length, scoped_ptr<media::SimpleCdmPromise> promise) { uint32_t promise_id = cdm_promise_adapter_.SavePromise(promise.Pass()); manager_->SetServerCertificate( cdm_id_, promise_id, std::vector<uint8>(certificate_data, certificate_data + certificate_data_length)); } void ProxyMediaKeys::CreateSessionAndGenerateRequest( SessionType session_type, const std::string& init_data_type, const uint8* init_data, int init_data_length, scoped_ptr<media::NewSessionCdmPromise> promise) { if (session_type != media::MediaKeys::TEMPORARY_SESSION) { promise->reject(NOT_SUPPORTED_ERROR, 0, "Only the temporary session type is supported."); return; } // TODO(xhwang): Move these checks up to blink and DCHECK here. // See http://crbug.com/342510 CdmHostMsg_CreateSession_InitDataType create_session_init_data_type; if (init_data_type == "cenc") { create_session_init_data_type = CREATE_SESSION_TYPE_MP4; } else if (init_data_type == "webm") { create_session_init_data_type = CREATE_SESSION_TYPE_WEBM; } else { DLOG(ERROR) << "Unsupported EME CreateSession content type of " << init_data_type; promise->reject( NOT_SUPPORTED_ERROR, 0, "Unsupported EME CreateSession init data type of " + init_data_type); return; } uint32_t promise_id = cdm_promise_adapter_.SavePromise(promise.Pass()); manager_->CreateSessionAndGenerateRequest( cdm_id_, promise_id, create_session_init_data_type, std::vector<uint8>(init_data, init_data + init_data_length)); } void ProxyMediaKeys::LoadSession( SessionType session_type, const std::string& session_id, scoped_ptr<media::NewSessionCdmPromise> promise) { // TODO(xhwang): Check key system and platform support for LoadSession in // blink and add NOTREACHED() here. See http://crbug.com/384152 DLOG(ERROR) << "ProxyMediaKeys doesn't support session loading."; promise->reject(NOT_SUPPORTED_ERROR, 0, "LoadSession() is not supported."); } void ProxyMediaKeys::UpdateSession( const std::string& session_id, const uint8* response, int response_length, scoped_ptr<media::SimpleCdmPromise> promise) { uint32_t promise_id = cdm_promise_adapter_.SavePromise(promise.Pass()); manager_->UpdateSession( cdm_id_, promise_id, session_id, std::vector<uint8>(response, response + response_length)); } void ProxyMediaKeys::CloseSession(const std::string& session_id, scoped_ptr<media::SimpleCdmPromise> promise) { uint32_t promise_id = cdm_promise_adapter_.SavePromise(promise.Pass()); manager_->CloseSession(cdm_id_, promise_id, session_id); } void ProxyMediaKeys::RemoveSession( const std::string& session_id, scoped_ptr<media::SimpleCdmPromise> promise) { // TODO(xhwang): Check key system and platform support for LoadSession in // blink and add NOTREACHED() here. See http://crbug.com/384152 promise->reject(NOT_SUPPORTED_ERROR, 0, "RemoveSession() not supported."); } media::CdmContext* ProxyMediaKeys::GetCdmContext() { return this; } media::Decryptor* ProxyMediaKeys::GetDecryptor() { return NULL; } int ProxyMediaKeys::GetCdmId() const { return cdm_id_; } void ProxyMediaKeys::OnSessionMessage( const std::string& session_id, media::MediaKeys::MessageType message_type, const std::vector<uint8>& message, const GURL& legacy_destination_url) { session_message_cb_.Run(session_id, message_type, message, legacy_destination_url); } void ProxyMediaKeys::OnSessionClosed(const std::string& session_id) { session_closed_cb_.Run(session_id); } void ProxyMediaKeys::OnLegacySessionError(const std::string& session_id, media::MediaKeys::Exception exception, uint32 system_code, const std::string& error_message) { session_error_cb_.Run(session_id, exception, system_code, error_message); } void ProxyMediaKeys::OnSessionKeysChange(const std::string& session_id, bool has_additional_usable_key, media::CdmKeysInfo keys_info) { session_keys_change_cb_.Run(session_id, has_additional_usable_key, keys_info.Pass()); } void ProxyMediaKeys::OnSessionExpirationUpdate( const std::string& session_id, const base::Time& new_expiry_time) { session_expiration_update_cb_.Run(session_id, new_expiry_time); } void ProxyMediaKeys::OnPromiseResolved(uint32_t promise_id) { cdm_promise_adapter_.ResolvePromise(promise_id); } void ProxyMediaKeys::OnPromiseResolvedWithSession( uint32_t promise_id, const std::string& session_id) { cdm_promise_adapter_.ResolvePromise(promise_id, session_id); } void ProxyMediaKeys::OnPromiseRejected(uint32_t promise_id, media::MediaKeys::Exception exception, uint32_t system_code, const std::string& error_message) { cdm_promise_adapter_.RejectPromise(promise_id, exception, system_code, error_message); } ProxyMediaKeys::ProxyMediaKeys( RendererCdmManager* manager, const media::SessionMessageCB& session_message_cb, const media::SessionClosedCB& session_closed_cb, const media::SessionErrorCB& session_error_cb, const media::SessionKeysChangeCB& session_keys_change_cb, const media::SessionExpirationUpdateCB& session_expiration_update_cb) : manager_(manager), session_message_cb_(session_message_cb), session_closed_cb_(session_closed_cb), session_error_cb_(session_error_cb), session_keys_change_cb_(session_keys_change_cb), session_expiration_update_cb_(session_expiration_update_cb) { cdm_id_ = manager->RegisterMediaKeys(this); } void ProxyMediaKeys::InitializeCdm(const std::string& key_system, const GURL& security_origin) { manager_->InitializeCdm(cdm_id_, this, key_system, security_origin); } } // namespace content
37.384615
80
0.719264
[ "vector" ]
fca5d9fed7e5374c6c29d378c536a733a62317eb
1,546
cpp
C++
mdk/src/forces/Tether.cpp
if-pan-zpp/mdk
a66575ae2160b3d8408fe4dceb971706f650bd05
[ "MIT" ]
null
null
null
mdk/src/forces/Tether.cpp
if-pan-zpp/mdk
a66575ae2160b3d8408fe4dceb971706f650bd05
[ "MIT" ]
null
null
null
mdk/src/forces/Tether.cpp
if-pan-zpp/mdk
a66575ae2160b3d8408fe4dceb971706f650bd05
[ "MIT" ]
1
2021-06-19T09:24:34.000Z
2021-06-19T09:24:34.000Z
#include "forces/Tether.hpp" #include "data/Chains.hpp" #include "simul/Simulation.hpp" using namespace mdk; Tether::Tether(bool fromNative) { this->fromNative = fromNative; } void Tether::bind(Simulation &simulation) { Force::bind(simulation); n = state->n; dist0 = Scalars::Constant(n, 3.8 * angstrom); isConnected = Bytes(n, false); auto model = simulation.data<Model>(); for (auto const& chain: model.chains) { for (int i = chain.start; i + 1 < chain.end; ++i) { isConnected[i] = true; } if (fromNative) { auto const& residues = model.residues; for (auto i = chain.start; i + 1 < chain.end; ++i) { if (not residues[i].nat_r || not residues[i+1].nat_r) { throw std::runtime_error("no native position" " - tether's length can't be calculated"); } Vector r1 = *residues[i].nat_r, r2 = *residues[i+1].nat_r; auto r12 = r2 - r1; dist0[i] = r12.norm(); } } } } void Tether::asyncPart(Dynamics &dyn) { #pragma omp for nowait for (int i = 0; i < n - 1; ++i) { if (not isConnected[i]) continue; auto r1 = state->r[i], r2 = state->r[i+1]; auto r12 = r2 - r1; auto r12_norm = r12.norm(); auto dx = r12_norm - dist0[i]; auto r12_unit = r12 / r12_norm; harm.computeF(r12_unit, dx, dyn.V, dyn.F[i], dyn.F[i+1]); } }
30.313725
87
0.518758
[ "vector", "model" ]
fcb031fba6d7b19af6e53fd26b1380daf00ff0b5
5,627
cpp
C++
actions/context.cpp
SGSSGene/qrqma
3bef6ded0d336e0edbacf3852ba80b19a07a4c1b
[ "MIT" ]
null
null
null
actions/context.cpp
SGSSGene/qrqma
3bef6ded0d336e0edbacf3852ba80b19a07a4c1b
[ "MIT" ]
null
null
null
actions/context.cpp
SGSSGene/qrqma
3bef6ded0d336e0edbacf3852ba80b19a07a4c1b
[ "MIT" ]
null
null
null
#include "context.h" #include "types.h" #include "../demangle.h" #include <numeric> namespace { template <class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template <class... Ts> overloaded(Ts...)->overloaded<Ts...>; } // namespace namespace qrqma { namespace actions { Context::Symbol const& Context::operator[](std::string const &name) const { Context const *context{this}; while (context) { auto it = context->symbols.find(name); if (it != context->symbols.end()) { return it->second; } context = context->parent; } throw std::runtime_error("no symbol with name \"" + name + "\" provided!"); } symbol::Symbol const* Context::getSymbol(std::string const &name) const { Context const *context{this}; while (context) { auto it = context->symbols.find(name); if (it != context->symbols.end()) { return &it->second; } context = context->parent; } return nullptr; } Context::SymbolTable const& Context::getSymbolTable() const { return symbols; } void Context::setSymbol(std::string const& name, Symbol symbol) { symbols[name] = std::move(symbol); } Context::Block const& Context::getBlock(std::string const &name) const { Context const *context{this}; while (context) { auto it = context->blocks.find(name); if (it != context->blocks.end()) { return it->second; } context = context->parent; } throw std::runtime_error("no block with name \"" + name + "\" provided!"); } void Context::setBlock(std::string const& name, Block block) { blocks.emplace(name, std::move(block)); } Context::BlockTable Context::popBlockTable() { BlockTable table; std::swap(table, blocks); return table; } std::string Context::operator()() const { std::string s; for (auto const &t : tokens) { s += std::visit(overloaded{ [](StaticText const &t) -> std::string { return t; }, [](Callable const &c) -> std::string { return c(); }}, t); } return s; } void Context::addToken(Token t) { tokens.emplace_back(std::move(t)); } void Context::pushExpression(Expression f) { expression_stack.emplace_back(std::move(f)); } Context::Expression Context::popExpression() { auto e = std::move(expression_stack.back()); expression_stack.pop_back(); return e; } std::vector<Context::Expression> Context::popAllExpressions() { std::vector<Context::Expression> newStack; std::swap(newStack, expression_stack); return newStack; } Context::Context(SymbolTable in_symbols, BlockTable in_blocks) : symbols{std::move(in_symbols)} , blocks{std::move(in_blocks)} {} Context::Context(Context const* c_parent) : parent{c_parent} {} Context& Context::childContext() { return *childContexts.emplace_back(std::make_unique<Context>(this)).get(); } Context::ConverterFunc Context::convert(std::type_info const& from, std::type_info const& to) { if (from == to) { return [](std::any const& a) { return a; }; } if (from == typeid(void)) { // if the type is not known yet return [&to](std::any const& a) { if (a.type() == typeid(void)) { // cannot convert anything during runtime from void throw std::runtime_error("cannot (runtime) convert from void to " + internal::demangle(to)); } return convert(a.type(), to)(a); }; } if (typeid(types::String) == to) { if (typeid(types::Integer) == from) { return [](std::any const& a) { return std::to_string(std::any_cast<types::Integer>(a)); }; } else if (typeid(types::Float) == from) { return [](std::any const& a) { return std::to_string(std::any_cast<types::Float>(a)); }; } else if (typeid(types::Bool) == from) { return [](std::any const& a) { if (std::any_cast<types::Bool>(a)) { return std::string{"True"}; } else { return std::string{"False"}; } }; } else if (typeid(symbol::List) == from) { return [](std::any const& a) { auto const& l = std::any_cast<symbol::List const&>(a); std::string ret = "["; auto to_str = [](std::any const& a) { return std::any_cast<std::string>(convert(a.type(), typeid(std::string))(a)); }; if (not l.empty()) { ret += std::accumulate(std::next(std::begin(l)), std::end(l), to_str(*std::begin(l)), [=](std::string const& l, std::any const& r) { return l + ", " + to_str(r); }); } ret += "]"; return ret; }; } } else if (typeid(types::Bool) == to) { if (typeid(std::string) == from) { return [](std::any const& a) { return not std::any_cast<std::string const&>(a).empty();}; } else if (typeid(types::Integer) == from) { return [](std::any const& a) { return static_cast<types::Bool>(std::any_cast<types::Integer>(a)); }; } else if (typeid(types::Float) == from) { return [](std::any const& a) { return static_cast<types::Bool>(std::any_cast<types::Float>(a)); }; } } throw std::runtime_error("dont know how to create a converter from type " + internal::demangle(from) + " to " + internal::demangle(to)); return [](std::any const& a) { return a; }; } } }
33.295858
152
0.5614
[ "vector" ]
fcb17f93048934317b45e5cb78ccc01c9232401a
1,190
hpp
C++
src/org/apache/poi/sl/draw/DrawSheet.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/sl/draw/DrawSheet.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/sl/draw/DrawSheet.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/sl/draw/DrawSheet.java #pragma once #include <fwd-POI.hpp> #include <java/awt/fwd-POI.hpp> #include <org/apache/poi/sl/draw/fwd-POI.hpp> #include <org/apache/poi/sl/usermodel/fwd-POI.hpp> #include <java/lang/Object.hpp> #include <org/apache/poi/sl/draw/Drawable.hpp> struct default_init_tag; class poi::sl::draw::DrawSheet : public virtual ::java::lang::Object , public virtual Drawable { public: typedef ::java::lang::Object super; public: /* protected */ ::poi::sl::usermodel::Sheet* sheet { }; protected: void ctor(::poi::sl::usermodel::Sheet* sheet); public: void draw(::java::awt::Graphics2D* graphics) override; void applyTransform(::java::awt::Graphics2D* context) override; void drawContent(::java::awt::Graphics2D* context) override; public: /* protected */ virtual bool canDraw(::java::awt::Graphics2D* graphics, ::poi::sl::usermodel::Shape* shape); // Generated public: DrawSheet(::poi::sl::usermodel::Sheet* sheet); protected: DrawSheet(const ::default_init_tag&); public: static ::java::lang::Class *class_(); private: virtual ::java::lang::Class* getClass0(); };
24.285714
96
0.687395
[ "object", "shape" ]
fcc240252bad4e275833186cadf95ebdeec1f8d4
662
hpp
C++
libpiga/include/piga/Renderer.hpp
maximaximal/piga
54530c208e59eaaf8d44c1f8d640f5ec028d4126
[ "Zlib" ]
2
2015-01-07T18:36:39.000Z
2015-01-08T13:54:43.000Z
libpiga/include/piga/Renderer.hpp
maximaximal/piga
54530c208e59eaaf8d44c1f8d640f5ec028d4126
[ "Zlib" ]
null
null
null
libpiga/include/piga/Renderer.hpp
maximaximal/piga
54530c208e59eaaf8d44c1f8d640f5ec028d4126
[ "Zlib" ]
null
null
null
#ifndef LIBPIGA_PIGA_RENDERER_HPP_INCLUDED #define LIBPIGA_PIGA_RENDERER_HPP_INCLUDED struct SDL_Renderer; struct SDL_Window; namespace piga { class Renderer { public: Renderer(SDL_Window *window = nullptr, SDL_Renderer *sdlRenderer = nullptr); virtual ~Renderer(); void render(); void setSDLRenderer(SDL_Renderer *renderer); void setSDLWindow(SDL_Window *window); SDL_Renderer* getSDLRenderer(); SDL_Window* getSDLWindow(); private: SDL_Renderer *m_sdlRenderer = nullptr; SDL_Window *m_sdlWindow = nullptr; }; } #endif
22.827586
88
0.637462
[ "render" ]
fccbf024d12d3ebc8cbbcc6523b7e8c794dcab58
1,307
cpp
C++
neon/Helium/HeliumForWindows/Implementation/ActiveX/PBODAX/CeODAX/CeODAX.cpp
mensfeld/rhodes
2962610a314ed563a0b7c83fcae6136913a1b033
[ "MIT" ]
173
2015-01-02T11:14:08.000Z
2022-03-05T09:54:54.000Z
neon/Helium/HeliumForWindows/Implementation/ActiveX/PBODAX/CeODAX/CeODAX.cpp
mensfeld/rhodes
2962610a314ed563a0b7c83fcae6136913a1b033
[ "MIT" ]
263
2015-01-05T04:35:22.000Z
2021-09-07T06:00:02.000Z
neon/Helium/HeliumForWindows/Implementation/ActiveX/PBODAX/CeODAX/CeODAX.cpp
watusi/rhodes
07161cca58ff6a960bbd1b79b36447b819bfa0eb
[ "MIT" ]
77
2015-01-12T20:57:18.000Z
2022-02-17T15:15:14.000Z
// CeODAX.cpp : Implementation of DLL Exports. #include "stdafx.h" #ifdef POCKETPC2003_UI_MODEL #include "resourceppc.h" #endif #include "CeODAX.h" class CCeODAXModule : public CAtlDllModuleT< CCeODAXModule > { public : DECLARE_LIBID(LIBID_CeODAXLib) #ifndef _CE_DCOM DECLARE_REGISTRY_APPID_RESOURCEID(IDR_CEODAX, "{439A5112-7237-4E78-BAF4-C94D73F8D87D}") #endif }; CCeODAXModule _AtlModule; // DLL Entry Point extern "C" BOOL WINAPI DllMain(HANDLE hInstance, DWORD dwReason, LPVOID lpReserved) { hInstance; return _AtlModule.DllMain(dwReason, lpReserved); } // Used to determine whether the DLL can be unloaded by OLE STDAPI DllCanUnloadNow(void) { return _AtlModule.DllCanUnloadNow(); } // Returns a class factory to create an object of the requested type STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) { return _AtlModule.DllGetClassObject(rclsid, riid, ppv); } // DllRegisterServer - Adds entries to the system registry STDAPI DllRegisterServer(void) { // registers object, typelib and all interfaces in typelib HRESULT hr = _AtlModule.DllRegisterServer(); return hr; } // DllUnregisterServer - Removes entries from the system registry STDAPI DllUnregisterServer(void) { HRESULT hr = _AtlModule.DllUnregisterServer(FALSE); return hr; }
20.746032
88
0.767406
[ "object" ]
fccfa0f4da634332958082209ed616da8529a718
23,105
hh
C++
src/MultiOrderCounts_tmpl.hh
psmit/variKN
9623c5909bb43a5e3f9bb4df850284e30784e957
[ "BSD-3-Clause" ]
null
null
null
src/MultiOrderCounts_tmpl.hh
psmit/variKN
9623c5909bb43a5e3f9bb4df850284e30784e957
[ "BSD-3-Clause" ]
null
null
null
src/MultiOrderCounts_tmpl.hh
psmit/variKN
9623c5909bb43a5e3f9bb4df850284e30784e957
[ "BSD-3-Clause" ]
null
null
null
// Library for storing and modifying the n-gram counts /********************************************************************** These functions are for top level class (BOT abstracted away) **********************************************************************/ template <typename KT, typename CT> CT MultiOrderCounts<KT, CT>::GetCount(const std::vector<KT> &v) { return(GetCount(v.size(),&v[0])); } template <typename KT, typename CT> CT MultiOrderCounts<KT,CT>::IncrementCount(const std::vector<KT> &v, const CT value) { return(IncrementCount(v.size(), &v[0],value)); } /*********************************************************************** Functions for the lower level template implementing most of the class **********************************************************************/ template <typename KT, typename CT> long MultiOrderCounts<KT, CT>::InitializeCountsFromText(FILE *in, Vocabulary *vocab, const bool grow_vocab, const int read_order, const std::string &sent_start_sym) { char charbuf[MAX_WLEN+1]; long num_read=0; int sent_start_idx; KT idx; std::vector<KT> v; if (grow_vocab) { if (sent_start_sym.size()) sent_start_idx=vocab->add_word(sent_start_sym); else sent_start_idx=-1; vocabsize=64000; } else { vocabsize=vocab->num_words(); if (!sent_start_sym.size()) sent_start_idx=-1; else if (!(sent_start_idx=vocab->word_index(sent_start_sym))) { fprintf(stderr,"No sentence start symbol %s in vocabulary, exit.\n", sent_start_sym.c_str()); exit(-1); } } while (fscanf(in,MAX_WLEN_FMT_STRING,charbuf)!=EOF) { num_read++; //if (num_read % 1000000 == 0) fprintf(stderr,"Read %lld words\n",num_read); if (grow_vocab) idx=vocab->add_word(charbuf); else idx=vocab->word_index(charbuf); //fprintf(stderr,"Word %s = %d\n", charbuf, idx); if (idx==sent_start_idx) v.clear(); if (v.size()<read_order) v.push_back(idx); else v.back()=idx; IncrementCount(v,1); //fprintf(stderr,"Cadd ");print_indices(stderr,v);fprintf(stderr," %d\n", 1); if (v.size()==read_order) for (int j=0;j<read_order-1;j++) v[j]=v[j+1]; } fprintf(stderr,"Finished reading %ld words.\n", num_read); return(num_read); } template <typename KT, typename CT> long MultiOrderCounts<KT, CT>::InitializeCountsFromStorage(Storage_t<KT, CT> *data, const int read_order, const int sent_start_idx) { long num_read=0; std::vector<KT> v; KT idx; //fprintf(stderr,"Init from storage\n"); for (size_t di=0;di<data->size(); di++) { //fprintf(stderr,"adding %d: %d\n", di, data->data(di)); num_read++; idx=data->data(di); if (idx==sent_start_idx) v.clear(); if (v.size()<read_order) v.push_back(idx); else v.back()=idx; IncrementCount(v,1); if (v.size()==read_order) for (int j=0;j<read_order-1;j++) v[j]=v[j+1]; } return(num_read); } template <typename KT, typename CT> CT MultiOrderCounts<KT, CT>::Increment_wo_del( struct matrix *m, const KT *indices, const CT value) { indextype idx=FindEntry(m, (byte *) indices, 1); CT *valp = (CT *) &(m->data[idx*m->size_of_entry]); *valp+=value; return(*valp); } template <typename KT, typename CT> void MultiOrderCounts<KT, CT>::SetCount(const int order, const KT *v, const CT value) { allocate_matrices_counts(order); m_counts[order]->setvalue(v,value); } template <typename KT, typename CT> CT MultiOrderCounts<KT, CT>::GetCount(const int order, const KT *v) { if (order >= m_counts.size()) return(0); return(m_counts[order]->getvalue(v)); } template <typename KT, typename CT> CT MultiOrderCounts<KT, CT>::IncrementCount(const int order, const KT *v, const CT value) { allocate_matrices_counts(order); return(Increment_wo_del(m_counts[order]->m, v, value)); } template <typename KT, typename CT> void *MultiOrderCounts<KT, CT>:: StepCountsOrder(const bool init, const int order, KT *indices, CT *value) { if (order>=m_counts.size()) return(NULL); return(m_counts[order]->stepthrough(init,indices,value)); } template <typename KT, typename CT> void *MultiOrderCounts<KT, CT>::OrderedStepCountsOrder(const bool init, const int order, KT *indices, CT *value){ if (order>=m_counts.size()) return(NULL); return(m_counts[order]->ordered_stepthrough(init,indices,value)); } template <typename KT, typename CT> CT MultiOrderCounts<KT, CT>::GetBackoffDen(const std::vector<KT> &v) { return(GetBackoffDen(v.size(),&v[0])); } template <typename KT, typename CT> CT MultiOrderCounts<KT, CT>::GetBackoffNzer(const std::vector<KT> &v) { return(GetBackoffNzer(v.size(),&v[0])); } template <typename KT, typename CT> MultiOrderCounts<KT, CT>::~MultiOrderCounts() { for (int i=1;i<m_counts.size();i++) if (std::find(m_do_not_delete.begin(),m_do_not_delete.end(),i) == m_do_not_delete.end()) // The matrix was internally malloced delete m_counts[i]; } template <typename KT, typename CT> void MultiOrderCounts<KT, CT>::allocate_matrices_counts(int o) { if (o<m_counts.size()) return; if (vocabsize==0) { fprintf(stderr,"MultiOrderCounts: Please set a reasonable vocabulary size. Exit.\n"); exit(-1); } if (hashsize==0) hashsize=600000; indextype real_hashsize; int old_size=m_counts.size(); m_counts.resize(o+1,NULL); for (int i=std::max(1,old_size);i<m_counts.size();i++) { assert(m_counts[i]==NULL); std::vector<KT> v(i,(KT) vocabsize); // Some heuristics to try to get reasonable hash sizes. Not too well tested real_hashsize=std::min(std::max(1000,(indextype) (vocabsize*pow((float) i,3))),hashsize); //fprintf(stderr,"min(%d*%d^3=%.0f,", vocabsize,i, vocabsize*pow((float) i, 3)); //fprintf(stderr,"%d)\n", (int) hashsize); if (i>4 && order_size(i-1)>1) real_hashsize=order_size(i-1)*2+1; //if (i>2) fprintf(stderr,"Allocating counts matrices for order %d, size %d (prev size %d, vocabsize %d)\n", i, real_hashsize, order_size(i-1), this->vocabsize); m_counts[i]= new sikMatrix<KT, CT>(i,real_hashsize,0); } } template <typename KT, typename CT> bool MultiOrderCounts<KT, CT>::NextVector(std::vector<KT> &v) { if (m_cur_ng>=m_counts[m_cur_order]->num_entries()) { m_cur_ng=0; m_cur_order++; while (m_cur_order<m_counts.size() && m_counts[m_cur_order]->num_entries()==0) m_cur_order++; if (m_cur_order>=m_counts.size()) { m_cur_order=1; m_cur_ng=0; return(false); } } v.resize(m_cur_order); const KT *keys=m_counts[m_cur_order]->Idx2Keyp(m_cur_ng); for (int i=0;i<m_cur_order;i++) { v[i]=keys[i]; } m_cur_ng++; return(true); } template <typename KT, typename CT> CT MultiOrderCounts<KT, CT>::IncrementCountCache( const int order, const KT *indices, const CT value) { allocate_matrices_counts(order); CT *v; c_cache.resize(c_cache.size()+1); c_cache_t &c=c_cache.back(); c.order=order; c.val=value; struct matrix *m = m_counts[order]->m; const indextype idx=FindEntry(m, (byte *) indices, 1); c.index=idx; v=m_counts[order]->Idx2Valp(idx); //(CT *) &(m->data[idx*m->size_of_entry]); *v += value; return(*v); } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>::WriteCounts(FILE *out) { std::vector<KT> v; CT val; BOT bo_val; fprintf(out,"\\vocabsize %d\n", MultiOrderCounts<KT, CT>::vocabsize); for (int o=1; o<=order(); o++) { v.resize(o); fprintf(out,"\\%d-gram counts\n",o); this->StepCountsOrder(true, o, &v[0], &val); while (this->StepCountsOrder(false, o, &v[0], &val)) { if (val==0) continue; print_indices(out, v); fprintf(out," "); this->write_num(out, val); fprintf(out,"\n"); } v.resize(o-1); fprintf(out, "\n\\%d-gram backoffs\n",o); if (o==1) { fprintf(out, "[ ] "); WriteCounts_BOhelper(out, &m_uni_bo); fprintf(out, "\n\n"); continue; } StepBackoffsOrder(true, o, &v[0], &bo_val); while (StepBackoffsOrder(false, o, &v[0], &bo_val)) { if (bo_val.den==0) continue; print_indices(out, v); fprintf(out," "); WriteCounts_BOhelper(out, &bo_val); fprintf(out,"\n"); } fprintf(out,"\n"); } } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>::ReadCounts(FILE *in) { int order=-1; std::string line; std::vector<KT> v; std::vector<std::string> vec; CT val; BOT bo_val; long lineno=0; bool read_backoffs=false; bool ok=true; if (!str::read_line(&line, in ,true) || 1!=sscanf(line.c_str(),"\\vocabsize %d",& (this->vocabsize))) { fprintf(stderr,"Error reading counts file.\nExit.\n"); exit(-1); } while (str::read_line(&line, in, true)) { //fprintf(stderr,"READ %s\n", line.c_str()); lineno++; // Skip empty lines if (line.find_first_not_of(" \t\n") == line.npos) continue; if (line[0] == '\\') { str::split(&line, "-", true, &vec); vec[0][0]=' '; order = str::str2long(&vec[0], &ok); //fprintf(stderr,"ordered %s=%d(%d)\n", vec[0].c_str(), order, ok); //fprintf(stderr,"comparestring *%s*\n", vec[1].c_str()); if (!strcmp("gram counts", vec[1].c_str())) { read_backoffs=false; v.resize(order); } else if (!strcmp("gram backoffs", vec[1].c_str())) { read_backoffs=true; v.resize(order-1); } else ok=false; if (!ok) { fprintf(stderr,"Error reading line %ld.\n%s\nExit.\n", lineno, line.c_str()); exit(-1); } continue; } str::split(&line, " \t", true, &vec); //fprintf(stderr,"ORDER %d\n", order); if (!read_backoffs) { for (int i=1;i<=order;i++) { v[i-1]=str::str2long(&vec[i], &ok); //fprintf(stderr,"Putting %s=%d, %d\n", vec[i].c_str(), v[i-1], ok); } this->read_num(&val, &vec[order+2], &ok); //fprintf(stderr,"Val %s=%d (%d)\n", vec[order+2].c_str(), val, ok); if (!ok) { fprintf(stderr,"Error reading line %ld:\n%s\nExit2.\n", lineno, line.c_str()); exit(-1); } //fprintf(stderr,"Setcount ");print_indices(stderr,v); //fprintf(stderr,"val %d\n", val); this->SetCount(v, val); continue; } for (int i=1;i<order;i++) { v[i-1]=str::str2long(&vec[i], &ok); } ReadCounts_BOhelper(&bo_val, &vec[order+1], &ok); if (!ok) { fprintf(stderr,"Error reading line %ld. Exit3.\n", lineno); exit(-1); } SetBackoff(order, &v[0], &bo_val); } } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>:: IncrementBackoffCache(const int order, const KT *indices, const BOT *value) { bo_cache.resize(bo_cache.size()+1); bo_cache_t &b=bo_cache.back(); b.order=order; b.bo=*value; if (order ==1) { m_uni_bo+=*value; return; } allocate_matrices_backoffs(order); BOT *v; struct matrix *m = m_backoffs[order]->m; const indextype idx=FindEntry(m, (byte *) indices, 1); b.index=idx; v=(BOT *) &(m->data[idx*m->size_of_entry]); *v += *value; } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>::ResetCaches() { this->c_cache.resize(0); bo_cache.resize(0); this->min_cc_cache.resize(this->m_counts.size()+1); for (int i=1;i<this->m_counts.size();i++) { this->min_cc_cache[i]=this->m_counts[i]->num_entries(); //fprintf(stderr,"cc[%d]=%d\n",i,m_counts[i]->num_entries); } this->min_cc_cache[this->m_counts.size()]=0; min_bo_cache.resize(m_backoffs.size()+1); for (int i=2;i<m_backoffs.size();i++) { min_bo_cache[i]=m_backoffs[i]->num_entries(); //fprintf(stderr,"bo[%d]=%d\n",i,m_backoffs[i]->num_entries); } min_bo_cache[m_backoffs.size()]=0; } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>::UndoCached() { /* This could be speeded up by assuming that all cached values are of the same order */ for (long i=this->c_cache.size()-1;i>=0;i--) { struct MultiOrderCounts<KT,CT>::c_cache_t &c=this->c_cache[i]; struct matrix *m = this->m_counts[c.order]->m; * (CT *)(&(m->data[c.index*m->size_of_entry])) -= c.val; } for (int j=1;j<this->m_counts.size();j++) { for (long i=this->m_counts[j]->num_entries()-1;i>=this->min_cc_cache[j];i--) { RemoveEntryIdx(MultiOrderCounts<KT, CT>::m_counts[j]->m,i); } } /* Copy of the beginning of the func modified for backoffs.. */ for (long i=bo_cache.size()-1;i>=0;i--) { struct bo_cache_t &c=bo_cache[i]; if (c.order == 1) { m_uni_bo-=c.bo; continue; } if (c.index >= min_bo_cache[c.order]) continue; struct matrix *m = m_backoffs[c.order]->m; BOT *bo = (BOT *) (&(m->data[c.index*m->size_of_entry])); *bo-=c.bo; } for (int j=2;j<m_backoffs.size();j++) { for (long i=m_backoffs[j]->num_entries()-1;i>=min_bo_cache[j];i--) RemoveEntryIdx(m_backoffs[j]->m,i); } } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>:: IncrementBackoff(const int order, const KT *v, const BOT *value) { if (order==1) { m_uni_bo+= *value; return; } allocate_matrices_backoffs(order); m_backoffs[order]->increment(v,value); } template <typename KT, typename CT, typename BOT> CT MultiOrderCounts_Generic_BOT<KT, CT, BOT>::GetBackoffDen(const int order, const KT *v) { if (order==1) return(m_uni_bo.den); if (order>=m_backoffs.size()) return(0); return(m_backoffs[order]->getvalue(v).den); } template <typename KT, typename CT> void MultiOrderCounts<KT, CT>::UseAsCounts(sikMatrix<KT, CT> *mat) { /* Should get rid of m->dims, so that libsparsematrix can be cleaned up */ allocate_matrices_counts(mat->dims); if (std::find(m_do_not_delete.begin(),m_do_not_delete.end(),mat->dims) == m_do_not_delete.end()) // The matrix was internally malloced delete m_counts[mat->dims]; m_counts[mat->dims]=mat; m_do_not_delete.push_back(mat->dims); } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>::RemoveOrder(int order) { fprintf(stderr,"cur_o %d(%ld): ",order, (long) MultiOrderCounts<KT, CT>::m_counts.size()-1); assert(order == (MultiOrderCounts<KT, CT>::m_counts.size()-1)) ; delete MultiOrderCounts<KT, CT>::m_counts.back(); MultiOrderCounts<KT, CT>::m_counts.pop_back(); assert(order==m_backoffs.size()-1); delete m_backoffs.back(); m_backoffs.pop_back(); fprintf(stderr,"cur_o %d(%ld): ",order, (long) MultiOrderCounts<KT, CT>::m_counts.size()-1); } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>:: IncrementBackoff(const std::vector<KT> &v, const BOT *value) { IncrementBackoff(v.size(),&v[0],value); } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>::SetBackoff( const int order, const KT *v, const BOT *bo) { allocate_matrices_backoffs(order); if (order>1) { m_backoffs[order]->setvalue(v,bo); return; } m_uni_bo = *bo; } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>::SetBackoff( const std::vector<KT> &v, const BOT *bo) { SetBackoff(v.size()+1,&v[0],bo); } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>::GetBackoff(const int order, const KT *v, BOT *value){ if (order>=m_backoffs.size()) { memcpy(value,&m_bb_init,sizeof(BOT)); return; } if (order>1) { m_backoffs[order]->getvalue(v,value); return; } memcpy(value,&m_uni_bo,sizeof(BOT)); } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>::IncrementBackoffCacheDen( const int order, const KT *v, const CT value){ BOT bo; zero_bo(bo); bo.den=value; IncrementBackoffCache(order, v, &bo); } template <typename KT, typename CT, typename BOT> MultiOrderCounts_Generic_BOT<KT, CT, BOT>::MultiOrderCounts_Generic_BOT() { m_bb_init.den=0; m_bb_init.nzer=0; m_bb_init.prune_den=0; m_bb_fp_init.den=0; m_bb_fp_init.nzer=0; m_bb_fp_init.lost=0; m_bb_fp_init.lost_den=0; m_3bb_init.den=0; m_3bb_init.nzer[0]=0;m_3bb_init.nzer[1]=0;m_3bb_init.nzer[2]=0; m_3bb_init.prune_den=0; m_3bb_fp_init.den=0; m_3bb_fp_init.nzer[0]=0;m_3bb_fp_init.nzer[1]=0;m_3bb_fp_init.nzer[2]=0; m_3bb_fp_init.prune_den=0; m_3bb_fp_init.prune_den_left[0]=0; m_3bb_fp_init.prune_den_left[1]=0; m_3bb_fp_init.prune_den_left[2]=0; m_3bb_fp_init.prune_den_den[0]=0; m_3bb_fp_init.prune_den_den[1]=0; m_3bb_fp_init.prune_den_den[2]=0; zero_bo(m_uni_bo); zero_bo(bo_init); } template <typename KT, typename CT, typename BOT> MultiOrderCounts_Generic_BOT<KT, CT, BOT>::~MultiOrderCounts_Generic_BOT() { for (int i=2;i<m_backoffs.size();i++) { delete m_backoffs[i]; } } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>:: IncrementBackoffDen(const int order, const KT *indices, const CT den) { allocate_matrices_backoffs(order); if (order>1) { struct matrix *m = m_backoffs[order]->m; indextype idx=FindEntry(m, (byte *) indices,1); BOT *bop=(BOT *)(&(m->data[idx*m->size_of_entry])); bop->den+=den; // Delete node, if matches default value if (!memcmp(bop,m->default_value, m->size_of_entry)) RemoveEntryIdx(m,idx); return; } m_uni_bo.den+=den; } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>::allocate_matrices_backoffs(int o ) { if (o<m_backoffs.size()) return; if (this->vocabsize==0) { fprintf(stderr,"MultiOrderCounts_t: Please set a reasonable vocabulary size. Exit.\n"); exit(-1); } if (this->hashsize==0) this->hashsize=300000; indextype real_hashsize; int old_size=m_backoffs.size(); m_backoffs.resize(o+1,NULL); for (int i=std::max(2,old_size);i<m_backoffs.size();i++) { assert(m_backoffs[i]==NULL); // Some heuristics to try to get reasonable hash sizes. Not too well tested real_hashsize=std::min(std::max(1000,(indextype) (this->vocabsize*pow((float) i,3))),this->hashsize); if (i>4 && bo_order_size(i-1)>1) real_hashsize=bo_order_size(i-1)*2+1; fprintf(stderr,"Allocating backoff matrices for order %d, size %ld", i, (long) real_hashsize); if (i>2) fprintf(stderr,"(prev_size %d, vocabsize %d)\n", bo_order_size(i-1), this->vocabsize); else fprintf(stderr,"\n"); m_backoffs[i]=new sikMatrix<KT, BOT>(i-1,real_hashsize,bo_init); fprintf(stderr,"allocation succesful\n"); } } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>::clear_derived_counts() { zero_bo(m_uni_bo); this->m_counts[1]->clear(); for (int i=2; i<this->m_counts.size()-1;i++) { this->m_counts[i]->clear(); m_backoffs[i]->clear(); } m_backoffs.back()->clear(); } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>::clear_nzer(int o) { if (o>1) { for (indextype i=0;i<m_backoffs[o]->num_entries();i++) zero_nz(m_backoffs[o]->Idx2Valp(i)); return; } zero_nz(&m_uni_bo); } template <typename KT, typename CT> void MultiOrderCounts_1nzer_fp<KT, CT>::clear_lden(const int o) { if (o>1) { for (indextype i=0;i<MultiOrderCounts_Generic_BOT<KT, CT, MultiOrderCounts_counter_types::bo_c_fp<CT> >::m_backoffs[o]->num_entries();i++) { MultiOrderCounts_counter_types::bo_c_fp<CT> *bop = MultiOrderCounts_Generic_BOT<KT, CT, MultiOrderCounts_counter_types::bo_c_fp<CT> >::m_backoffs[o]->Idx2Valp(i); bop->lost_den=0; } return; } MultiOrderCounts_Generic_BOT<KT, CT, MultiOrderCounts_counter_types::bo_c_fp<CT> >::m_uni_bo.lost_den=0; } template <typename KT, typename CT, typename BOT> void *MultiOrderCounts_Generic_BOT<KT, CT, BOT>:: StepBackoffsOrder(const bool init, const int order, KT *indices, BOT *value) { if (order>=MultiOrderCounts<KT, CT>::m_counts.size()) return(NULL); assert(order>=2); return(m_backoffs[order]->stepthrough(init,indices,value)); } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>:: IncrementBackoffNzer_1nzer(const int order, const KT *indices, const CT nz) { if (order>1) { allocate_matrices_backoffs(order); struct matrix *m=m_backoffs[order]->m; indextype idx=FindEntry(m,(byte *) indices,1); BOT *bop = (BOT *)(&(m->data[idx*m->size_of_entry])); bop->nzer+=nz; // Delete node, if matches default value if (!memcmp(bop,m->default_value, m->size_of_entry)) RemoveEntryIdx(m,idx); return; } m_uni_bo.nzer+=nz; } template <typename KT, typename CT, typename BOT> CT MultiOrderCounts_Generic_BOT<KT, CT, BOT>:: GetBackoffNzer_1nzer(const int order,const KT *v){ if (order==1) return(m_uni_bo.nzer); if (order>=m_backoffs.size()) return(0); return(m_backoffs[order]->getvalue(v).nzer); } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>:: IncrementBackoffCacheNzer_1nzer(const int order, const KT *v, const CT value) { BOT bo; zero_bo(bo); bo.nzer=value; IncrementBackoffCache(order,v, &bo); } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>:: GetBackoffNzer_3nzer(const int order, const KT *v, CT *res) { if (order==1) { for (int i=0;i<3;i++) res[i]=m_uni_bo.nzer[i]; return; } if (order>=m_backoffs.size()) { for (int i=0;i<3;i++) res[i]=0; return; } BOT bo; m_backoffs[order]->getvalue(v,&bo); for (int i=0;i<3;i++) res[i]=bo.nzer[i]; } template <typename KT, typename CT, typename BOT> CT MultiOrderCounts_Generic_BOT<KT, CT, BOT>:: GetBackoffNzer_3nzer(const int order, const KT *v, const int which) { CT res[3]; GetBackoffNzer(order,v,res); return(res[which]); } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>:: IncrementBackoffCacheNzer_3nzer(const int order, const KT *v, const CT *value){ BOT bo; zero_bo(bo); bo.nzer[0]=value[0];bo.nzer[1]=value[1];bo.nzer[2]=value[2]; IncrementBackoffCache(order,v, &bo); } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>:: IncrementBackoffCacheNzer_3nzer(const int order, const KT *v, const int pos, const CT value){ BOT bo; zero_bo(bo); bo.nzer[pos]=value; IncrementBackoffCache(order,v, &bo); } template <typename KT, typename CT, typename BOT> void MultiOrderCounts_Generic_BOT<KT, CT, BOT>:: IncrementBackoffNzer_3nzer(const int order, const KT *indices, const int pos, const CT nz) { if (order > 1) { struct matrix *m=m_backoffs[order]->m; indextype idx=FindEntry(m,(byte *) indices,1); BOT *bop = (BOT *) (&(m->data[idx*m->size_of_entry])); bop->nzer[pos]+=nz; // Delete node, if matches default value if (!memcmp(bop,m->default_value, m->size_of_entry)) RemoveEntryIdx(m,idx); return; } m_uni_bo.nzer[pos]+=nz; }
32.090278
166
0.657866
[ "vector" ]
fcd627de8abda33677862b3fe48a1002561e0f20
38,752
cc
C++
agent/base/Synchronizer.cc
automenta/trex-autonomy
fcca1f7596af30735fe53d1bab54b3a0c1f97b89
[ "BSD-3-Clause" ]
null
null
null
agent/base/Synchronizer.cc
automenta/trex-autonomy
fcca1f7596af30735fe53d1bab54b3a0c1f97b89
[ "BSD-3-Clause" ]
null
null
null
agent/base/Synchronizer.cc
automenta/trex-autonomy
fcca1f7596af30735fe53d1bab54b3a0c1f97b89
[ "BSD-3-Clause" ]
null
null
null
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2007. MBARI. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the TREX Project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "Synchronizer.hh" #include "DbCore.hh" #include "Token.hh" #include "TokenVariable.hh" #include "PlanDatabaseWriter.hh" #include "PlanDatabase.hh" #include "Timeline.hh" #include "Agent.hh" #include "Utilities.hh" namespace TREX { Synchronizer::Synchronizer(const DbCoreId& _core) : m_core(_core), m_db(m_core->m_db), m_timelines(m_core->m_timelines), m_goals(m_core->m_goals), m_observations(m_core->m_observations), m_tokenAgenda(m_core->m_tokenAgenda), m_committedTokens(m_core->m_committedTokens){} /** * Will be in the horizon if start.ub <= (tao) && end.lb >= tao */ bool Synchronizer::inTickHorizon(const TokenId& token, int currentTick){ return token->start()->lastDomain().getUpperBound() <= currentTick && token->end()->lastDomain().getLowerBound() >= currentTick && token->end()->lastDomain().getLowerBound() > 0; } /** * @brief Will be in scope if in the tick horizon and in scope for this reactor, and a unit decision */ bool Synchronizer::inSynchScope(const TokenId& token, TokenId& mergeCandidate){ if(inTickHorizon(token, m_core->getCurrentTick()) && m_core->inScope(token) && !m_core->inDeliberation(token) && isUnit(token, mergeCandidate)) return true; return false; } /** * @brief Will be a unit decision if it has only one option to be resolved or if it has a specific position * in the plan. The latter case arises where we have a token that must go in a specific time slot but which * could merge onto the plan or insert and nudge the plan. The resolution model will only try one. If that fails, it will * relax the plan. * @note Any token that is rejectable is not in scope. */ bool Synchronizer::isUnit(const TokenId& token, TokenId& merge_candidate){ if(!token->getObject()->lastDomain().isSingleton()) return false; // Compute compatible tokens, using an exact test std::vector<TokenId> compatible_tokens; m_db->getCompatibleTokens(token, compatible_tokens, PLUS_INFINITY, true); // Iterate over tokens to find one suitable for merging in synchronization unsigned int merge_choice_count(0); for(std::vector<TokenId>::const_iterator it = compatible_tokens.begin(); it != compatible_tokens.end(); ++it){ TokenId candidate = *it; // If the token in question is in deliberation, continue if(m_core->inDeliberation(candidate)){ TREX_INFO("trex:warning:synchronization", candidate->toString() << " cannot be used because it is in delibertion."); continue; } merge_choice_count++; merge_candidate = candidate; // If we have more than one option, break out of loop since this is not a unit decision if(merge_choice_count > 1) break; } // If we have only one option to merge onto, and we have nowhere to insert the token, then we will have a unit decision if(merge_choice_count == 1 && !m_db->hasOrderingChoice(token)){ TREX_INFO("trex:debug:synchronization", "Found unit decision for " << token->toString() << " with start = " << token->start()->lastDomain().toString() << ". One spot to merge it."); return true; } if(merge_choice_count == 0){ merge_candidate = TokenId::noId(); TREX_INFO("trex:debug:synchronization", "Found unit decision for " << token->toString() << " with start = " << token->start()->lastDomain().toString() << ". No ordering choice."); return true; } TREX_INFO("trex:debug:synchronization", "Excluding " << token->toString()); return false; } ConstrainedVariableId Synchronizer::getActiveGuard(const ConstrainedVariableId& var){ EntityId parent = var->parent(); if(parent.isId() && TokenId::convertable(parent)){ TokenId token = parent; // If the token has been merged, we want the underlying variable if(token->isMerged()) return token->getActiveToken()->getVariables()[var->getIndex()]; // No binding rules on inactive tokens if(token->isInactive()) return ConstrainedVariableId::noId(); } return var; } /* * @brief Resolve unit flaws at the execution frontier */ bool Synchronizer::resolve(){ // Use a counter to aid with settng debug breakpoints static unsigned int sl_counter(0); sl_counter++; if(!m_core->propagate()){ TREX_INFO("trex:debug:synchronization", m_core->nameString() << "Constraint network inconsistent after propagation. Cannot output database."); return false; } TREX_INFO("trex:debug:synchronization", m_core->nameString() << "Database prior to synchronization:\n" << PlanDatabaseWriter::toString(m_db)); checkError(m_core->isValidDb(), "Invalid database before synchronization."); m_stepCount = 0; // Reset step counter for stats if(resolveTokens(m_stepCount) && completeInternalTimelines(m_stepCount) && resolveTokens(m_stepCount)){ TREX_INFO("trex:debug:synchronization", m_core->nameString() << "Database after successful synchronization:\n" << PlanDatabaseWriter::toString(m_db)); return true; } return false; } /** * @brief Relax the plan at the execution frontier, but keep what is entailed by prior state. * the model, and current observations.. */ bool Synchronizer::relax(bool discardCurrentValues) { TREXLog() << m_core->nameString() << "Beginning database relax." << std::endl; TREX_INFO("trex:debug:synchronization:relax", m_core->nameString() << "START"); // Reset observations to base values. It is important that we do this before processing // other tokens as we want to recover the current observation and the easiest way to // do that is to evaluate the end time of committed observations or observations that are // merged onto committed tokens. We cannot do the latter if they have been split, which // can happen when we reset goals or other commitments. We do not want any propagation to be // done during this reset since we will just be relaxing the database and re-propagating and // the system will be in an incomplete state in the interim while all resets are done. resetObservations(); // Reset the goals, clearing out the crud resetGoals(discardCurrentValues); // Reset remaining tokens resetRemainingTokens(discardCurrentValues); // Purge bad links in foreign key table. m_core->purgeOrphanedKeys(); checkError(m_core->verifyEntities(), "Bug somewhere."); TREX_INFO("trex:debug:synchronization:relax", m_core->nameString() << "Prior to insertion of copied values" << std::endl << PlanDatabaseWriter::toString(m_db)); // Final step before trying again to resolve if(insertCopiedValues()){ TREX_INFO("trex:debug:synchronization:relax", m_core->nameString() << "Relaxed Database Below" << std::endl << PlanDatabaseWriter::toString(m_db)); return true; } TREXLog() << m_core->nameString() << "Relax failed." << std::endl; return false; } /** * @brief Relaxes goal commitments and removes those goals that are no longer achievable * @see relax */ void Synchronizer::resetGoals(bool discardOpenGoals){ TREX_INFO("trex:debug:synchronization:resetGoals", m_core->nameString() << "START with 'discard open goals' " << (discardOpenGoals ? "enabled." : "disabled.")); std::vector<TokenId> past; /*!< Necessarily in the past */ std::vector<TokenId> present; /*!< Committed goals we will want to make a relaxed copy of */ // Iterate over the goals and place in different buckets. We make no mods in this iteration since they can impact the // contents of the map, possibly removing goals altogether. This can be the case since some goals are sub-goals and can thus be deleted // if the master is relaxed or removed. TokenSet goals = m_goals; for(TokenSet::const_iterator it = goals.begin(); it != goals.end(); ++it){ TokenId goal = *it; checkError(goal.isValid(), "Invalid goal:" << goal); checkError(goal->master().isNoId(), "Should only have orphans in the goal buffer. " << goal->toString() << " has master " << goal->getMaster()->toString()); assertTrue(!goal->start()->baseDomain().isEmpty(), "Bad"); const IntervalIntDomain& endTime = (goal->isMerged() ? goal->getActiveToken()->end()->baseDomain() : goal->end()->baseDomain()); TREX_INFO("trex:debug:synchronization:resetGoals", m_core->nameString() << "Evaluating " << goal->toString() << " ending in " << endTime.toString()); // Case 2: The goal is a current value it will be handled when we reset remaining tokens if(isCurrent(goal)){ m_goals.erase(goal); TREX_INFO("trex:debug:synchronization:resetGoals", m_core->nameString() << "Removing goal but keeping value for:" << goal->toString()); continue; } // Case 0: We are discarding open goals if(discardOpenGoals == true){ TREX_INFO("trex:debug:synchronization:resetGoals", m_core->nameString() << "Open goal will be removed: " << goal->toString()); past.push_back(goal); continue; } // Case 1: The goal must end in the past if(endTime.getUpperBound() <= m_core->getCurrentTick()){ TREX_INFO("trex:debug:synchronization:resetGoals", m_core->nameString() << "Ends in the past: " << goal->toString()); past.push_back(goal); continue; } // Case 3: The goal was previously rejected and cannot be started. This is also considered the past. if(goal->isRejected() && goal->start()->baseDomain().getUpperBound() < m_core->getCurrentTick()){ TREX_INFO("trex:debug:synchronization:resetGoals", m_core->nameString() << "Rejected: " << goal->toString()); past.push_back(goal); continue; } // Case 4: The goal is merged with a current value. We will remove the goal as it has already been started. if(goal->isMerged() && isCurrent(goal->getActiveToken())){ TREX_INFO("trex:debug:synchronization:resetGoals", m_core->nameString() << "Merged with current value." << goal->toString()); past.push_back(goal); continue; } // Case 5: The goal is active. It will be in the future so and it's parameters should be reset if(goal->isActive()){ const std::vector<ConstrainedVariableId>& vars = goal->getVariables(); for(std::vector<ConstrainedVariableId>::const_iterator it = vars.begin(); it != vars.end(); ++it){ ConstrainedVariableId var = *it; if(var->canBeSpecified() && var->isSpecified()) var->reset(); } } // Case 6: The goal cannot be planned in time if(goal->start()->baseDomain().getUpperBound() < m_core->getCurrentTick()){ TREX_INFO("trex:debug:synchronization:resetGoals", m_core->nameString() << "Might have to start before we have time to plan."); past.push_back(goal); continue; } // Finally, if the goal remains !inActive, it must be cancelled and fixed in the future. if(!goal->isInactive()){ goal->cancel(); goal->start()->restrictBaseDomain(IntervalIntDomain(m_core->getCurrentTick(), PLUS_INFINITY)); } } for(std::vector<TokenId>::const_iterator it = past.begin(); it != past.end(); ++it){ TokenId token = *it; TREX_INFO("trex:debug:synchronization:resetGoals", m_core->nameString() << "Discarding goal: " << token->toString()); m_core->cleanupGoal(token); token->discard(); } TREX_INFO("trex:debug:synchronization:resetGoals", m_core->nameString() << "END"); } /** * @brief Clear out observations, and set only the current observation. Assumes no splitting has * occurred yet. So must precede goal reset. */ void Synchronizer::resetObservations(){ static int sl_counter(0); sl_counter++; TREX_INFO("trex:debug:synchronization:resetObservations", m_core->nameString() << "[" << sl_counter << "]START"); TokenSet observations = m_observations; for(TokenSet::iterator it = observations.begin(); it != observations.end(); ++it){ TokenId observation = *it; checkError(observation.isValid(), observation); TREX_INFO("trex:debug:synchronization:resetObservations", m_core->nameString() << "Evaluating " << observation->toString()); // If the observation contains merged tokens, they should all be cancelled. TokenSet mergedTokens = observation->getMergedTokens(); for(TokenSet::const_iterator it = mergedTokens.begin(); it != mergedTokens.end(); ++it){ TokenId m = *it; m->cancel(); } if(m_core->isCurrentObservation(observation)){ TREX_INFO("trex:debug:synchronization:resetObservations", m_core->nameString() << "Handling current observation " << observation->toString()); // Relax if we can and if we must. If committed, see remaining Tokens if(!observation->isCommitted() && !observation->isInactive()){ TREX_INFO("trex:debug:synchronization:resetObservations", m_core->nameString() << "Relaxing " << observation->toString()); observation->cancel(); } // We know we are synhronizing, so if this is the current value, we are extending it so that it must hold for this tick checkError(observation->end()->baseDomain().isMember(m_core->getCurrentTick() + 1), observation->toString() << " must end in " << observation->end()->baseDomain().toString()); // The end variable might be specified, so reset if it is. if(observation->end()->isSpecified()) observation->end()->reset(); else observation->end()->relax(); observation->end()->restrictBaseDomain(IntervalIntDomain(m_core->getCurrentTick() + 1, PLUS_INFINITY)); } else observation->discard(); } TREX_INFO("trex:debug:synchronization:resetObservations", m_core->nameString() << "END"); } /** * @brief Handle the remainder * Assumes we have already reset goals and observations. Will also force a copy of current committed tokens to re-apply the model. * @see relax */ void Synchronizer::resetRemainingTokens(bool discardCurrentValues){ TREX_INFO("trex:debug:synchronization:resetRemainingTokens", m_core->nameString() << "START with discarding current internal values " << (discardCurrentValues ? "enabled." : "disabled.")); std::vector<TokenId> tokensToDiscard; const TokenSet allTokens = m_db->getTokens(); for(TokenSet::const_iterator it = allTokens.begin(); it!= allTokens.end(); ++it){ TokenId token = *it; checkError(token.isValid(), token); const IntervalIntDomain& endTime = token->end()->baseDomain(); TREX_INFO("trex:debug:synchronization:resetRemainingTokens", m_core->nameString() << "Evaluating " << token->toString() << " ending in " << endTime.toString()); // Case 1: The value is current. This means it is committed, which implies it was previously found to be consistent // during synchronization. if(isCurrent(token)){ if(!discardCurrentValues || m_core->isObservation(token) || isPersistent(token)) copyValue(token); TREX_INFO("trex:debug:synchronization:resetRemainingTokens", "Scheduling discard for current value " << token->toString()); tokensToDiscard.push_back(token); continue; } // Case 3: After excluding the above cases, as long as it is not a goal or observation, which will have been dealt with expliticly in // resetGoals and resetObservations, then we want to remove the token. New tokens will be regenerated by the model if implied. if(!m_core->isGoal(token) && !m_core->isObservation(token)){ TREX_INFO("trex:debug:synchronization:resetRemainingTokens", "Scheduling discard for stale value" << token->toString()); tokensToDiscard.push_back(token); } } // Now we clean up all the tokens we plan to discard. TREX_INFO("trex:debug:synchronization:resetRemainingTokens", "Discarding " << tokensToDiscard.size() << " tokens"); Entity::discardAll(tokensToDiscard); TREX_INFO("trex:debug:synchronization:resetRemainingTokens", m_core->nameString() << "END"); } /** * @brief True if a current value. */ bool Synchronizer::isCurrent(const TokenId& token) { bool result = token->isCommitted() && !token->isTerminated(); // Should not be in the past. Condition varies for internal vs. external tokens bool is_internal = m_core->isInternal(token); result = result && ( (is_internal && token->end()->baseDomain().getUpperBound() >= m_core->getCurrentTick()) || (!is_internal && token->end()->baseDomain().getUpperBound() > m_core->getCurrentTick())); // Can ignore actions - we just regenerate them result = result && !m_core->isAction(token); return result; } /** * @brief Copies a current value to a new token which is also active and committed. We relax the new token * in its end time and in the set of applicable constraints */ void Synchronizer::copyValue(const TokenId& source){ // Allocate a token TokenId token = m_db->getClient()->createToken(source->getPredicateName().c_str(), DbCore::NOT_REJECTABLE); token->activate(); // Pin all variables with published values of the token for(unsigned int i = 0; i < (unsigned int) source->parameters().size(); i++){ token->parameters()[i]->restrictBaseDomain(source->parameters()[i]->baseDomain()); } token->getObject()->restrictBaseDomain(source->getObject()->baseDomain()); token->start()->restrictBaseDomain(source->start()->baseDomain()); token->end()->restrictBaseDomain(IntervalIntDomain(m_core->getCurrentTick(), PLUS_INFINITY)); if(m_core->isObservation(source)){ // Current observations should have their values extended in case this did not happen correctly before pre-emption was required checkError(m_core->isCurrentObservation(source), "Should only be copying current observations. But copied " << source->toString()); token->end()->restrictBaseDomain(IntervalIntDomain(m_core->getCurrentTick() + 1, PLUS_INFINITY)); m_core->bufferObservation(token); } else if(m_core->isGoal(source)){ token->end()->restrictBaseDomain(source->end()->baseDomain()); m_goals.insert(token); } // Update the duration also, based on base domain values of start and end int durationMin = std::max((int) ( token->end()->baseDomain().getLowerBound() - token->start()->baseDomain().getUpperBound()), 0); token->duration()->restrictBaseDomain(IntervalIntDomain(durationMin, PLUS_INFINITY)); // Finally, we commit the value. This is reasonable since we are copying a current value. All this approach allows // us to do is re-apply the model with internal decisions free to be taken anew. Public variables of the token // remain bound to prior valaues since the past is monotonic. Since we have already done the base domain restriction // and we want to prevent propagation while we are relaxing, we just commit directly token->commit(); TREX_INFO("trex:debug:synchronization:copyValue",m_core->nameString() << "Replaced " << source->toString() << " with " << token->toString()); } /** * Processes the token agenda and makes insertion or merge choices */ bool Synchronizer::resolveTokens(unsigned int& stepCount){ static unsigned int sl_counter; unsigned int lastCount = PLUS_INFINITY; while(lastCount != m_stepCount){ lastCount = m_stepCount; // Update this to track changes on this iteration // Process tokens on the agenda that are in scope const TokenSet agenda = m_core->m_tokenAgenda; if(!m_core->propagate()) return false; for(TokenSet::const_iterator it = agenda.begin(); it != agenda.end(); ++it){ // Debugging Aid sl_counter++; TokenId token = *it; TREX_INFO("trex:debug:synchronization:resolveTokens", m_core->nameString() << "[" << sl_counter << "] Evaluating " << token->toString() << " Start = " << token->start()->toString() << " End = " << token->end()->toString()); // Tokens that are unbound are ignored since they are not unit decisions if(!token->getObject()->lastDomain().isSingleton()) continue; // If not inactive, then it must have been resolved already if(!token->isInactive()) continue; // If outside the horizon or out of scope, skip it TokenId merge_candidate; if(!inSynchScope(token, merge_candidate)) continue; stepCount++; TREX_INFO("trex:debug:synchronization:resolveTokens", m_core->nameString() << "Resolving " << token->toString() << " IN " << std::endl << PlanDatabaseWriter::toString(m_db)); // Resolve the token and ensure consistency in order to continue. if(!resolveToken(token, stepCount, merge_candidate) || !m_core->propagate()) return false; } } return true; } bool Synchronizer::resolveToken(const TokenId& token, unsigned int& stepCount, const TokenId& merge_candidate){ if(mergeToken(token, merge_candidate) || insertToken(token, stepCount)) return true; std::string explanation_str; TREX_INFO("trex:monitor:conflicts", m_core->nameString() << (explanation_str = tokenResolutionFailure(token, merge_candidate))); m_core->markInvalid(std::string("Could not insert ") + token->toString() + " into the plan. The plan is not compatible with observations and must be relaxed. Enable all DbCore messages and also enable Synchronizer messages in the Debug.cfg file.", true, explanation_str); return false; } /** * Notes: * 1. All copied values will have been committed * 2. Insertion has been deferred till after all cleanup has occured of prior tokens to avoid restrictions mingling * with relaxations. * 3. We assume no copied values have been inserted yet */ bool Synchronizer::insertCopiedValues(){ TREX_INFO("trex:debug:synchronization:insertCopiedValues", m_core->nameString() << "Relaxed Database Prior to insertion of copied values" << std::endl << PlanDatabaseWriter::toString(m_db)); for(TokenSet::const_iterator it = m_committedTokens.begin(); it != m_committedTokens.end(); ++it){ TokenId token = *it; unsigned int stepCount = 0; if(!insertToken(token, stepCount)){ TREX_INFO("trex:debug:synchronization:insertCopiedValues", m_core->nameString() << "Failed to insert " << token->toString()); std::string explanation_str; TREX_INFO("trex:debug:synchronization:insertCopiedValues", m_core->nameString() << (explanation_str = tokenResolutionFailure(token, TokenId::noId()))); m_core->markInvalid(std::string("Failed to insert ") + token->toString() + "This is bad. After relaxing the plan and restoring necessary state, we still can't synchronize. " + "There is probably a bug in the model. Enable PlanDatabase and DbCore messages in Debug.log", true, explanation_str); return false; } } return true; } /** * Only merge it. True if we tried to merge, false if we did not. */ bool Synchronizer::mergeToken(const TokenId& token, const TokenId& merge_candidate){ if(m_core->isInvalid() || merge_candidate.isNoId()) return false; // No need to try if already active, or if cannot be merged if(!token->isInactive() || !token->getState()->lastDomain().isMember(Token::MERGED)) return false; token->merge(merge_candidate); TREX_INFO("trex:debug:synchronization:mergeToken", m_core->nameString() << "Merging " << token->toString() << " onto " << merge_candidate->toString()); m_core->propagate(); return true; } /** * Tail recursive to follow the slaves */ bool Synchronizer::insertToken(const TokenId& token, unsigned int& stepCount){ if(m_core->isInvalid() || m_core->inDeliberation(token)) return false; // If the token is in the past, we will not insert it. Just remove it from the agenda and return OK if(token->end()->lastDomain().getUpperBound() == Agent::instance()->getCurrentTick()){ m_core->m_tokenAgenda.erase(token); TREX_INFO("trex:debug:synchronization:insertToken", m_core->nameString() << "Skipping insertion of " << token->toString() << " which is in the past."); return true; } if(token->isInactive()) token->activate(); condDebugMsg(!token->getObject()->lastDomain().isSingleton(), "trex:error", "Expecting " << token->toLongString() << " to be bound to a timeline for synchronization"); checkError(token->getObject()->lastDomain().isSingleton(), "Expecting " << token->toLongString() << " to be bound to a timeline for synchronization"); ObjectId object = token->getObject()->lastDomain().getSingletonValue(); // If not a timeline - no ordering requirement if(!TimelineId::convertable(object)) return m_core->propagate(); std::vector<OrderingChoice> results; m_db->getOrderingChoices(token, results, 1); if (results.empty()) return false; const OrderingChoice& choice = results[0]; checkError(choice.first == object, choice.first->toString() << " != " << object->toString()); TokenId p = choice.second.first; TokenId s = choice.second.second; TREX_INFO("trex:debug:synchronization:insertToken", m_core->nameString() << "Inserting " << token->toString()); object->constrain(p, s); m_core->propagate(); TREX_INFO_COND(m_core->isInvalid(), "trex:debug:synchronization:insertToken", m_core->nameString() << "Inconsistent after inserting " << token->toString()); const TokenSet& slaves = token->slaves(); for(TokenSet::const_iterator it = slaves.begin(); it != slaves.end(); ++it){ if(m_core->isInvalid()) return false; TokenId slave = *it; TokenId merge_candidate; if(!inSynchScope(slave, merge_candidate)) continue; stepCount++; if(!resolveToken(slave, stepCount, merge_candidate)) return false; } return true; } /** * @brief Iterates over all internal timelines. If it finds a gap at the current execution frontier, it will allocate * and insert an 'undefined' token which starts at this tick, and whose end is open. */ bool Synchronizer::completeInternalTimelines(unsigned int& stepCount){ if(m_core->isInvalid()) return false; TREX_INFO("trex:debug:synchronization:completeInternalTimelines", m_core->nameString() << "START"); unsigned int max_i = m_core->m_internalTimelineTable.size(); TICK tick = m_core->getCurrentTick(); for(unsigned int i = 0; i < max_i; i++){ TimelineId timeline = m_core->m_internalTimelineTable[i].first; const std::list<TokenId>& tokens = timeline->getTokenSequence(); // Advance the iterator to the execution frontier std::list<TokenId>::const_iterator it = tokens.begin(); TokenId token; while(it != tokens.end()){ TokenId candidate = *it; TREX_INFO("trex:debug:synchronization:completeInternalTimelines", m_core->nameString() << "Evaluating " << candidate->toString() << " for processing at the execution frontier"); // Terminate if we have moved past tao if(candidate->start()->lastDomain().getLowerBound() > tick) break; // Terminate, selecting the candidate, if it contains tao if(candidate->start()->lastDomain().getLowerBound() <= tick && candidate->end()->lastDomain().getUpperBound() > tick){ TREX_INFO("trex:debug:synchronization:completeInternalTimelines", m_core->nameString() << candidate->toString() << " has been selected for processing at the execution frontier"); token = candidate; break; } ++it; } // If no token, then we must insert if(token.isNoId()){ if(!insertDefaultValue(timeline, stepCount)) return false; continue; } // If the end time exceeds the current tick, the token can be extended if(token->start()->lastDomain().getUpperBound() < tick && token->end()->lastDomain().getUpperBound() > tick) m_core->extendCurrentValue(token); else // We should start the next token token->start()->specify(tick); // Propagate since we have restricted the database and this can have knock-on effects if(!m_core->propagate()) return false; } TREX_INFO("trex:debug:synchronization:completeInternalTimelines", m_core->nameString() << "END"); return true; } /** * @brief Insert a new undefined token relative to the given token */ bool Synchronizer::insertDefaultValue(const TimelineId& timeline, unsigned int& stepCount){ static const int sl_defaultPredicateIndex(1); // Mode is first. // Allocate a token - it should be inactive but not rejectable. We are definitievly setting the state // to undefined, though we may merge in doing so. std::string predicate = timeline->getType().toString(); ConstrainedVariableId defaultPredicateName = timeline->getVariables()[sl_defaultPredicateIndex]; checkError(defaultPredicateName.isValid(), "Invalid NDDL class for " << timeline->toString()); checkError(defaultPredicateName->lastDomain().isSingleton(), defaultPredicateName->toString()); LabelStr predLabel = (LabelStr) defaultPredicateName->lastDomain().getSingletonValue(); predicate += "."; predicate += predLabel.toString(); TREX_INFO("trex:debug:synchronization:insertDefaultValue", m_core->nameString() << "Insert " << predicate << " On " << timeline->toString()); TokenId token = m_db->getClient()->createToken(predicate.c_str(), DbCore::NOT_REJECTABLE); token->activate(); token->start()->restrictBaseDomain(IntervalIntDomain(m_core->getCurrentTick(), m_core->getCurrentTick())); token->end()->restrictBaseDomain(IntervalIntDomain(m_core->getCurrentTick() + 1, PLUS_INFINITY)); token->getObject()->specify(timeline); return insertToken(token, stepCount); } /** * @see TREX.nddl for definition of parameters of AgentTimeline */ bool Synchronizer::isPersistent(const TokenId& token){ if(token->getObject()->lastDomain().isSingleton()){ ObjectId object = token->getObject()->lastDomain().getSingletonValue(); if(token->getPlanDatabase()->getSchema()->isA(object->getType(), Agent::TIMELINE())){ ConstrainedVariableId mode = object->getVariables()[2]; if(mode->lastDomain().isMember(true)) return true; } } return false; } std::string Synchronizer::propagationFailure() const { std::stringstream ss; ConstraintEngineId ce = m_db->getConstraintEngine(); if(!ce->constraintConsistent()){ ss << "Constraint Network is inconsistent. " << std::endl; const ConstrainedVariableSet& variables = ce->getVariables(); for(ConstrainedVariableSet::const_iterator v_it = variables.begin(); v_it != variables.end(); ++v_it){ ConstrainedVariableId var = *v_it; if(var->lastDomain().isEmpty() && var->lastDomain().isClosed()){ ss << localContextForConstrainedVariable(var); } } } return ss.str(); } std::string Synchronizer::tokenResolutionFailure(const TokenId& tokenToResolve, const TokenId& merge_candidate) const { std::stringstream ss; ss << "Failed to resolve " << tokenToResolve->toString() << std::endl << tokenToResolve->toLongString() << std::endl << std::endl << "Analysis results below" << std::endl << std::endl; if(m_core->isObservation(tokenToResolve)){ ss << tokenToResolve->toString() << " is an observation." << std::endl; } if(tokenToResolve->master().isId()){ const TokenId master = tokenToResolve->master(); ss << tokenToResolve->toString() << " is implied by the model and a slave of " << master->toString() << std::endl << std::endl; } // If the network is inconsistent then we want to analyze the neighborhood of the empty variable if(!m_db->getConstraintEngine()->constraintConsistent()){ ss << propagationFailure(); } else if(merge_candidate.isId()){ ss << merge_candidate->toString() << " is not compatible in database below:" << std::endl; ss << PlanDatabaseWriter::toString(m_db) << std::endl; } else { ss << "No compatible tokens and no locations for insertion." << std::endl; // Output an analysis of the blocking token, if there is one. ss << analysisOfBlockingToken(tokenToResolve); ss << std::endl << "Current Partial Plan:" << std::endl; ss << PlanDatabaseWriter::toString(m_db) << std::endl; } return ss.str(); } std::string Synchronizer::localContextForConstrainedVariable(const ConstrainedVariableId& var) const { std::stringstream ss; ss << std::endl << "Local context for variable " << var->getName().toString() << "(" << var->getKey() << "):" << std::endl << "Base Domain is:" << var->baseDomain().toString() << std::endl << "Derived domain is:" << var->lastDomain().toString() << std::endl << std::endl; TokenId token = getParentToken(var); if(token.isId()) ss << "Variable belongs to :" << PlanDatabaseWriter::simpleTokenSummary(token); else ss << "Variable does not belong to any token."; ss << std::endl << std::endl; ConstraintSet constraints; ConstrainedVariableSet variables; TokenSet tokens; var->constraints(constraints); for(ConstraintSet::const_iterator c_it = constraints.begin(); c_it != constraints.end(); ++c_it){ ConstraintId constraint = *c_it; const std::vector<ConstrainedVariableId>& scope = constraint->getScope(); for(unsigned int i=0; i<scope.size(); i++){ variables.insert(scope[i]); TokenId parent = getParentToken(scope[i]); if(parent.isId()) tokens.insert(parent); } } ss << "Related Tokens: " << std::endl; for(TokenSet::const_iterator t_it = tokens.begin(); t_it != tokens.end(); ++t_it){ TokenId token = *t_it; ss << " " << PlanDatabaseWriter::simpleTokenSummary(token) << std::endl; } ss << std::endl << "Related Variables:" << std::endl; for(ConstrainedVariableSet::const_iterator it = variables.begin(); it != variables.end(); ++it){ ConstrainedVariableId v = *it; ss << " " << v->getName().toString() << "(" << v->getKey() << ")"; TokenId parent = getParentToken(v); if(parent.isId()) ss << " of " << PlanDatabaseWriter::simpleTokenSummary(parent); ss << std::endl; } ss << std::endl << "Related Constraints: " << std::endl; for(ConstraintSet::const_iterator c_it = constraints.begin(); c_it != constraints.end(); ++c_it){ ConstraintId constraint = *c_it; ss << constraint->toString() << std::endl << std::endl ; } return ss.str(); } std::string Synchronizer::tokenExtensionFailure(const TokenId& expectedToken) const{ std::stringstream ss; ss << "Expected to have a value given by:" << expectedToken->toString() << " which starts at " << expectedToken->start()->lastDomain().toString() << " and ends at " << expectedToken->end()->lastDomain().toString() << std::endl; // The tmepoint of interest is the start or end at the current tick ConstrainedVariableId timepointOfInterest; if(expectedToken->start()->lastDomain().isSingleton() && expectedToken->start()->lastDomain().getSingletonValue() == m_core->getCurrentTick()) timepointOfInterest = expectedToken->start(); else timepointOfInterest = expectedToken->end(); // Output the local context for this timepoint" ss << localContextForConstrainedVariable(timepointOfInterest); return ss.str(); } /** * Search for the location in the database where this token would like to be and see which * tokens are present and why there is no merge possible. */ std::string Synchronizer::analysisOfBlockingToken(const TokenId& tokenToResolve) const { std::stringstream ss; const TokenSet& activeTokens = m_db->getActiveTokens(tokenToResolve->getPredicateName()); const AbstractDomain& startDom = tokenToResolve->start()->lastDomain(); const AbstractDomain& endDom = tokenToResolve->end()->lastDomain(); for(TokenSet::const_iterator it = activeTokens.begin(); it != activeTokens.end(); ++it){ TokenId token = *it; // Skip if it is this token if(token == tokenToResolve) continue; if(!token->getObject()->lastDomain().intersects(tokenToResolve->getObject()->lastDomain())) continue; // Report the token if it overalps in time but does not allow merging if(token->start()->lastDomain().intersects(startDom) && token->end()->lastDomain().intersects(endDom)){ ss << "Found a conflict with " << token->toLongString() << std::endl << std::endl; std::vector<ConstrainedVariableId> p_a = token->parameters(); std::vector<ConstrainedVariableId> p_b = tokenToResolve->parameters(); for(unsigned int i = 0; i < p_a.size(); i++){ ConstrainedVariableId v_a = p_a[i]; ConstrainedVariableId v_b = p_b[i]; if(!v_a->lastDomain().intersects(v_b->lastDomain())) ss << " " << v_a->toLongString() << " conflicts with " << v_b->toLongString() << std::endl; } ss << std::endl; break; } } return ss.str(); } /** * @brief Accessor to debug stream for debug output */ std::ostream& Synchronizer::getStream(){ return m_core->getStream(); } }
40.57801
182
0.684094
[ "object", "vector", "model" ]
fcd65227c2be60a84b43f0e44f033859321d8a9b
4,322
cc
C++
scrypt.cc
cheongwy/node-scrypt
638e5c50c491d959fec0b14c402f1eb23bc2849e
[ "MIT" ]
2
2015-04-30T17:16:34.000Z
2017-03-20T10:08:55.000Z
scrypt.cc
cheongwy/node-scrypt
638e5c50c491d959fec0b14c402f1eb23bc2849e
[ "MIT" ]
null
null
null
scrypt.cc
cheongwy/node-scrypt
638e5c50c491d959fec0b14c402f1eb23bc2849e
[ "MIT" ]
null
null
null
#include <v8.h> #include <node.h> #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <openssl/sha.h> #include <openssl/hmac.h> #include <openssl/evp.h> #include <openssl/bio.h> #include <openssl/buffer.h> // link as C since we compile as C and not C++ // see wscript extern "C" { #include <crypto_scrypt.h> } #include <iostream> using namespace std; using namespace node; using namespace v8; #define ENCBLOCK 65536 static int getsalt(uint8_t salt[32]); static char *base64(const unsigned char *input, int length); static char *unbase64(unsigned char *input, int length); static std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len); static Handle<Value> Encrypt(const Arguments& args) { HandleScope scope; const char *usage = "usage: encrypt(passwd)"; if (args.Length() != 1) { return ThrowException(Exception::Error(String::New(usage))); } Local<String> password = args[0]->ToString(); String::Utf8Value passwd(password); //printf ("Incoming password: [%s]\n",*passwd); int len = 32; uint8_t dk[len]; size_t buflen = len; int N = 1024; int r = 8; int p = 8; String::Utf8Value salt(String::New("")); const char *salt_err_msg = "Unable to obtain salt"; int rc; // if ((rc = getsalt(salt)) != 0) // return ThrowException(Exception::Error(String::New(salt_err_msg))); // printf ("Salt: [%s]\n", base64(salt,32)); const char *enc_err_msg = "An error occured when encrypting password"; if( rc = crypto_scrypt((uint8_t *)*passwd, strlen(*passwd), (uint8_t *)*salt, strlen(*salt), N, r, p, dk, buflen)!=0) return ThrowException(Exception::Error(String::New(enc_err_msg))); //int ret = scryptenc_buf(inbuf, inbuflen, outbuf, passwd, passwdlen, maxmem, maxmem_frac, maxtime); std::string encrypted = base64_encode(dk, len); //char * encrypted = base64(dk, len); //printf ("[%s] is the encrypted password\n",encrypted); std::cout << "encoded: " << encrypted << std::endl; Local<String> result = String::New(encrypted.c_str()); return scope.Close(result); } static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) { std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i <4) ; i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for(j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while((i++ < 3)) ret += '='; } return ret; } /* Not used. Unless we want to store the random salts along with the password */ static int getsalt(uint8_t salt[32]) { int fd; ssize_t lenread; uint8_t * buf = salt; size_t buflen = 32; /* Open /dev/urandom. */ if ((fd = open("/dev/urandom", O_RDONLY)) == -1) goto err0; /* Read bytes until we have filled the buffer. */ while (buflen > 0) { if ((lenread = read(fd, buf, buflen)) == -1) goto err1; /* The random device should never EOF. */ if (lenread == 0) goto err1; /* We're partly done. */ buf += lenread; buflen -= lenread; } /* Close the device. */ while (close(fd) == -1) { if (errno != EINTR) goto err0; } /* Success! */ return (0); err1: close(fd); err0: /* Failure! */ return (4); } extern "C" void init(Handle<Object> target) { //Scrypt::Initialize(target); HandleScope scope; //target->Set(String::NewSymbol("Scrypt"), String::New("Hello Scrypt")); NODE_SET_METHOD(target, "encrypt", Encrypt); }
24.418079
118
0.643452
[ "object" ]
fce27e8689ca8d1567e60b72394ea7e7c8e4fa1e
1,408
cpp
C++
example/DMRG/dmrg_tfim.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
11
2020-04-14T15:45:42.000Z
2022-03-31T14:37:03.000Z
example/DMRG/dmrg_tfim.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
38
2019-08-02T15:15:51.000Z
2022-03-04T19:07:02.000Z
example/DMRG/dmrg_tfim.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
7
2019-07-17T07:50:55.000Z
2021-07-03T06:44:52.000Z
#include "cytnx.hpp" using namespace std; using namespace cytnx; Scalar run_DMRG(tn_algo::MPO &mpo, tn_algo::MPS &mps, int Nsweeps, std::vector<tn_algo::MPS> ortho_mps={}, double weight=40){ auto model = tn_algo::DMRG(mpo,mps,ortho_mps,weight); model.initialize(); Scalar E; for(int xi=0;xi<Nsweeps; xi++){ E = model.sweep(); cout << "sweep " << xi << "/" << Nsweeps << " | Enr: " << E << endl; } return E; } int main(){ int Nsites = 10; int chi = 16; double weight = 40; double h = 4; int Nsweeps = 10; //construct MPO: auto sz = cytnx::physics::pauli("z").real(); auto sx = cytnx::physics::pauli("x").real(); auto II = cytnx::eye(2); auto tM = cytnx::zeros({3,3,2,2}); tM(0,0) = II; tM(-1,-1) = II; tM(0,2) = -h*sx; tM(0,1) = -sz; tM(1,2) = sz; auto uM = UniTensor(tM,0); auto mpo = tn_algo::MPO(); mpo.assign(Nsites,uM); // starting DMRG: auto mps0 = tn_algo::MPS(Nsites,2,chi); Scalar E0 = run_DMRG(mpo,mps0,Nsweeps); // first excited auto mps1 = tn_algo::MPS(Nsites,2,chi); Scalar E1 = run_DMRG(mpo,mps1,Nsweeps,{mps0},weight=60); // second excited. auto mps2 = tn_algo::MPS(Nsites,2,chi); Scalar E2 = run_DMRG(mpo,mps2,Nsweeps,{mps0,mps1},weight=60); cout << E0 << endl; cout << E1 << endl; cout << E2 << endl; return 0; }
23.081967
125
0.5625
[ "vector", "model" ]
fce81e748958d7e8d111cd89d820749d97203ce5
4,674
cc
C++
native/pwm.cc
melizalab/decide
057bf49ee745c4c47e75698e2453705b700f4e41
[ "BSD-3-Clause" ]
1
2020-07-28T22:35:15.000Z
2020-07-28T22:35:15.000Z
native/pwm.cc
bjoring/decide
057bf49ee745c4c47e75698e2453705b700f4e41
[ "BSD-3-Clause" ]
19
2015-02-25T23:03:42.000Z
2019-06-20T02:12:51.000Z
native/pwm.cc
bjoring/decide
057bf49ee745c4c47e75698e2453705b700f4e41
[ "BSD-3-Clause" ]
1
2019-11-08T18:06:35.000Z
2019-11-08T18:06:35.000Z
/* * node.js addon for PRU PWM control * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Copyright (C) 2015 C Daniel Meliza <dan || meliza.org> */ #include <string> #include <unistd.h> // node headers #include <node.h> #include <v8.h> #include "pruss_pwm.hh" using namespace v8; static pruss::pwm PWM(50); inline Handle<Value> throw_exception(char const * arg) { return ThrowException(Exception::Error(String::New(arg))); } /** Load a program in the PRU and run it */ Handle<Value> start(const Arguments& args) { HandleScope scope; // check arguments if (args.Length() != 1 || !args[0]->IsString()) { return throw_exception("start() requires one string argument"); } //Get a C++ string String::Utf8Value program(args[0]->ToString()); std::string programS = std::string(*program); PWM.start(programS.c_str()); usleep(1); if (!PWM.running()) return throw_exception("failed to run program - check path"); return scope.Close(Undefined()); } Handle<Value> period(const Arguments& args) { HandleScope scope; double usec; // PRU loop is 4 instructions except on cycles where the GPIO is flipped // on, so the actual period is going to be 4*_pruDataMem0[1] + 2 + 9. PRU // clock is 200 MHz, so instructions are 5 ns if (args.Length() > 0) { if (!args[0]->IsNumber()) { return throw_exception("period() takes 0 or 1 numeric argument"); } usec = args[0]->ToNumber()->Value(); PWM.period(usec); } return scope.Close(Number::New(PWM.period())); } Handle<Value> duty(const Arguments& args) { HandleScope scope; unsigned int idx; double duty; if (args.Length() == 0) { return throw_exception("duty() requires 1 or two arguments"); } if (!args[0]->IsNumber()) { return throw_exception("first argument must be an unsigned integer"); } idx = args[0]->ToUint32()->Value(); if (idx >= pruss::pwm::n_pwms) { return throw_exception("invalid PWM index"); } if (args.Length() > 1) { if (!args[1]->IsNumber()) { return throw_exception("arg 2 must be a float between 0 and 100"); } duty = args[1]->ToNumber()->Value(); PWM.duty(idx, duty); } return scope.Close(Number::New(PWM.duty(idx))); } Handle<Value> pulse_hold(const Arguments& args) { HandleScope scope; unsigned int idx; double duration; double pulse, hold; // argument boilerplate if (args.Length() < 4) { return throw_exception("pulse_hold(idx, pulse_duty, pulse_dur, hold_duty)"); } for (int i = 0; i < 4; ++i) { if (!args[i]->IsNumber()) return throw_exception("arguments must be numbers"); } idx = args[0]->ToUint32()->Value(); pulse = args[1]->ToNumber()->Value(); duration = args[2]->ToNumber()->Value(); hold = args[3]->ToNumber()->Value(); if (idx >= pruss::pwm::n_pwms) return throw_exception("invalid PWM index"); if (pulse < 0 || pulse > 100) return throw_exception("pulse duty cycle must be between [0, 100]"); if (hold < 0 || hold > 100) return throw_exception("hold duty cycle must be between [0, 100]"); if (duration <= 0) return throw_exception("duration must be greater than zero"); PWM.duty(idx, pulse); // pulses should be short - okay to hold the interpreter? usleep(duration * 1000); PWM.duty(idx, hold); return scope.Close(Undefined()); } void Init(Handle<Object> exports) { exports->Set(String::NewSymbol("start"), FunctionTemplate::New(start)->GetFunction()); exports->Set(String::NewSymbol("period"), FunctionTemplate::New(period)->GetFunction()); exports->Set(String::NewSymbol("duty"), FunctionTemplate::New(duty)->GetFunction()); exports->Set(String::NewSymbol("pulse"), FunctionTemplate::New(pulse_hold)->GetFunction()); } NODE_MODULE(pwm, Init)
33.148936
92
0.562473
[ "object" ]
fce9356308963dafd74573ab89cd2e8d77a5a933
6,385
cpp
C++
catkin_ws/src/srrg2_laser_slam_2d/srrg2_laser_slam_2d/apps/visual_test_scene_clipper_projective_2d.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
null
null
null
catkin_ws/src/srrg2_laser_slam_2d/srrg2_laser_slam_2d/apps/visual_test_scene_clipper_projective_2d.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
null
null
null
catkin_ws/src/srrg2_laser_slam_2d/srrg2_laser_slam_2d/apps/visual_test_scene_clipper_projective_2d.cpp
laaners/progetto-labiagi_pick_e_delivery
3453bfbc1dd7562c78ba06c0f79b069b0a952c0e
[ "MIT" ]
null
null
null
#include <iomanip> #include <iostream> #include <signal.h> #include "srrg2_laser_slam_2d/mapping/scene_clipper_projective_2d.h" #include "srrg2_laser_slam_2d/sensor_processing/raw_data_preprocessor_projective_2d.h" #include <srrg_data_structures/platform.h> #include <srrg_messages/instances.h> #include <srrg_pcl/instances.h> #include <srrg_qgl_viewport/viewer_core_shared_qgl.h> #include <srrg_system_utils/parse_command_line.h> #include <srrg_system_utils/shell_colors.h> #include <srrg_system_utils/system_utils.h> #include <srrg_messages/message_handlers/message_file_source.h> #include <srrg_messages/messages/point_cloud2_message.h> using namespace srrg2_core; using namespace srrg2_laser_slam_2d; const std::string exe_name = "SRRG_LASER_SLAM_2D.visual_test_scene_clipper_projective_2d"; #define LOG std::cerr << exe_name + "|" void process(MessageFileSourcePtr src_, const ViewerCanvasPtr& canvas_); int main(int argc, char** argv) { srrg2_core::point_cloud_registerTypes(); srrg2_core::messages_registerTypes(); ParseCommandLine cmd(argv); ArgumentString arg_config_filename(&cmd, "c", "config", "config file path", "laser_config.conf"); ArgumentString arg_message(&cmd, "m", "message", "module you want to create, choose between {System, Tracker, Aligner}", "laser_messages.boss"); cmd.parse(); MessageFileSourcePtr src(new MessageFileSource); src->open(arg_message.value()); QApplication qapp(argc, argv); srrg2_qgl_viewport::ViewerCoreSharedQGL viewer_core(argc, argv, &qapp); const ViewerCanvasPtr& canvas = viewer_core.getCanvas(exe_name); srrg2_qgl_viewport::ViewerCoreSharedQGL::stop(); std::thread processing_t(process, src, canvas); viewer_core.startViewerServer(); processing_t.join(); src->close(); return 0; } void process(MessageFileSourcePtr src_, const ViewerCanvasPtr& canvas_) { while (!srrg2_qgl_viewport::ViewerCoreSharedQGL::isRunning()) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } srrg2_core::BaseSensorMessagePtr msg; RawDataPreprocessorProjective2DPtr meas_adaptor(new RawDataPreprocessorProjective2D); std::vector<RawDataPreprocessorProjective2D::MeasurementType> adapted_meas; StdVectorEigenIsometry3f odoms; std::string sensor_frame; std::string base_frame; Point3fVectorCloud pc3d; PointNormal2fVectorCloud global_scene; PointNormal2fVectorCloud local_scene0, local_scene1; Platform platform; srrg2_slam_interfaces::TrackerReportRecord report_record; while ((msg = src_->getMessage())) { report_record.clear(); platform.add(msg); if (PointCloud2MessagePtr casted_msg = std::dynamic_pointer_cast<PointCloud2Message>(msg)) { casted_msg->getPointCloud(pc3d); global_scene.reserve(pc3d.size()); for (const auto& p : pc3d) { PointNormal2f pn; pn.coordinates().x() = p.coordinates().x(); pn.coordinates().y() = p.coordinates().y(); global_scene.emplace_back(pn); } NormalComputator1DSlidingWindowNormal normal_computator; normal_computator.computeNormals(global_scene); continue; } if (LaserMessagePtr casted_msg = std::dynamic_pointer_cast<LaserMessage>(msg)) { RawDataPreprocessorProjective2D::MeasurementType cloud; meas_adaptor->setMeas(&cloud); if (meas_adaptor->setRawData(msg, report_record)) { meas_adaptor->compute(); adapted_meas.push_back(cloud); } continue; } if (OdometryMessagePtr casted_msg = std::dynamic_pointer_cast<OdometryMessage>(msg)) { odoms.push_back(casted_msg->pose.value()); } } platform.isWellFormed(); std::cerr << platform << std::endl; Isometry3f s_pose = Isometry3f::Identity(); platform.getTransform(s_pose, "/scan", "/base_frame"); Isometry2f sensor_in_world = geometry3d::get2dFrom3dPose(odoms[0] * s_pose); SceneClipperProjective2DPtr clipper(new SceneClipperProjective2D); clipper->param_projector->param_angle_col_min.setValue(-M_PI_2); clipper->param_projector->param_angle_col_max.setValue(M_PI_2); clipper->setFullScene(&global_scene); clipper->setClippedSceneInRobot(&local_scene0); clipper->setRobotInLocalMap(sensor_in_world); clipper->compute(); sensor_in_world = geometry3d::get2dFrom3dPose(odoms[1] * s_pose); clipper->setClippedSceneInRobot(&local_scene1); clipper->setRobotInLocalMap(sensor_in_world); clipper->compute(); // local scene is in sensor's reference frame while (srrg2_qgl_viewport::ViewerCoreSharedQGL::isRunning()) { { canvas_->pushColor(); // push color canvas_->setColor(srrg2_core::ColorPalette::color3fBlack()); canvas_->pushPointSize(); // push point size canvas_->setPointSize(1); canvas_->putPoints(pc3d); canvas_->popAttribute(); // pop point size canvas_->popAttribute(); // pop color } { canvas_->multMatrix(odoms[0].matrix()); canvas_->pushMatrix(); canvas_->putReferenceSystem(.5); { canvas_->multMatrix(s_pose.matrix()); canvas_->pushMatrix(); canvas_->putReferenceSystem(.25); { canvas_->pushColor(); // push color canvas_->setColor(srrg2_core::ColorPalette::color3fBlue()); canvas_->pushPointSize(); // push point size canvas_->setPointSize(3); canvas_->putPoints(local_scene0); canvas_->popAttribute(); // pop point size canvas_->popAttribute(); // pop color } canvas_->popMatrix(); } canvas_->popMatrix(); } { canvas_->multMatrix(odoms[1].matrix()); canvas_->pushMatrix(); canvas_->putReferenceSystem(1); { canvas_->multMatrix(s_pose.matrix()); canvas_->pushMatrix(); canvas_->putReferenceSystem(.25); { canvas_->pushColor(); // push color canvas_->setColor(srrg2_core::ColorPalette::color3fGreen()); canvas_->pushPointSize(); // push point size canvas_->setPointSize(5); canvas_->putPoints(local_scene1); canvas_->popAttribute(); // pop point size canvas_->popAttribute(); // pop color } canvas_->popMatrix(); } canvas_->popMatrix(); } canvas_->flush(); } }
32.576531
100
0.694283
[ "vector" ]
fcebbdd84f2941cec568a2eefd55163264f4640f
627
cpp
C++
src/algo/leetcode/0320_generateAbbreviations.cpp
donaldcao/simpleS
c3f74ae5de985be30d6fae8749b59485d44c3d88
[ "MIT" ]
3
2019-01-19T04:48:12.000Z
2019-06-15T01:06:32.000Z
src/algo/leetcode/0320_generateAbbreviations.cpp
donaldcao/hello-world
c3f74ae5de985be30d6fae8749b59485d44c3d88
[ "MIT" ]
2
2019-01-19T12:03:03.000Z
2019-06-15T01:46:02.000Z
src/algo/leetcode/0320_generateAbbreviations.cpp
donaldcao/simpleS
c3f74ae5de985be30d6fae8749b59485d44c3d88
[ "MIT" ]
null
null
null
#include <string> #include <vector> using namespace std; class Solution{ public: vector<string> generateAbbreviations(string word) { vector<string> res{word}; helper(word, 0, res); return res; } void helper(string word, int pos, vector<string> &res) { for(int i = pos; i < word.size(); ++i) { for(int j = 1; i + j <= word.size(); ++j) { string t = word.substr(0, i); t += to_string(j) + word.substr(i+j); res.push_back(t); helper(t, i + 1 + to_string(j).size(), res); } } } };
26.125
60
0.491228
[ "vector" ]
fcecc464d07e83a7291d31a521495edc2d994bf5
3,606
cpp
C++
RTIDPRR/Source/Graphics/Core/CommandPool.cpp
brunosegiu/RTIDPRR
d7daef7611899db4e23ba6a2b5a91135c57e0871
[ "MIT" ]
3
2020-12-06T02:22:48.000Z
2021-06-24T13:52:10.000Z
RTIDPRR/Source/Graphics/Core/CommandPool.cpp
brunosegiu/RTIDPRR
d7daef7611899db4e23ba6a2b5a91135c57e0871
[ "MIT" ]
null
null
null
RTIDPRR/Source/Graphics/Core/CommandPool.cpp
brunosegiu/RTIDPRR
d7daef7611899db4e23ba6a2b5a91135c57e0871
[ "MIT" ]
1
2021-10-13T10:36:36.000Z
2021-10-13T10:36:36.000Z
#include "CommandPool.h" #include "../../Misc/DebugUtils.h" #include "Command.h" #include "Context.h" using namespace RTIDPRR::Graphics; vk::CommandPool allocateCommandPool(const vk::Device& logicalDevice, uint32_t queueFamilyIndex) { vk::CommandPoolCreateInfo commandPoolCreateInfo = vk::CommandPoolCreateInfo() .setQueueFamilyIndex(queueFamilyIndex) .setFlags(vk::CommandPoolCreateFlagBits::eResetCommandBuffer); return RTIDPRR_ASSERT_VK( logicalDevice.createCommandPool(commandPoolCreateInfo)); } CommandPool::CommandPool(const vk::Device& logicalDevice, Queue::QueueIndices indices) { mGraphicsCommandPool = allocateCommandPool(logicalDevice, indices.graphicsQueueIndex); mComputeCommandPool = allocateCommandPool(logicalDevice, indices.computeQueueIndex); } Command* CommandPool::allocateGraphicsCommand() { return allocateCommand(mGraphicsCommandCache, mGraphicsCommandPool); } Command* CommandPool::allocateComputeCommand() { return allocateCommand(mComputeCommandCache, mComputeCommandPool); } Command* CommandPool::allocateCommand(CommandCache& commandCache, vk::CommandPool& commandPool) { Command* command = nullptr; if (commandCache.mUnusedCommands.size() > 0) { command = *commandCache.mUnusedCommands.begin(); commandCache.mUnusedCommands.erase(command); } else { const Device& device = Context::get().getDevice(); vk::CommandBufferAllocateInfo commandAllocInfo = vk::CommandBufferAllocateInfo() .setCommandPool(commandPool) .setLevel(vk::CommandBufferLevel::ePrimary) .setCommandBufferCount(1); std::vector<vk::CommandBuffer> commandBuffers = RTIDPRR_ASSERT_VK( device.getLogicalDeviceHandle().allocateCommandBuffers( commandAllocInfo)); command = new Command(commandBuffers[0]); } commandCache.mUsedCommands.emplace(command); return command; } void CommandPool::releaseCommand(Command* command) { if (mGraphicsCommandCache.mUsedCommands.find(command) != mGraphicsCommandCache.mUsedCommands.end()) { mGraphicsCommandCache.mUsedCommands.erase(command); mGraphicsCommandCache.mUnusedCommands.emplace(command); } else { mComputeCommandCache.mUsedCommands.erase(command); mComputeCommandCache.mUnusedCommands.emplace(command); } } CommandPool::~CommandPool() { const Device& device = Context::get().getDevice(); for (Command* command : mGraphicsCommandCache.mUsedCommands) { device.getLogicalDeviceHandle().freeCommandBuffers(mGraphicsCommandPool, *command); delete command; } for (Command* command : mGraphicsCommandCache.mUnusedCommands) { device.getLogicalDeviceHandle().freeCommandBuffers(mGraphicsCommandPool, *command); delete command; } device.getLogicalDeviceHandle().destroyCommandPool(mGraphicsCommandPool); for (Command* command : mComputeCommandCache.mUsedCommands) { device.getLogicalDeviceHandle().freeCommandBuffers(mComputeCommandPool, *command); delete command; } for (Command* command : mComputeCommandCache.mUnusedCommands) { device.getLogicalDeviceHandle().freeCommandBuffers(mComputeCommandPool, *command); delete command; } device.getLogicalDeviceHandle().destroyCommandPool(mComputeCommandPool); }
36.06
76
0.695785
[ "vector" ]
fced96e30c635c39a0c6d4127abd14b24c1dc1e9
2,796
cc
C++
src/main.cc
leovalais/raytracer
5dc8c486a190a8bb1c1b0cd4a6fc7579576fd5e1
[ "MIT" ]
null
null
null
src/main.cc
leovalais/raytracer
5dc8c486a190a8bb1c1b0cd4a6fc7579576fd5e1
[ "MIT" ]
null
null
null
src/main.cc
leovalais/raytracer
5dc8c486a190a8bb1c1b0cd4a6fc7579576fd5e1
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <string> #include "vec.hh" #include "printers.hh" #include "color.hh" #include "triangle.hh" #include "ray.hh" #include "scene.hh" #include "json-serializers.hh" #include "utils.hh" void cli_help(char* argv0) { std::cerr << "Usage: " << argv0 << " SCENE [OUT_IMAGE]\n" << "\tSCENE: a JSON file describing the scene to render (defaults to stdin" "when equals '-')\n" << "\tOUT_IMAGE: the name of the image to render (defaults to out.png)" << std::endl; } /* const auto print_normals = make_y_combinator([](auto rec, auto n) -> void { std::for_each(n.meshes.begin(), n.meshes.end(), [](auto m) { std::for_each(m.triangles.begin(), m.triangles.end(), [](auto t) { auto [a, b, c] = t.normals; std::cout << a << " " << b << " " << c << "\n"; }); }); std::for_each(n.children.begin(), n.children.end(), rec); }); print_normals(root); */ int main(int argc, char** argv) { if (argc == 1 or argc > 3) { cli_help(argv[0]); return 1; } const auto scene_file = std::filesystem::path{argv[1]}; nlohmann::json j; if (scene_file != "-") std::ifstream{scene_file} >> j; else std::cin >> j; auto scene = j.get<Scene>(); const auto out_file = argc == 3 ? argv[2] : "out.png"; std::cout << "Loading scene: " << scene_file << std::endl; scene.load(scene_file.parent_path()); const auto& root = scene.get_root_node(); const auto count_triangles = make_y_combinator([](const auto& recurse, const Node& node) -> size_t { return std::accumulate(node.meshes.begin(), node.meshes.end(), 0, [](const size_t& s, const Mesh& m) { return s + m.triangles.size(); }) + std::accumulate(node.children.begin(), node.children.end(), 0, [&recurse](const size_t& s, const Node& child) { return s + recurse(child); }); }); std::cout << "... contains " << count_triangles(root) << " triangles" << std::endl; std::cout << "Rendering scene..." << std::endl; auto image = scene.render(); std::cout << "Applying gamma correction..." << std::endl; image.gamma_correct(); std::cout << "Saving it into '" << out_file << "'..." << std::endl; image.save(out_file); return 0; }
37.783784
89
0.480329
[ "mesh", "render" ]
fceff59ab13435c66f7c6614b046141fdc522e10
1,828
cpp
C++
tests/test051.cpp
0x0c/rapidcsv
93e25e7c60c7fc435a1fcb24ee0e19d0fcc056e1
[ "BSD-3-Clause" ]
439
2017-05-20T09:08:04.000Z
2022-03-30T21:20:58.000Z
tests/test051.cpp
0x0c/rapidcsv
93e25e7c60c7fc435a1fcb24ee0e19d0fcc056e1
[ "BSD-3-Clause" ]
500
2020-09-15T09:45:10.000Z
2022-03-30T04:28:38.000Z
tests/test051.cpp
0x0c/rapidcsv
93e25e7c60c7fc435a1fcb24ee0e19d0fcc056e1
[ "BSD-3-Clause" ]
148
2017-10-09T01:30:31.000Z
2022-03-24T04:10:31.000Z
// test051.cpp - get column and row names #include <rapidcsv.h> #include "unittest.h" int main() { int rv = 0; std::string csv = "-,A,B,C\n" "1,3,9,81\n" "2,4,16,256\n" ; std::string path = unittest::TempPath(); unittest::WriteFile(path, csv); try { rapidcsv::Document doc(path, rapidcsv::LabelParams(0, 0)); std::vector<std::string> columnNames = doc.GetColumnNames(); unittest::ExpectEqual(size_t, columnNames.size(), 3); unittest::ExpectEqual(std::string, columnNames[0], "A"); unittest::ExpectEqual(std::string, columnNames[1], "B"); unittest::ExpectEqual(std::string, columnNames[2], "C"); std::vector<std::string> rowNames = doc.GetRowNames(); unittest::ExpectEqual(size_t, rowNames.size(), 2); unittest::ExpectEqual(std::string, rowNames[0], "1"); unittest::ExpectEqual(std::string, rowNames[1], "2"); rapidcsv::Document doc2(path, rapidcsv::LabelParams(0, -1)); std::vector<std::string> columnNames2 = doc2.GetColumnNames(); unittest::ExpectEqual(size_t, columnNames2.size(), 4); unittest::ExpectEqual(std::string, columnNames2[0], "-"); unittest::ExpectEqual(std::string, columnNames2[1], "A"); unittest::ExpectEqual(std::string, columnNames2[2], "B"); unittest::ExpectEqual(std::string, columnNames2[3], "C"); rapidcsv::Document doc3(path, rapidcsv::LabelParams(-1, 0)); std::vector<std::string> rowNames2 = doc3.GetRowNames(); unittest::ExpectEqual(size_t, rowNames2.size(), 3); unittest::ExpectEqual(std::string, rowNames2[0], "-"); unittest::ExpectEqual(std::string, rowNames2[1], "1"); unittest::ExpectEqual(std::string, rowNames2[2], "2"); } catch (const std::exception& ex) { std::cout << ex.what() << std::endl; rv = 1; } unittest::DeleteFile(path); return rv; }
31.517241
66
0.650985
[ "vector" ]
fcf1ceba5c19ced166ea4e3f4f3217b061b3c635
4,844
cpp
C++
Algorithms/1307.VerbalArithmeticPuzzle/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/1307.VerbalArithmeticPuzzle/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/1307.VerbalArithmeticPuzzle/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
#include <algorithm> #include <array> #include <string> #include <unordered_map> #include <vector> #include "gtest/gtest.h" namespace { class Solution { public: bool isSolvable(std::vector<std::string> const &words, std::string const &result) const { size_t maxWordSize = 0; for (std::string const& word : words) maxWordSize = std::max(maxWordSize, word.size()); if ((result.size() < maxWordSize) || (result.size() - maxWordSize > 1)) return false; std::vector<std::string> destWords; std::string destResult; const int lettersCount = transformInput(words, result, destWords, destResult); std::vector<int> letterConstraints(lettersCount, 0); for (std::string const& destWord : destWords) { for (char ch : destWord) letterConstraints[ch - FirstChar] = 0b1111111111; } for (char ch : destResult) letterConstraints[ch - FirstChar] = 0b1111111111; for (std::string const& destWord : destWords) { if (destWord.size() > 1) letterConstraints[destWord.front() - FirstChar] = 0b1111111110; } if (destResult.size() > 1) letterConstraints[destResult.front() - FirstChar] = 0b1111111110; return processDigitPos(destWords, destResult, letterConstraints, 0, 0, 0); } private: constexpr static size_t FirstChar = 'A'; int transformInput(std::vector<std::string> const &sourceWords, std::string const &sourceResult, std::vector<std::string> &destWords, std::string &destResult) const { std::unordered_map<char, char> letterMap; char lettersCount = 0; for (std::string const& sourceWord : sourceWords) { for (char ch : sourceWord) { if (letterMap.count(ch) == 0) letterMap[ch] = FirstChar + (lettersCount++); } } for (char ch : sourceResult) { if (letterMap.count(ch) == 0) letterMap[ch] = FirstChar + (lettersCount++); } for (std::string const& sourceWord : sourceWords) { destWords.emplace_back(""); for (char ch : sourceWord) destWords.back().push_back(letterMap[ch]); } for (char ch : sourceResult) destResult.push_back(letterMap[ch]); return static_cast<int>(lettersCount); } bool canUseDigit(std::vector<int> const &letterConstraints, char letter, int digit) const { const int mask = 1 << digit; return (letterConstraints[letter - FirstChar] & mask) != 0; } std::vector<int> useDigit(std::vector<int> letterConstraints, char letter, int digit) const { const int mask = 1 << digit; const size_t letterIndex = letter - FirstChar; for (size_t index = 0; index < letterConstraints.size(); ++index) letterConstraints[index] = index == letterIndex ? mask : letterConstraints[index] & (~mask); return letterConstraints; } bool processDigitPos(std::vector<std::string> const &words, std::string const &result, std::vector<int> const &letterConstraints, size_t digitPos, size_t row, int sum) const { if (digitPos == result.size()) return sum == 0; if (row == words.size()) { const char letter = result[result.size() - 1 - digitPos]; return !canUseDigit(letterConstraints, letter, sum % 10) ? false : processDigitPos(words, result, useDigit(letterConstraints, letter, sum % 10), digitPos + 1, 0, sum / 10); } if (digitPos >= words[row].size()) return processDigitPos(words, result, letterConstraints, digitPos, row + 1, sum); for (int digit = 0; digit <= 9; ++digit) { const char letter = words[row][words[row].size() - 1 - digitPos]; if (canUseDigit(letterConstraints, letter, digit) && processDigitPos(words, result, useDigit(letterConstraints, letter, digit), digitPos, row + 1, sum + digit)) return true; } return false; } }; } namespace VerbalArithmeticPuzzleTask { TEST(VerbalArithmeticPuzzleTaskTests, Examples) { const Solution solution; ASSERT_EQ(true, solution.isSolvable({"SEND", "MORE"}, "MONEY")); ASSERT_EQ(true, solution.isSolvable({"SIX", "SEVEN", "SEVEN"}, "TWENTY")); ASSERT_EQ(true, solution.isSolvable({"THIS", "IS", "TOO"}, "FUNNY")); ASSERT_EQ(false, solution.isSolvable({"LEET", "CODE"}, "POINT")); } TEST(VerbalArithmeticPuzzleTaskTests, FromWrongAnswers) { const Solution solution; ASSERT_EQ(false, solution.isSolvable({"CBA", "CBA", "CBA", "CBA", "CBA"}, "EDD")); ASSERT_EQ(true, solution.isSolvable({"A", "B"}, "A")); } }
36.977099
184
0.603633
[ "vector" ]
fcf8aaf287c7587ba9abc5671a53d61f5f5cef0f
22,563
hpp
C++
include/Valve/VR/CVRChaperoneSetup.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
23
2020-08-07T04:09:00.000Z
2022-03-31T22:10:29.000Z
include/Valve/VR/CVRChaperoneSetup.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
6
2021-09-29T23:47:31.000Z
2022-03-30T20:49:23.000Z
include/Valve/VR/CVRChaperoneSetup.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
17
2020-08-20T19:36:52.000Z
2022-03-30T18:28:24.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: Valve.VR.IVRChaperoneSetup #include "Valve/VR/IVRChaperoneSetup.hpp" // Including type: System.IntPtr #include "System/IntPtr.hpp" // Including type: Valve.VR.HmdQuad_t #include "Valve/VR/HmdQuad_t.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" #include "extern/beatsaber-hook/shared/utils/typedefs-array.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: Valve::VR namespace Valve::VR { // Forward declaring type: EChaperoneConfigFile struct EChaperoneConfigFile; // Forward declaring type: HmdMatrix34_t struct HmdMatrix34_t; } // Forward declaring namespace: System::Text namespace System::Text { // Forward declaring type: StringBuilder class StringBuilder; } // Completed forward declares // Type namespace: Valve.VR namespace Valve::VR { // Forward declaring type: CVRChaperoneSetup class CVRChaperoneSetup; } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(Valve::VR::CVRChaperoneSetup); DEFINE_IL2CPP_ARG_TYPE(Valve::VR::CVRChaperoneSetup*, "Valve.VR", "CVRChaperoneSetup"); // Type namespace: Valve.VR namespace Valve::VR { // Size: 0xB0 #pragma pack(push, 1) // Autogenerated type: Valve.VR.CVRChaperoneSetup // [TokenAttribute] Offset: FFFFFFFF class CVRChaperoneSetup : public ::Il2CppObject { public: #ifdef USE_CODEGEN_FIELDS public: #else protected: #endif // private Valve.VR.IVRChaperoneSetup FnTable // Size: 0xA0 // Offset: 0x10 Valve::VR::IVRChaperoneSetup FnTable; // Field size check static_assert(sizeof(Valve::VR::IVRChaperoneSetup) == 0xA0); public: // Creating conversion operator: operator Valve::VR::IVRChaperoneSetup constexpr operator Valve::VR::IVRChaperoneSetup() const noexcept { return FnTable; } // Get instance field reference: private Valve.VR.IVRChaperoneSetup FnTable Valve::VR::IVRChaperoneSetup& dyn_FnTable(); // System.Void .ctor(System.IntPtr pInterface) // Offset: 0x1871D88 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static CVRChaperoneSetup* New_ctor(System::IntPtr pInterface) { static auto ___internal__logger = ::Logger::get().WithContext("Valve::VR::CVRChaperoneSetup::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<CVRChaperoneSetup*, creationType>(pInterface))); } // public System.Boolean CommitWorkingCopy(Valve.VR.EChaperoneConfigFile configFile) // Offset: 0x1871E90 bool CommitWorkingCopy(Valve::VR::EChaperoneConfigFile configFile); // public System.Void RevertWorkingCopy() // Offset: 0x1872124 void RevertWorkingCopy(); // public System.Boolean GetWorkingPlayAreaSize(ref System.Single pSizeX, ref System.Single pSizeZ) // Offset: 0x1872140 bool GetWorkingPlayAreaSize(ByRef<float> pSizeX, ByRef<float> pSizeZ); // public System.Boolean GetWorkingPlayAreaRect(ref Valve.VR.HmdQuad_t rect) // Offset: 0x1872164 bool GetWorkingPlayAreaRect(ByRef<Valve::VR::HmdQuad_t> rect); // public System.Boolean GetWorkingCollisionBoundsInfo(out Valve.VR.HmdQuad_t[] pQuadsBuffer) // Offset: 0x1872180 bool GetWorkingCollisionBoundsInfo(ByRef<::ArrayW<Valve::VR::HmdQuad_t>> pQuadsBuffer); // public System.Boolean GetLiveCollisionBoundsInfo(out Valve.VR.HmdQuad_t[] pQuadsBuffer) // Offset: 0x1872220 bool GetLiveCollisionBoundsInfo(ByRef<::ArrayW<Valve::VR::HmdQuad_t>> pQuadsBuffer); // public System.Boolean GetWorkingSeatedZeroPoseToRawTrackingPose(ref Valve.VR.HmdMatrix34_t pmatSeatedZeroPoseToRawTrackingPose) // Offset: 0x1872534 bool GetWorkingSeatedZeroPoseToRawTrackingPose(ByRef<Valve::VR::HmdMatrix34_t> pmatSeatedZeroPoseToRawTrackingPose); // public System.Boolean GetWorkingStandingZeroPoseToRawTrackingPose(ref Valve.VR.HmdMatrix34_t pmatStandingZeroPoseToRawTrackingPose) // Offset: 0x1872550 bool GetWorkingStandingZeroPoseToRawTrackingPose(ByRef<Valve::VR::HmdMatrix34_t> pmatStandingZeroPoseToRawTrackingPose); // public System.Void SetWorkingPlayAreaSize(System.Single sizeX, System.Single sizeZ) // Offset: 0x187256C void SetWorkingPlayAreaSize(float sizeX, float sizeZ); // public System.Void SetWorkingCollisionBoundsInfo(Valve.VR.HmdQuad_t[] pQuadsBuffer) // Offset: 0x1872588 void SetWorkingCollisionBoundsInfo(::ArrayW<Valve::VR::HmdQuad_t> pQuadsBuffer); // public System.Void SetWorkingSeatedZeroPoseToRawTrackingPose(ref Valve.VR.HmdMatrix34_t pMatSeatedZeroPoseToRawTrackingPose) // Offset: 0x18725B0 void SetWorkingSeatedZeroPoseToRawTrackingPose(ByRef<Valve::VR::HmdMatrix34_t> pMatSeatedZeroPoseToRawTrackingPose); // public System.Void SetWorkingStandingZeroPoseToRawTrackingPose(ref Valve.VR.HmdMatrix34_t pMatStandingZeroPoseToRawTrackingPose) // Offset: 0x18725CC void SetWorkingStandingZeroPoseToRawTrackingPose(ByRef<Valve::VR::HmdMatrix34_t> pMatStandingZeroPoseToRawTrackingPose); // public System.Void ReloadFromDisk(Valve.VR.EChaperoneConfigFile configFile) // Offset: 0x18725E8 void ReloadFromDisk(Valve::VR::EChaperoneConfigFile configFile); // public System.Boolean GetLiveSeatedZeroPoseToRawTrackingPose(ref Valve.VR.HmdMatrix34_t pmatSeatedZeroPoseToRawTrackingPose) // Offset: 0x1872604 bool GetLiveSeatedZeroPoseToRawTrackingPose(ByRef<Valve::VR::HmdMatrix34_t> pmatSeatedZeroPoseToRawTrackingPose); // public System.Void SetWorkingCollisionBoundsTagsInfo(System.Byte[] pTagsBuffer) // Offset: 0x1872620 void SetWorkingCollisionBoundsTagsInfo(::ArrayW<uint8_t> pTagsBuffer); // public System.Boolean GetLiveCollisionBoundsTagsInfo(out System.Byte[] pTagsBuffer) // Offset: 0x1872648 bool GetLiveCollisionBoundsTagsInfo(ByRef<::ArrayW<uint8_t>> pTagsBuffer); // public System.Boolean SetWorkingPhysicalBoundsInfo(Valve.VR.HmdQuad_t[] pQuadsBuffer) // Offset: 0x187295C bool SetWorkingPhysicalBoundsInfo(::ArrayW<Valve::VR::HmdQuad_t> pQuadsBuffer); // public System.Boolean GetLivePhysicalBoundsInfo(out Valve.VR.HmdQuad_t[] pQuadsBuffer) // Offset: 0x1872984 bool GetLivePhysicalBoundsInfo(ByRef<::ArrayW<Valve::VR::HmdQuad_t>> pQuadsBuffer); // public System.Boolean ExportLiveToBuffer(System.Text.StringBuilder pBuffer, ref System.UInt32 pnBufferLength) // Offset: 0x1872A24 bool ExportLiveToBuffer(System::Text::StringBuilder* pBuffer, ByRef<uint> pnBufferLength); // public System.Boolean ImportFromBufferToWorking(System.String pBuffer, System.UInt32 nImportFlags) // Offset: 0x1872E34 bool ImportFromBufferToWorking(::Il2CppString* pBuffer, uint nImportFlags); }; // Valve.VR.CVRChaperoneSetup #pragma pack(pop) static check_size<sizeof(CVRChaperoneSetup), 16 + sizeof(Valve::VR::IVRChaperoneSetup)> __Valve_VR_CVRChaperoneSetupSizeCheck; static_assert(sizeof(CVRChaperoneSetup) == 0xB0); } #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::CommitWorkingCopy // Il2CppName: CommitWorkingCopy template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Valve::VR::CVRChaperoneSetup::*)(Valve::VR::EChaperoneConfigFile)>(&Valve::VR::CVRChaperoneSetup::CommitWorkingCopy)> { static const MethodInfo* get() { static auto* configFile = &::il2cpp_utils::GetClassFromName("Valve.VR", "EChaperoneConfigFile")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "CommitWorkingCopy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{configFile}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::RevertWorkingCopy // Il2CppName: RevertWorkingCopy template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Valve::VR::CVRChaperoneSetup::*)()>(&Valve::VR::CVRChaperoneSetup::RevertWorkingCopy)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "RevertWorkingCopy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::GetWorkingPlayAreaSize // Il2CppName: GetWorkingPlayAreaSize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Valve::VR::CVRChaperoneSetup::*)(ByRef<float>, ByRef<float>)>(&Valve::VR::CVRChaperoneSetup::GetWorkingPlayAreaSize)> { static const MethodInfo* get() { static auto* pSizeX = &::il2cpp_utils::GetClassFromName("System", "Single")->this_arg; static auto* pSizeZ = &::il2cpp_utils::GetClassFromName("System", "Single")->this_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "GetWorkingPlayAreaSize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pSizeX, pSizeZ}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::GetWorkingPlayAreaRect // Il2CppName: GetWorkingPlayAreaRect template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Valve::VR::CVRChaperoneSetup::*)(ByRef<Valve::VR::HmdQuad_t>)>(&Valve::VR::CVRChaperoneSetup::GetWorkingPlayAreaRect)> { static const MethodInfo* get() { static auto* rect = &::il2cpp_utils::GetClassFromName("Valve.VR", "HmdQuad_t")->this_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "GetWorkingPlayAreaRect", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{rect}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::GetWorkingCollisionBoundsInfo // Il2CppName: GetWorkingCollisionBoundsInfo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Valve::VR::CVRChaperoneSetup::*)(ByRef<::ArrayW<Valve::VR::HmdQuad_t>>)>(&Valve::VR::CVRChaperoneSetup::GetWorkingCollisionBoundsInfo)> { static const MethodInfo* get() { static auto* pQuadsBuffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("Valve.VR", "HmdQuad_t"), 1)->this_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "GetWorkingCollisionBoundsInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pQuadsBuffer}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::GetLiveCollisionBoundsInfo // Il2CppName: GetLiveCollisionBoundsInfo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Valve::VR::CVRChaperoneSetup::*)(ByRef<::ArrayW<Valve::VR::HmdQuad_t>>)>(&Valve::VR::CVRChaperoneSetup::GetLiveCollisionBoundsInfo)> { static const MethodInfo* get() { static auto* pQuadsBuffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("Valve.VR", "HmdQuad_t"), 1)->this_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "GetLiveCollisionBoundsInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pQuadsBuffer}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::GetWorkingSeatedZeroPoseToRawTrackingPose // Il2CppName: GetWorkingSeatedZeroPoseToRawTrackingPose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Valve::VR::CVRChaperoneSetup::*)(ByRef<Valve::VR::HmdMatrix34_t>)>(&Valve::VR::CVRChaperoneSetup::GetWorkingSeatedZeroPoseToRawTrackingPose)> { static const MethodInfo* get() { static auto* pmatSeatedZeroPoseToRawTrackingPose = &::il2cpp_utils::GetClassFromName("Valve.VR", "HmdMatrix34_t")->this_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "GetWorkingSeatedZeroPoseToRawTrackingPose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pmatSeatedZeroPoseToRawTrackingPose}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::GetWorkingStandingZeroPoseToRawTrackingPose // Il2CppName: GetWorkingStandingZeroPoseToRawTrackingPose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Valve::VR::CVRChaperoneSetup::*)(ByRef<Valve::VR::HmdMatrix34_t>)>(&Valve::VR::CVRChaperoneSetup::GetWorkingStandingZeroPoseToRawTrackingPose)> { static const MethodInfo* get() { static auto* pmatStandingZeroPoseToRawTrackingPose = &::il2cpp_utils::GetClassFromName("Valve.VR", "HmdMatrix34_t")->this_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "GetWorkingStandingZeroPoseToRawTrackingPose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pmatStandingZeroPoseToRawTrackingPose}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::SetWorkingPlayAreaSize // Il2CppName: SetWorkingPlayAreaSize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Valve::VR::CVRChaperoneSetup::*)(float, float)>(&Valve::VR::CVRChaperoneSetup::SetWorkingPlayAreaSize)> { static const MethodInfo* get() { static auto* sizeX = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; static auto* sizeZ = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "SetWorkingPlayAreaSize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sizeX, sizeZ}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::SetWorkingCollisionBoundsInfo // Il2CppName: SetWorkingCollisionBoundsInfo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Valve::VR::CVRChaperoneSetup::*)(::ArrayW<Valve::VR::HmdQuad_t>)>(&Valve::VR::CVRChaperoneSetup::SetWorkingCollisionBoundsInfo)> { static const MethodInfo* get() { static auto* pQuadsBuffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("Valve.VR", "HmdQuad_t"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "SetWorkingCollisionBoundsInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pQuadsBuffer}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::SetWorkingSeatedZeroPoseToRawTrackingPose // Il2CppName: SetWorkingSeatedZeroPoseToRawTrackingPose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Valve::VR::CVRChaperoneSetup::*)(ByRef<Valve::VR::HmdMatrix34_t>)>(&Valve::VR::CVRChaperoneSetup::SetWorkingSeatedZeroPoseToRawTrackingPose)> { static const MethodInfo* get() { static auto* pMatSeatedZeroPoseToRawTrackingPose = &::il2cpp_utils::GetClassFromName("Valve.VR", "HmdMatrix34_t")->this_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "SetWorkingSeatedZeroPoseToRawTrackingPose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pMatSeatedZeroPoseToRawTrackingPose}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::SetWorkingStandingZeroPoseToRawTrackingPose // Il2CppName: SetWorkingStandingZeroPoseToRawTrackingPose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Valve::VR::CVRChaperoneSetup::*)(ByRef<Valve::VR::HmdMatrix34_t>)>(&Valve::VR::CVRChaperoneSetup::SetWorkingStandingZeroPoseToRawTrackingPose)> { static const MethodInfo* get() { static auto* pMatStandingZeroPoseToRawTrackingPose = &::il2cpp_utils::GetClassFromName("Valve.VR", "HmdMatrix34_t")->this_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "SetWorkingStandingZeroPoseToRawTrackingPose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pMatStandingZeroPoseToRawTrackingPose}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::ReloadFromDisk // Il2CppName: ReloadFromDisk template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Valve::VR::CVRChaperoneSetup::*)(Valve::VR::EChaperoneConfigFile)>(&Valve::VR::CVRChaperoneSetup::ReloadFromDisk)> { static const MethodInfo* get() { static auto* configFile = &::il2cpp_utils::GetClassFromName("Valve.VR", "EChaperoneConfigFile")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "ReloadFromDisk", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{configFile}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::GetLiveSeatedZeroPoseToRawTrackingPose // Il2CppName: GetLiveSeatedZeroPoseToRawTrackingPose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Valve::VR::CVRChaperoneSetup::*)(ByRef<Valve::VR::HmdMatrix34_t>)>(&Valve::VR::CVRChaperoneSetup::GetLiveSeatedZeroPoseToRawTrackingPose)> { static const MethodInfo* get() { static auto* pmatSeatedZeroPoseToRawTrackingPose = &::il2cpp_utils::GetClassFromName("Valve.VR", "HmdMatrix34_t")->this_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "GetLiveSeatedZeroPoseToRawTrackingPose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pmatSeatedZeroPoseToRawTrackingPose}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::SetWorkingCollisionBoundsTagsInfo // Il2CppName: SetWorkingCollisionBoundsTagsInfo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (Valve::VR::CVRChaperoneSetup::*)(::ArrayW<uint8_t>)>(&Valve::VR::CVRChaperoneSetup::SetWorkingCollisionBoundsTagsInfo)> { static const MethodInfo* get() { static auto* pTagsBuffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "SetWorkingCollisionBoundsTagsInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pTagsBuffer}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::GetLiveCollisionBoundsTagsInfo // Il2CppName: GetLiveCollisionBoundsTagsInfo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Valve::VR::CVRChaperoneSetup::*)(ByRef<::ArrayW<uint8_t>>)>(&Valve::VR::CVRChaperoneSetup::GetLiveCollisionBoundsTagsInfo)> { static const MethodInfo* get() { static auto* pTagsBuffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->this_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "GetLiveCollisionBoundsTagsInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pTagsBuffer}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::SetWorkingPhysicalBoundsInfo // Il2CppName: SetWorkingPhysicalBoundsInfo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Valve::VR::CVRChaperoneSetup::*)(::ArrayW<Valve::VR::HmdQuad_t>)>(&Valve::VR::CVRChaperoneSetup::SetWorkingPhysicalBoundsInfo)> { static const MethodInfo* get() { static auto* pQuadsBuffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("Valve.VR", "HmdQuad_t"), 1)->byval_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "SetWorkingPhysicalBoundsInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pQuadsBuffer}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::GetLivePhysicalBoundsInfo // Il2CppName: GetLivePhysicalBoundsInfo template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Valve::VR::CVRChaperoneSetup::*)(ByRef<::ArrayW<Valve::VR::HmdQuad_t>>)>(&Valve::VR::CVRChaperoneSetup::GetLivePhysicalBoundsInfo)> { static const MethodInfo* get() { static auto* pQuadsBuffer = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("Valve.VR", "HmdQuad_t"), 1)->this_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "GetLivePhysicalBoundsInfo", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pQuadsBuffer}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::ExportLiveToBuffer // Il2CppName: ExportLiveToBuffer template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Valve::VR::CVRChaperoneSetup::*)(System::Text::StringBuilder*, ByRef<uint>)>(&Valve::VR::CVRChaperoneSetup::ExportLiveToBuffer)> { static const MethodInfo* get() { static auto* pBuffer = &::il2cpp_utils::GetClassFromName("System.Text", "StringBuilder")->byval_arg; static auto* pnBufferLength = &::il2cpp_utils::GetClassFromName("System", "UInt32")->this_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "ExportLiveToBuffer", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pBuffer, pnBufferLength}); } }; // Writing MetadataGetter for method: Valve::VR::CVRChaperoneSetup::ImportFromBufferToWorking // Il2CppName: ImportFromBufferToWorking template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (Valve::VR::CVRChaperoneSetup::*)(::Il2CppString*, uint)>(&Valve::VR::CVRChaperoneSetup::ImportFromBufferToWorking)> { static const MethodInfo* get() { static auto* pBuffer = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* nImportFlags = &::il2cpp_utils::GetClassFromName("System", "UInt32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(Valve::VR::CVRChaperoneSetup*), "ImportFromBufferToWorking", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pBuffer, nImportFlags}); } };
68.789634
228
0.763063
[ "vector" ]
1e01390964a3de4da77edd4f432a2d2fea5d3e9d
3,153
cpp
C++
client/trackerconnector.cpp
uroni/qstream
334c5d886fc626b3eff79870f283a906cdd353e0
[ "Apache-2.0" ]
4
2018-03-16T03:30:43.000Z
2022-02-24T09:42:37.000Z
client/trackerconnector.cpp
uroni/qstream
334c5d886fc626b3eff79870f283a906cdd353e0
[ "Apache-2.0" ]
null
null
null
client/trackerconnector.cpp
uroni/qstream
334c5d886fc626b3eff79870f283a906cdd353e0
[ "Apache-2.0" ]
2
2018-10-12T02:45:41.000Z
2019-07-03T11:55:32.000Z
#ifdef _WIN32 #include <windows.h> #endif #include "trackerconnector.h" #include "../common/socket_functions.h" #include "../common/log.h" #include "../common/stringtools.h" #include "../common/data.h" #include "../common/packet_ids.h" #include "../common/msg_tree.h" /** * Initialize the tracker connector by giving the name of the tracker (ip or dns-name) 'pTracker' the port on which the tracker * accepts tcp connections, the port which is used by this client to receive udp packets and the bandwidth this client has to * forward packets. **/ TrackerConnector::TrackerConnector(std::string pTracker, unsigned short pTrackerport, unsigned short pControllerport, unsigned int pBandwidth_out) : tracker(pTracker), trackerport(pTrackerport), controllerport(pControllerport), bandwidth_out(pBandwidth_out) { } /** * Main thread function **/ void TrackerConnector::operator()(void) { unsigned int trackerip=os_resolv(tracker); cs=os_createSocket(false); bool b=os_connect(cs, trackerip, trackerport); if(!b) { log("Could not connect to tracker "+tracker+" on port "+nconvert(trackerport)); os_closesocket(cs); return; } log("Connected to tracker."); os_nagle(cs, false); { CWData msg; msg.addUChar(TRACKER_PORT); msg.addUShort(controllerport); msg.addUInt(bandwidth_out); stack.Send(cs,msg); } while(true) { char buffer[4096]; int rc=os_recv(cs, buffer, 4096); if(rc<=0) { log("Connection to tracker lost!"); os_closesocket(cs); return; } else { stack.AddData(buffer, rc); size_t bsize; char *buf; while( (buf=stack.getPacket(&bsize))!=NULL) { CRData msg(buf, bsize); receivePacket(msg); delete []buf; } } } } /** * Returns a list of ip,port pairs of children for a message with id 'msgid'. The msgid is used to * calculate which slice the message is in. **/ std::vector<std::pair<unsigned int, unsigned short> > TrackerConnector::getPeers(unsigned int msgid) { boost::mutex::scoped_lock lock(mutex); if(peers.empty()) return std::vector<std::pair<unsigned int, unsigned short> >(); int k=msgid%peers.size(); if(k<(int)peers.size()) { return peers[k]; } else { return std::vector<std::pair<unsigned int, unsigned short> >(); } } /** * Handle the message 'msg' received from the tracker **/ void TrackerConnector::receivePacket(CRData &msg) { unsigned char type; if(msg.getUChar(&type) ) { switch(type) { case TRACKER_PING: { CWData repl; repl.addUChar(TRACKER_PONG); stack.Send(cs, repl); }break; case TRACKER_TREE: { msg_tree tree(msg); if(!tree.hasError()) { boost::mutex::scoped_lock lock(mutex); if(peers.size()!=tree.getSlices()) { peers.resize(tree.getSlices()); } peers[tree.getK()]=tree.getRelayNodes(); } else { log("tree message has error"); } }; } } } /** * Send data 'data' to the tracker using the TCP connection **/ void TrackerConnector::sendToTracker(CWData &data) { stack.Send(cs, data); }
22.847826
147
0.649223
[ "vector" ]
1e019a24557479ea6afe6ad1ce341b39d92a5fdf
788
cpp
C++
Online Judges/URI/1547/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
64
2019-03-17T08:56:28.000Z
2022-01-14T02:31:21.000Z
Online Judges/URI/1547/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
1
2020-12-24T07:16:30.000Z
2021-03-23T20:51:05.000Z
Online Judges/URI/1547/main.cpp
AnneLivia/URI-Online
02ff972be172a62b8abe25030c3676f6c04efd1b
[ "MIT" ]
19
2019-05-25T10:48:16.000Z
2022-01-07T10:07:46.000Z
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int t, qtA, numM, n; vector<int>v; cin >> t; while(t--) { v.clear(); cin >> qtA >> numM; while(qtA--) { cin >> n; v.push_back(n); } int achou = 0, i, pos = 0, closer = abs(v[0] - numM); for ( i = 0; i < (int)v.size(); i++) { if(v[i] == numM) { achou = true; break; } if(abs((v[i] - numM)) < closer) { closer = abs(v[i] - numM); pos = i; } } if(achou) { cout << i + 1 << endl; } else { cout << pos + 1 << endl; } } return 0; }
19.219512
61
0.356599
[ "vector" ]
1e01faedee95d6affcbf3e9eff6cd37ad2a6aca5
53,429
cpp
C++
src/image.cpp
akivajp/lev
945aa438ce4718f60cde35556c55655515cb423b
[ "MIT" ]
null
null
null
src/image.cpp
akivajp/lev
945aa438ce4718f60cde35556c55655515cb423b
[ "MIT" ]
null
null
null
src/image.cpp
akivajp/lev
945aa438ce4718f60cde35556c55655515cb423b
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Name: src/image.cpp // Purpose: source for image handling classes // Author: Akiva Miura <akiva.miura@gmail.com> // Modified by: // Created: 01/25/2011 // Copyright: (C) 2010-2011 Akiva Miura // Licence: MIT License ///////////////////////////////////////////////////////////////////////////// // pre-compiled header #include "prec.h" // declarations #include "lev/image.hpp" // dependencies #include "lev/debug.hpp" #include "lev/entry.hpp" #include "lev/font.hpp" #include "lev/fs.hpp" #include "lev/util.hpp" #include "lev/screen.hpp" #include "lev/system.hpp" #include "lev/timer.hpp" //#include "resource/levana.xpm" // libraries #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include <GL/glu.h> #include <luabind/adopt_policy.hpp> #include <luabind/luabind.hpp> #include "stb_image.c" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" namespace lev { static bool blend_pixel(unsigned char *dst, const unsigned char *src) { if (src[3] == 0) { return true; } unsigned char dst_r = dst[0]; unsigned char dst_g = dst[1]; unsigned char dst_b = dst[2]; unsigned char dst_a = dst[3]; unsigned char src_r = src[0]; unsigned char src_g = src[1]; unsigned char src_b = src[2]; unsigned char src_a = src[3]; if (dst_a == 0 || src_a == 255) { dst[0] = src_r; dst[1] = src_g; dst[2] = src_b; dst[3] = src_a; } else if (dst_a == 255) { unsigned char base_alpha = 255 - src_a; dst[0] = ((unsigned short)src_r * src_a + (unsigned short)dst_r * base_alpha) / 255; dst[1] = ((unsigned short)src_g * src_a + (unsigned short)dst_g * base_alpha) / 255; dst[2] = ((unsigned short)src_b * src_a + (unsigned short)dst_b * base_alpha) / 255; // dst[3] = 255; } else { unsigned char base_alpha = (unsigned short)dst_a * (255 - src_a) / 255; dst[3] = src_a + base_alpha; dst[0] = ((unsigned short)src_r * src_a + (unsigned short)dst_r * base_alpha) / dst[3]; dst[1] = ((unsigned short)src_g * src_a + (unsigned short)dst_g * base_alpha) / dst[3]; dst[2] = ((unsigned short)src_b * src_a + (unsigned short)dst_b * base_alpha) / dst[3]; } return true; } static bool blend_pixel(unsigned char *dst, const color &c) { if (c.get_a() == 0) { return true; } unsigned char dst_r = dst[0]; unsigned char dst_g = dst[1]; unsigned char dst_b = dst[2]; unsigned char dst_a = dst[3]; unsigned char src_r = c.get_r(); unsigned char src_g = c.get_g(); unsigned char src_b = c.get_b(); unsigned char src_a = c.get_a(); if (dst_a == 0 || src_a == 255) { dst[0] = src_r; dst[1] = src_g; dst[2] = src_b; dst[3] = src_a; } else if (dst_a == 255) { unsigned char base_alpha = 255 - src_a; dst[0] = ((unsigned short)src_r * src_a + (unsigned short)dst_r * base_alpha) / 255; dst[1] = ((unsigned short)src_g * src_a + (unsigned short)dst_g * base_alpha) / 255; dst[2] = ((unsigned short)src_b * src_a + (unsigned short)dst_b * base_alpha) / 255; // dst[3] = 255; } else { unsigned char base_alpha = (unsigned short)dst_a * (255 - src_a) / 255; dst[3] = src_a + base_alpha; dst[0] = ((unsigned short)src_r * src_a + (unsigned short)dst_r * base_alpha) / dst[3]; dst[1] = ((unsigned short)src_g * src_a + (unsigned short)dst_g * base_alpha) / dst[3]; dst[2] = ((unsigned short)src_b * src_a + (unsigned short)dst_b * base_alpha) / dst[3]; } return true; } class impl_bitmap : public bitmap { public: typedef boost::shared_ptr<impl_bitmap> ptr; protected: impl_bitmap(int w, int h) : bitmap(), w(w), h(h), descent(0), tex() { } public: virtual ~impl_bitmap() { if (buf) { delete [] buf; } } virtual bool blit(int dst_x, int dst_y, bitmap::ptr src, int src_x, int src_y, int w, int h, unsigned char alpha) { if (src == NULL) { return false; } unsigned char *dst_buf = get_buffer(); const unsigned char *src_buf = src->get_buffer(); int dst_h = get_h(); int dst_w = get_w(); int src_h = src->get_h(); int src_w = src->get_w(); if (w < 0) { w = src_w; } if (h < 0) { h = src_h; } for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { int real_src_x = src_x + x; int real_src_y = src_y + y; if (real_src_x < 0 || real_src_x >= src_w || real_src_y < 0 || real_src_y >= src_h) { continue; } int real_dst_x = dst_x + x; int real_dst_y = dst_y + y; if (real_dst_x < 0 || real_dst_x >= dst_w || real_dst_y < 0 || real_dst_y >= dst_h) { continue; } const unsigned char *src_pixel = &src_buf[4 * (real_src_y * src_w + real_src_x)]; blend_pixel(&dst_buf[4 * (real_dst_y * dst_w + real_dst_x)], src_pixel); } } return on_change(); } virtual bool clear(unsigned char r = 0, unsigned char g = 0, unsigned char b = 0, unsigned char a = 0) { unsigned char *pixel = get_buffer(); int length = get_w() * get_h(); if (a > 0) { for (int i = 0; i < length; i++) { pixel[0] = r; pixel[1] = g; pixel[2] = b; pixel[3] = a; pixel += 4; } } else { for (int i = 0; i < length; i++) { pixel[3] = 0; pixel += 4; } } return on_change(); } virtual bitmap::ptr clone() { boost::shared_ptr<bitmap> bmp; try { bmp = bitmap::create(get_w(), get_h()); if (! bmp) { throw -1; } unsigned char *src_buf = get_buffer(); unsigned char *new_buf = bmp->get_buffer(); long length = 4 * get_w() * get_h(); for (int i = 0; i < length; i++) { new_buf[i] = src_buf[i]; } } catch (...) { bmp.reset(); lev::debug_print("error on bitmap memory cloning"); } return bmp; } static impl_bitmap::ptr create(int w, int h) { impl_bitmap::ptr bmp; if (w <= 0 || h <= 0) { return bmp; } try { bmp.reset(new impl_bitmap(w, h)); if (! bmp) { throw -1; } bmp->wptr = bmp; bmp->buf = new unsigned char [w * h * 4]; if (! bmp->buf) { throw -2; } bmp->clear(); } catch (...) { bmp.reset(); lev::debug_print("error on bitmap memory allocation"); } return bmp; } virtual bool draw(drawable::ptr src, int x, int y, unsigned char alpha) { if (! src) { return false; } src->draw_on(to_canvas(), x, y, alpha); return on_change(); } virtual bool draw_on(canvas::ptr dst, int offset_x, int offset_y, unsigned char alpha) { if (! dst) { return false; } return dst->blit(offset_x, offset_y, to_bitmap(), 0, 0, -1, -1, alpha); } virtual bool draw_pixel(int x, int y, const color &c) { if (x < 0 || x >= get_w() || y < 0 || y >= get_h()) { return false; } unsigned char *buf = get_buffer(); unsigned char *pixel = &buf[4 * (y * get_w() + x)]; blend_pixel(pixel, c); return on_change(); } unsigned char *get_buffer() { return buf; } const unsigned char *get_buffer() const { return buf; } virtual int get_descent() const { return descent; } virtual int get_h() const { return h; } virtual color::ptr get_pixel(int x, int y) const { if (x < 0 || x >= get_w() || y < 0 || y >= get_h()) { color::ptr(); } const unsigned char *buf = get_buffer(); const unsigned char *pixel = &buf[4 * (y * get_w() + x)]; return color::create(pixel[0], pixel[1], pixel[2], pixel[3]); } virtual rect::ptr get_rect() const { return rect::create(0, 0, get_w(), get_h()); } virtual size::ptr get_size() const { return size::create(get_w(), get_h()); } virtual texture::ptr get_texture() const { return tex; } virtual int get_w() const { return w; } virtual bool is_compiled() const { return false; } virtual bool is_texturized() const { if (tex) { return true; } return false; } // bitmap* bitmap::levana_icon() // { // static bitmap *img = NULL; // wxBitmap *obj = NULL; // // if (img) { return img; } // try { // img = new bitmap; // img->_obj = obj = new wxBitmap(levana_xpm); // img->_status = new myImageStatus; // return img; // } // catch (...) { // delete img; // return NULL; // } // } static bitmap::ptr load(const std::string &filename) { file::ptr f = file::open(filename); if (! f) { bitmap::ptr(); } return bitmap::load_file(f); } static bitmap::ptr load_file(file::ptr f) { bitmap::ptr bmp; if (! f) { return bmp; } try { int w, h; std::string data; if (! f->read_all(data)) { throw -1; } boost::shared_ptr<unsigned char> buf; buf.reset(stbi_load_from_memory((unsigned char *)data.c_str(), data.length(), &w, &h, NULL, 4), stbi_image_free); if (! buf) { throw -2; } bmp = bitmap::create(w, h); if (! bmp) { throw -3; } for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { unsigned char *pixel = buf.get() + (y * w + x) * 4; unsigned char r, g, b, a; r = pixel[0]; g = pixel[1]; b = pixel[2]; a = pixel[3]; bmp->set_pixel(x, y, color(r, g, b, a)); } } } catch (...) { bmp.reset(); lev::debug_print("error on bitmap data loading"); } return bmp; } bool on_change() { if (tex) { tex.reset(); } return true; } virtual bitmap::ptr resize(int width, int height) { bitmap::ptr bmp; try { bmp = bitmap::create(width, height); if (! bmp) { throw -1; } for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { color::ptr c; c = get_pixel(long(x) * get_w() / width, long(y) * get_h() / height); if (c) { bmp->set_pixel(x, y, *c); } } } } catch (...) { bmp.reset(); lev::debug_print("error on resized bitmap creation"); } return bmp; } virtual bool save(const std::string &filename) const { const unsigned char *buf = get_buffer(); if (stbi_write_png(filename.c_str(), get_w(), get_h(), 4, buf, 4 * get_w()) != 0) { return true; } else { return false; } } virtual bool set_descent(int d) { descent = d; return true; } virtual bool set_pixel(int x, int y, const color &c) { if (x < 0 || x >= get_w() || y < 0 || y >= get_h()) { return false; } unsigned char *buf = get_buffer(); unsigned char *pixel = &buf[4 * (y * get_w() + x)]; pixel[0] = c.get_r(); pixel[1] = c.get_g(); pixel[2] = c.get_b(); pixel[3] = c.get_a(); return on_change(); } virtual bitmap::ptr sub(int x, int y, int w, int h) { bitmap::ptr bmp; try { bmp = bitmap::create(w, h); if (! bmp) { throw -1; } bmp->blit(0, 0, this->to_bitmap(), x, y, w, h); } catch (...) { bmp.reset(); lev::debug_print("error on sub bitmap instance creation"); } return bmp; } static int sub_l(lua_State *L) { using namespace luabind; int x = 0, y = 0, w = -1, h = -1; luaL_checktype(L, 1, LUA_TUSERDATA); bitmap *img = object_cast<bitmap *>(object(from_stack(L, 1))); if (img == NULL) { return 0; } object t = util::get_merged(L, 2, -1); if (t["x"]) { x = object_cast<int>(t["x"]); } else if (t["lua.number1"]) { x = object_cast<int>(t["lua.number1"]); } if (x < 0) { x = 0; } if (t["y"]) { y = object_cast<int>(t["y"]); } else if (t["lua.number2"]) { y = object_cast<int>(t["lua.number2"]); } if (y < 0) { y = 0; } if (t["w"]) { w = object_cast<int>(t["w"]); } else if (t["lua.number3"]) { w = object_cast<int>(t["lua.number3"]); } if (w < 0) { w = img->get_w() - x; } if (t["h"]) { h = object_cast<int>(t["h"]); } else if (t["lua.number4"]) { h = object_cast<int>(t["lua.number4"]); } if (h < 0) { h = img->get_h() - y; } object o = globals(L)["lev"]["classes"]["bitmap"]["sub_c"](img, x, y, w, h); o.push(L); return 1; } virtual bool texturize(bool force) { if (tex && !force) { return false; } tex = texture::create(to_bitmap()); if (! tex) { return false; } return true; } virtual bitmap::ptr to_bitmap() { return bitmap::ptr(wptr); } virtual canvas::ptr to_canvas() { return canvas::ptr(wptr); } virtual drawable::ptr to_drawable() { return drawable::ptr(wptr); } boost::weak_ptr<impl_bitmap> wptr; int w, h, descent; unsigned char *buf; boost::shared_ptr<texture> tex; }; bitmap::ptr bitmap::create(int w, int h) { return impl_bitmap::create(w, h); } bitmap::ptr bitmap::load(const std::string &filename) { return impl_bitmap::load(filename); } bitmap::ptr bitmap::load_file(file::ptr f) { return impl_bitmap::load_file(f); } bitmap::ptr bitmap::load_path(boost::shared_ptr<filepath> path) { if (! path) { return bitmap::ptr(); } return impl_bitmap::load(path->to_str()); } // texture class implementation class impl_texture : public texture { public: typedef boost::shared_ptr<impl_texture> ptr; protected: impl_texture(int w, int h) : texture(), descent(0), img_w(w), img_h(h), tex_w(1), tex_h(1) { while(tex_w < w) { tex_w <<= 1; } while(tex_h < h) { tex_h <<= 1; } coord_x = double(w) / tex_w; coord_y = double(h) / tex_h; } public: virtual ~impl_texture() { if (index > 0) { //printf("Rel: %d\n", index); glDeleteTextures(1, &index); index = 0; } } virtual bool blit_on(screen::ptr dst, int dst_x = 0, int dst_y = 0, int src_x = 0, int src_y = 0, int w = -1, int h = -1, unsigned char alpha = 255) const { if (! dst) { return NULL; } //printf("TEXTURE BLIT ON!\n"); if (w < 0) { w = img_w; } if (h < 0) { h = img_h; } double tex_x = coord_x * src_x / img_w; double tex_y = coord_y * src_y / img_h; double tex_w = coord_x * w / img_w; double tex_h = coord_y * h / img_h; dst->set_current(); glBindTexture(GL_TEXTURE_2D, index); glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); glColor4ub(255, 255, 255, alpha); glTexCoord2d(tex_x, tex_y); glVertex2i(dst_x, dst_y); glTexCoord2d(tex_x, tex_y + tex_h); glVertex2i(dst_x, dst_y + h); glTexCoord2d(tex_x + tex_w, tex_y + tex_h); glVertex2i(dst_x + w, dst_y + h); glTexCoord2d(tex_x + tex_w, tex_y); glVertex2i(dst_x + w, dst_y); glEnd(); glDisable(GL_TEXTURE_2D); return true; } static impl_texture::ptr create(bitmap::ptr src) { impl_texture::ptr tex; if (! src) { return tex; } try { tex.reset( new impl_texture(src->get_w(), src->get_h()) ); if (! tex) { throw -1; } tex->wptr = tex; glGenTextures(1, &tex->index); //printf("Gen: %d\n", tex->index); if (tex->index == 0) { throw -2; } tex->descent = src->get_descent(); glBindTexture(GL_TEXTURE_2D, tex->index); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0 /* level */, GL_RGBA, tex->tex_w, tex->tex_h, 0 /* border */, GL_RGBA, GL_UNSIGNED_BYTE, NULL /* only buffer reservation */); glTexSubImage2D(GL_TEXTURE_2D, 0, 0 /* x offset */, 0 /* y offset */, tex->img_w, tex->img_h, GL_RGBA, GL_UNSIGNED_BYTE, src->get_buffer()); } catch (...) { tex.reset(); lev::debug_print("error on texture instance creation"); } return tex; } virtual int get_descent() const { return descent; } virtual int get_h() const { return img_h; } virtual int get_w() const { return img_w; } virtual bool is_texturized() const { return true; } static impl_texture::ptr load(const std::string &file) { impl_texture::ptr tex; try { bitmap::ptr img = bitmap::load(file); if (! img) { throw -1; } tex = impl_texture::create(img); } catch (...) { tex.reset(); lev::debug_print("error on texture bitmap loading"); } return tex; } virtual bool set_descent(int d) { descent = d; return true; } virtual drawable::ptr to_drawable() { return drawable::ptr(wptr); } boost::weak_ptr<impl_texture> wptr; int img_w, img_h; int tex_w, tex_h; int descent; double coord_x, coord_y; GLuint index; }; texture::ptr texture::create(bitmap::ptr src) { return impl_texture::create(src); } texture::ptr texture::load(const std::string &file) { return impl_texture::load(file); } // animation class implementation class impl_animation : public animation { public: typedef boost::shared_ptr<impl_animation> ptr; protected: impl_animation(bool repeating = true) : animation(), imgs(), repeating(repeating), texturized(false) { } public: virtual ~impl_animation() { } virtual bool append(drawable::ptr img, double duration) { if (! img) { return false; } if (duration <= 0) { return false; } texturized = false; try { imgs.push_back(img); durations.push_back(duration); return true; } catch (...) { return false; } } virtual bool append_file(const std::string &filename, double duration) { return append(bitmap::load(filename), duration); } static int append_l(lua_State *L) { using namespace luabind; try { int x = 0, y = 0; double duration = 1; luaL_checktype(L, 1, LUA_TUSERDATA); animation* anim = object_cast<animation *>(object(from_stack(L, 1))); object t = util::get_merged(L, 2, -1); if (t["duration"]) { duration = object_cast<double>(t["duration"]); } else if (t["d"]) { duration = object_cast<double>(t["d"]); } else if (t["interval"]) { duration = object_cast<double>(t["interval"]); } else if (t["i"]) { duration = object_cast<double>(t["i"]); } else if (t["lua.number1"]) { duration = object_cast<double>(t["lua.number1"]); } if (t["lev.drawable1"]) { object obj = t["lev.drawable1"]; boost::shared_ptr<drawable> img; img = object_cast<boost::shared_ptr<drawable> >(obj["drawable"]); lua_pushboolean(L, anim->append(img, duration)); } else if (t["lua.string1"]) { const char *path = object_cast<const char *>(t["lua.string1"]); lua_pushboolean(L, anim->append(bitmap::load(path), duration)); } else if (t["lev.filepath1"]) { filepath::ptr path = object_cast<filepath::ptr>(t["lev.filepath1"]); lua_pushboolean(L, anim->append(bitmap::load(path->to_str()), duration)); } else if (t["lev.file1"]) { object obj = t["lev.file1"]; file::ptr f = object_cast<file::ptr>(obj["file"]); lua_pushboolean(L, anim->append(bitmap::load_file(f), duration)); } else { lua_pushboolean(L, false); } } catch (...) { lev::debug_print(lua_tostring(L, -1)); lev::debug_print("error on animation item appending"); lua_pushboolean(L, false); } return 1; } virtual bool compile(bool force) { for (int i = 0; i < imgs.size(); i++) { if (imgs[i]) { imgs[i]->compile(force); } } return true; } static impl_animation::ptr create(bool repeating = true) { impl_animation::ptr anim; try { anim.reset(new impl_animation(repeating)); if (! anim) { throw -1; } anim->wptr = anim; anim->sw = stop_watch::create(); if (! anim->sw) { throw -2; } } catch (...) { anim.reset(); lev::debug_print("error on animation instance creation"); } return anim; } virtual bool draw_on(canvas::ptr dst, int x, int y, unsigned char alpha) { drawable::ptr img = get_current(); //printf("ANIMATION SIZE: %d\n", (int)imgs.size()); if (! img) { return false; } //printf("ANIMATION DRAW ON: %p\n", img.get()); return img->draw_on(dst, x, y, alpha); } virtual drawable::ptr get_current() const { double now = sw->get_time(); double total = 0; if (imgs.size() == 0) { return drawable::ptr(); } for (int i = 0; i < durations.size(); i++) { if (total <= now && now < total + durations[i]) { return imgs[i]; } total += durations[i]; } if (! repeating) { return imgs[imgs.size() - 1]; } sw->start(sw->get_time() - total); return get_current(); } virtual int get_h() const { drawable::ptr img = get_current(); if (img) { return img->get_h(); } else { return 0; } } virtual int get_w() const { drawable::ptr img = get_current(); if (img) { return img->get_w(); } else { return 0; } } virtual bool texturize(bool force) { if (texturized && ! force) { return false; } for (int i = 0; i < imgs.size(); i++) { if (imgs[i]) { imgs[i]->texturize(force); } } texturized = true; return true; } virtual drawable::ptr to_drawable() { return drawable::ptr(wptr); } bool repeating; boost::shared_ptr<stop_watch> sw; std::vector<boost::shared_ptr<drawable> > imgs; std::vector<double> durations; bool texturized; boost::weak_ptr<impl_animation> wptr; }; animation::ptr animation::create(bool repeating) { return impl_animation::create(repeating); } // transition implementation class impl_transition : public transition { public: typedef boost::shared_ptr<impl_transition> ptr; enum transition_mode { LEV_TRAN_NONE = 0, LEV_TRAN_CROSS_FADE, LEV_TRAN_FADE_OUT, }; protected: impl_transition() : transition(), imgs(), sw(), texturized(false) { } public: virtual ~impl_transition() { } static impl_transition::ptr create(drawable::ptr img) { impl_transition::ptr tran; try { tran.reset(new impl_transition); if (! tran) { throw -1; } tran->wptr = tran; tran->sw = stop_watch::create(); if (! tran->sw) { throw -2; } tran->sw->start(); tran->imgs.push_back(img); } catch (...) { tran.reset(); lev::debug_print("error on image transition instance creation"); } return tran; } virtual bool draw_on(canvas::ptr dst, int x, int y, unsigned char alpha) { double grad = 1.0; if (durations.size() >= 1 && durations[0] > 0) { //printf("DURATION: %lf\n", durations[0]); grad = ((double)sw->get_time()) / durations[0]; if (grad > 1.0) { grad = 1.0; } } //printf("IMGS.SIZE: %p, %d\n", imgs[0].get(), imgs.size()); //printf("ALPHA: %ld\n", alpha); if (imgs.size() == 0) { return false; } if (imgs[0]) { if (modes.size() >= 1) { if (modes[0] == LEV_TRAN_FADE_OUT) { imgs[0]->draw_on(dst, x, y, (1 - grad) * alpha); } else if (modes[0] == LEV_TRAN_CROSS_FADE) { imgs[0]->draw_on(dst, x, y, (1 - grad) * alpha); } } else { imgs[0]->draw_on(dst, x, y, alpha); } } if (imgs.size() == 1) { return true; } if (imgs[1]) { if (modes[0] == LEV_TRAN_CROSS_FADE) { //printf("IMGS[1]: %p, %d\n", imgs[1].get(), (int)imgs.size()); //printf("1 FADE: alpha: %d, glad: %lf\n", (int)alpha, grad); imgs[1]->draw_on(dst, x, y, alpha * grad); } } if (sw->get_time() >= durations[0]) { sw->start(sw->get_time() - durations[0]); imgs.erase(imgs.begin()); durations.erase(durations.begin()); modes.erase(modes.begin()); } return true; } virtual drawable::ptr get_current() { return imgs[0]; } virtual int get_h() const { if (imgs[0]) { return imgs[0]->get_h(); } else { return 0; } } virtual int get_w() const { if (imgs[0]) { return imgs[0]->get_w(); } else { return 0; } } virtual bool is_running() const { if (imgs.size() <= 1) { return false; } else { return true; } } virtual bool rewind() { return sw->start(0); } virtual bool set_current(drawable::ptr img) { imgs.clear(); durations.clear(); modes.clear(); imgs.push_back(img); texturized = false; return true; } virtual bool set_current(const std::string &image_path) { return set_current(bitmap::load(image_path)); } static int set_current_l(lua_State *L) { using namespace luabind; try { bool result = false; luaL_checktype(L, 1, LUA_TUSERDATA); transition *tran = object_cast<transition *>(object(from_stack(L, 1))); object t = util::get_merged(L, 2, -1); if (t["lev.drawable1"]) { object obj = t["lev.drawable1"]; drawable::ptr img = object_cast<drawable::ptr>(obj["drawable"]); result = tran->set_current(img); } else if (t["lev.file1"]) { object obj = t["lev.file1"]; file::ptr f = object_cast<file::ptr>(obj["file"]); result = tran->set_current(bitmap::load_file(f)); } else if (t["lev.filepath1"]) { filepath::ptr path = object_cast<filepath::ptr>(t["lev.filepath1"]); result = tran->set_current(path->to_str()); } else if (t["lua.string1"]) { std::string path = object_cast<const char *>(t["lua.string1"]); result = tran->set_current(path); } else { result = tran->set_current(boost::shared_ptr<drawable>()); } lua_pushboolean(L, result); } catch (...) { lev::debug_print(lua_tostring(L, -1)); lev::debug_print("error on transition current bitmap setting"); lua_pushnil(L); } return 1; } virtual bool set_next(drawable::ptr img, double duration = 1, const std::string &type = "") { if (duration < 0) { return false; } try { imgs.push_back(img); durations.push_back(duration); texturized = false; if (type == "cross_fade") { modes.push_back(LEV_TRAN_CROSS_FADE); } else if (type == "crossfade") { modes.push_back(LEV_TRAN_CROSS_FADE); } else if (type == "fade") { modes.push_back(LEV_TRAN_CROSS_FADE); } else if (type == "fade_out") { modes.push_back(LEV_TRAN_FADE_OUT); } else if (type == "fadeout") { modes.push_back(LEV_TRAN_FADE_OUT); } else { modes.push_back(LEV_TRAN_CROSS_FADE); } } catch (...) { return false; } return true; } virtual bool set_next(const std::string &image_path, double duration = 1, const std::string &mode = "") { return set_next(bitmap::load(image_path), duration, mode); } static int set_next_l(lua_State *L) { using namespace luabind; try { double duration = 1; std::string mode = ""; bool result = false; luaL_checktype(L, 1, LUA_TUSERDATA); transition *tran = object_cast<transition *>(object(from_stack(L, 1))); object t = util::get_merged(L, 2, -1); if (t["duration"]) { duration = object_cast<double>(t["duration"]); } else if (t["d"]) { duration = object_cast<double>(t["d"]); } else if (t["lua.number1"]) { duration = object_cast<double>(t["lua.number1"]); } if (t["mode"]) { mode = object_cast<const char *>(t["mode"]); } else if (t["m"]) { mode = object_cast<const char *>(t["m"]); } else if (t["type"]) { mode = object_cast<const char *>(t["type"]); } else if (t["t"]) { mode = object_cast<const char *>(t["t"]); } if (t["lev.drawable1"]) { object obj = t["lev.drawable1"]; drawable::ptr img = object_cast<drawable::ptr>(obj["drawable"]); result = tran->set_next(img, duration, mode); } else if (t["lev.file1"]) { object obj = t["lev.file1"]; file::ptr f = object_cast<file::ptr>(obj["file"]); result = tran->set_next(bitmap::load_file(f), duration, mode); } else if (t["lev.filepath1"]) { filepath::ptr path = object_cast<filepath::ptr>(t["lev.filepath1"]); result = tran->set_next(path->to_str(), duration, mode); } else if (t["lua.string1"]) { std::string path = object_cast<const char *>(t["lua.string1"]); result = tran->set_next(path, duration, mode); } else { result = tran->set_next(boost::shared_ptr<drawable>(), duration, mode); } lua_pushboolean(L, result); } catch (...) { lev::debug_print(lua_tostring(L, -1)); lev::debug_print("error on transition next image setting"); lua_pushnil(L); } return 1; } virtual bool texturize(bool force) { if (texturized && !force) { return false; } for (int i = 0; i < imgs.size(); i++) { if (! imgs[i]) { continue; } imgs[i]->texturize(force); } texturized = true; return true; } virtual drawable::ptr to_drawable() { return drawable::ptr(wptr); } boost::weak_ptr<impl_transition> wptr; std::vector<boost::shared_ptr<drawable> > imgs; std::vector<double> durations; std::vector<transition_mode> modes; boost::shared_ptr<stop_watch> sw; bool texturized; }; transition::ptr transition::create(drawable::ptr img) { return impl_transition::create(img); } transition::ptr transition::create_with_file(file::ptr f) { return impl_transition::create(bitmap::load_file(f)); } transition::ptr transition::create_with_path(filepath::ptr path) { return create_with_string(path->to_str()); } transition::ptr transition::create_with_string(const std::string &image_path) { return create(bitmap::load(image_path)); } // layout implementation class impl_layout : public layout { public: typedef boost::shared_ptr<impl_layout> ptr; struct item_type { item_type() : x(-1), y(-1), fixed(false), func_hover(), func_lsingle(), auto_fill(true) { } drawable::ptr img; drawable::ptr img_hover; drawable::ptr img_showing; luabind::object func_hover; luabind::object func_lsingle; bool auto_fill; int x, y; bool fixed; }; protected: impl_layout(int width_stop = -1) : layout(), width_stop(width_stop), font_text(), font_ruby(), items(), texturized(false) { font_text = font::load0(); font_ruby = font::load0(); if (font_ruby) { font_ruby->set_size(font_ruby->get_size() / 2); } color_fg = color::white(); color_shade = color::black(); hover_bg = color::transparent(); hover_fg = color::red(); } public: virtual ~impl_layout() { } int calc_max_width() const { int max_w = 0; int x = 0; for (int i = 0; i < items.size(); i++) { const item_type &item = items[i]; if (! item.img || (item.auto_fill && width_stop > 0 && x > 0 && x + item.img->get_w() > width_stop)) { // newline if (x > max_w) { max_w = x; } x = 0; } if (item.img) { x += item.img->get_w(); } } return (max_w > x ? max_w : x); } bool calc_position(int index) { int x = 0; int y = 0; // int max_h = 0; int max_ascent = 0; int max_descent = 0; if (index < 0 || index >= items.size()) { return false; } if (! items[index].img) { return false; } // if position is already fixed, return it if (items[index].fixed) { return true; } // back scan int i = index - 1; for (; i >= 0; i--) { item_type &item = items[i]; if (item.fixed) { x = item.x; y = item.y; // max_h = item.img->get_h(); max_ascent = item.img->get_ascent(); max_descent = item.img->get_descent(); break; } } if (i < 0) { i = 0; } // fore scan for (; i < items.size(); i++) { item_type &item = items[i]; if (! item.img || (item.auto_fill && width_stop > 0 && x > 0 && x + item.img->get_w() > width_stop)) { // newline x = 0; // y += max_h; //printf("MAX ASCENT: %d, MAX DESCENT: %d\n", max_ascent, max_descent); y += (max_ascent + max_descent); // max_h = 0; max_ascent = 0; max_descent = 0; // back scan for position fixing for (int j = i - 1; j >= 0; j--) { if (items[j].fixed) { break; } if (items[j].img) { items[j].y = y - items[j].img->get_h(); // items[j].y = y - items[j].img->get_ascent(); items[j].fixed = true; } } if (i > index) { return true; } } //if (! item.auto_fill && width_stop > 0 && x > 0 && x + item.img->get_w() > width_stop) //{ // printf("NO AUTO FILL!\n"); //} if (item.img) { // calc by next item item.x = x; x += item.img->get_w(); // if (item.img->get_h() > max_h) { max_h = item.img->get_h(); } if (item.img->get_ascent() > max_ascent) { max_ascent = item.img->get_ascent(); } if (item.img->get_descent() > max_descent) { max_descent = item.img->get_descent(); } } } // y += max_h; y += (max_ascent + max_descent); // items[index].y = y - items[index].img->get_h(); items[index].y = y - max_descent - items[index].img->get_ascent(); // items[index].y = y - items[index].img->get_ascent(); return true; } int calc_total_height() const { int x = 0; int y = 0; int max_h = 0; for (int i = 0; i < items.size(); i++) { const item_type &item = items[i]; if (! item.img || (width_stop > 0 && x > 0 && x + item.img->get_w() > width_stop)) { // newline x = 0; y += max_h; max_h = 0; } if (item.img) { // calc by next item x += item.img->get_w(); if (item.img->get_h() > max_h) { max_h = item.img->get_h(); } } } y += max_h; return y; } virtual bool clear() { items.clear(); texturized = false; return true; } virtual bool complete() { for ( ; ; ) { int i = get_next_index(); if (i < 0) { return true; } show_index(i); } } static impl_layout::ptr create(int width_stop = -1) { impl_layout::ptr lay; try { lay.reset(new impl_layout(width_stop)); if (! lay) { throw -1; } lay->wptr = lay; } catch (...) { lay.reset(); lev::debug_print("error on layout instance creation"); } return lay; } virtual bool draw_on(canvas::ptr dst, int x, int y, unsigned char alpha) { for (int i = 0; i < items.size(); i++) { item_type &item = items[i]; if (item.img_showing) { calc_position(i); item.img_showing->draw_on(dst, x + item.x, y + item.y, alpha); } } //printf("\n"); return true; } virtual color::ptr get_fg_color() { return color_fg; } virtual font::ptr get_font() { return font_text; } virtual int get_h() const { return calc_total_height(); } int get_next_index() const { for (int i = 0; i < items.size(); i++) { if (! items[i].img) { continue; } if (! items[i].img_showing) { return i; } } return -1; } virtual font::ptr get_ruby_font() { return font_ruby; } virtual color::ptr get_shade_color() { return color_shade; } virtual int get_w() const { if (width_stop > 0) { return width_stop; } return calc_max_width(); } virtual bool is_done() const { return get_next_index() < 0; } virtual bool on_left_down(int x, int y) { using namespace luabind; for (int i = 0; i < items.size(); i++) { item_type &item = items[i]; if (! item.img_hover) { continue; } if (! item.img_showing) { continue; } calc_position(i); rect r(item.x, item.y, item.img->get_w(), item.img->get_h()); if (r.include(x, y)) { // if (item.func_lsingle && type(item.func_lsingle) == LUA_TFUNCTION) // { // item.func_lsingle(x, y); // } return true; } } return false; } virtual bool on_left_up(int x, int y) { using namespace luabind; for (int i = 0; i < items.size(); i++) { item_type &item = items[i]; if (! item.img_hover) { continue; } if (! item.img_showing) { continue; } calc_position(i); rect r(item.x, item.y, item.img->get_w(), item.img->get_h()); if (r.include(x, y) && item.img_showing == item.img_hover) { if (item.func_lsingle && type(item.func_lsingle) == LUA_TFUNCTION) { item.func_lsingle(x, y); } return true; } } return false; } virtual bool on_motion(int x, int y) { using namespace luabind; for (int i = 0; i < items.size(); i++) { item_type &item = items[i]; if (! item.img_hover) { continue; } if (! item.img_showing) { continue; } calc_position(i); rect r(item.x, item.y, item.img->get_w(), item.img->get_h()); if (r.include(x, y)) { // (x, y) is in the rect if (item.img_showing != item.img_hover) { if (item.func_hover && type(item.func_hover) == LUA_TFUNCTION) { item.func_hover(x, y); } item.img_showing = item.img_hover; } } else { // (x, y) isn't in the rect if (item.img_showing != item.img) { item.img_showing = item.img; } } } return true; } virtual bool rearrange() { for (int i = 0; i < items.size(); i++) { items[i].fixed = false; } for (int i = 0; i < items.size(); i++) { calc_position(i); } return true; } virtual bool reserve_clickable(drawable::ptr normal, drawable::ptr hover, luabind::object lsingle_func, luabind::object hover_func) { try { if (! normal) { throw -1; } if (! hover) { hover = normal; } items.push_back(item_type()); item_type &i = items[items.size() - 1]; i.img = normal; i.img_hover = hover; i.func_hover = hover_func; i.func_lsingle = lsingle_func; texturized = false; return true; } catch (...) { return false; } } virtual bool reserve_clickable_text(const std::string &text, luabind::object lsingle_func, luabind::object hover_func) { if (! font_text) { return false; } if (text.empty()) { return false; } try { bitmap::ptr img; bitmap::ptr hover_img; img = font_text->rasterize(text, color_fg, color::ptr(), color_shade); img->stroke_line(0, img->get_h() - 1, img->get_w() - 1, img->get_h() - 1, color_fg, 1, "dot"); hover_img = font_text->rasterize(text, hover_fg, hover_bg, color::ptr()); return reserve_clickable(img, hover_img, lsingle_func, hover_func); } catch (...) { return false; } } virtual bool reserve_image(drawable::ptr img, bool auto_filling = true) { try { if (! img) { throw -1; } items.push_back(item_type()); (items.end() - 1)->img = img; (items.end() - 1)->auto_fill = auto_filling; texturized = false; return true; } catch (...) { return false; } } virtual bool reserve_new_line() { // height spacing items.push_back(item_type()); (items.end() - 1)->img = spacer::create(0, font_text->get_size(), 0); // adding new line items.push_back(item_type()); texturized = false; return true; } virtual bool reserve_word(const std::string &word, const std::string &ruby = "", bool auto_filling = true) { if (! font_text) { return false; } if (! ruby.empty() && ! font_ruby) { return false; } if (word.empty()) { return false; } try { bitmap::ptr img; if (ruby.empty()) { img = font_text->rasterize(word, color_fg, color::ptr(), color_shade); return reserve_image(img, auto_filling); } else { boost::shared_ptr<bitmap> img_ruby; boost::shared_ptr<bitmap> img_word; img_ruby = font_ruby->rasterize(ruby, color_fg, color::ptr(), color_shade); img_word = font_text->rasterize(word, color_fg, color::ptr(), color_shade); if (!img_ruby || !img_word) { throw -1; } int h = img_ruby->get_h() + img_word->get_h(); int w = img_ruby->get_w(); if (img_word->get_w() > w) { w = img_word->get_w(); } img = bitmap::create(w, h); img->draw(img_ruby, (w - img_ruby->get_w()) / 2, 0); img->draw(img_word, (w - img_word->get_w()) / 2, img_ruby->get_h()); return reserve_image(img, auto_filling); } } catch (...) { return false; } } virtual bool set_fg_color(color::ptr fg) { if (! fg) { return false; } color_fg = fg; return true; } virtual bool set_font(font::ptr f) { if (! f) { return false; } font_text = f; return true; } virtual bool set_shade_color(color::ptr sh) { if (! sh) { return false; } color_shade = sh; return true; } virtual bool set_ruby_font(font::ptr f) { if (! f) { return false; } font_ruby = f; return true; } bool show_index(int index) { if (index >= items.size()) { return false; } item_type &item = items[index]; item.img_showing = item.img; return true; } virtual bool show_next() { if (is_done()) { return false; } return show_index(get_next_index()); } virtual bool texturize(bool force) { if (texturized && !force) { return false; } for (int i = 0; i < items.size(); i++) { item_type &item = items[i]; if (item.img) { item.img->texturize(force); } if (item.img_hover) { item.img_hover->texturize(force); } } texturized = true; return true; } virtual drawable::ptr to_drawable() { return drawable::ptr(wptr); } boost::weak_ptr<impl_layout> wptr; bool texturized; // common format properties color::ptr color_fg; color::ptr color_shade; color::ptr hover_bg; color::ptr hover_fg; boost::shared_ptr<font> font_text; boost::shared_ptr<font> font_ruby; int width_stop; // all items std::vector<item_type> items; }; layout::ptr layout::create(int width_stop) { return impl_layout::create(width_stop); } } int luaopen_lev_image(lua_State *L) { using namespace luabind; using namespace lev; open(L); globals(L)["package"]["loaded"]["lev.image"] = true; globals(L)["require"]("lev.draw"); module(L, "lev") [ namespace_("classes") [ class_<bitmap, canvas, canvas::ptr >("bitmap") .def("clone", &bitmap::clone) // .def("load", &bitmap::reload) .property("rect", &bitmap::get_rect) // .def("reload", &bitmap::reload) .def("resize", &bitmap::resize) .def("save", &bitmap::save) .def("set_color", &bitmap::set_pixel) .def("set_pixel", &bitmap::set_pixel) .property("sz", &bitmap::get_size) .property("size", &bitmap::get_size) .scope [ def("create", &bitmap::create), def("create", &bitmap::load), def("create", &bitmap::load_file), def("create", &bitmap::load_path), // def("levana_icon", &bitmap::levana_icon), def("sub_c", &bitmap::sub) ], class_<texture, drawable, boost::shared_ptr<drawable> >("texture") .scope [ def("create", &texture::create), def("create", &texture::load) ], class_<animation, drawable, boost::shared_ptr<drawable> >("animation") .property("current", &animation::get_current) .scope [ def("create", &animation::create), def("create", &animation::create0) ], class_<transition, drawable, boost::shared_ptr<drawable> >("transition") .property("current", &transition::get_current) .property("is_running", &transition::is_running) .def("rewind", &transition::rewind) .scope [ def("create", &transition::create), def("create", &transition::create0), def("create", &transition::create_with_file), def("create", &transition::create_with_path), def("create", &transition::create_with_string) ], class_<layout, clickable, clickable::ptr>("layout") .def("clear", &layout::clear) .property("color", &layout::get_fg_color, &layout::set_fg_color) .def("complete", &layout::complete) .property("fg", &layout::get_fg_color, &layout::set_fg_color) .property("fg_color", &layout::get_fg_color, &layout::set_fg_color) .property("font", &layout::get_font, &layout::set_font) .property("fore", &layout::get_fg_color, &layout::set_fg_color) .property("is_done", &layout::is_done) .def("rearrange", &layout::rearrange) .def("reserve_clickable", &layout::reserve_clickable) .def("reserve_clickable", &layout::reserve_clickable_text) .def("reserve_image", &layout::reserve_image) .def("reserve_image", &layout::reserve_image1) .def("reserve_new_line", &layout::reserve_new_line) .def("reserve_word", &layout::reserve_word) .def("reserve_word", &layout::reserve_word_filling) .def("reserve_word", &layout::reserve_word1) .def("reserve_word", &layout::reserve_word2) .property("ruby", &layout::get_ruby_font, &layout::set_ruby_font) .property("ruby_font", &layout::get_ruby_font, &layout::set_ruby_font) .property("shade", &layout::get_shade_color, &layout::set_shade_color) .property("shade_color", &layout::get_shade_color, &layout::set_shade_color) .def("show_next", &layout::show_next) .property("text_font", &layout::get_font, &layout::set_font) .scope [ def("create", &layout::create), def("create", &layout::create0) ] ] ]; object lev = globals(L)["lev"]; object classes = lev["classes"]; register_to(classes["bitmap"], "get_sub", &impl_bitmap::sub_l); register_to(classes["bitmap"], "sub", &impl_bitmap::sub_l); register_to(classes["animation"], "append", &impl_animation::append_l); register_to(classes["transition"], "set_current", &impl_transition::set_current_l); register_to(classes["transition"], "set_next", &impl_transition::set_next_l); lev["animation"] = classes["animation"]["create"]; lev["bitmap"] = classes["bitmap"]["create"]; lev["layout"] = classes["layout"]["create"]; lev["texture"] = classes["texture"]["create"]; lev["tex2d"] = classes["texture"]["create"]; lev["transition"] = classes["transition"]["create"]; // image["levana_icon"] = classes["image"]["levana_icon"]; globals(L)["require"]("lev.font"); globals(L)["require"]("lev.prim"); globals(L)["package"]["loaded"]["lev.image"] = true; return 0; }
28.725269
101
0.499092
[ "object", "vector" ]
1e0618c51742a716886d7a400396976bd51385b6
4,589
cpp
C++
Sample_protocols/Protocols_from_OpenWetWare/OWW_DNA_extraction_salting_out.cpp
o-micron/BioCoderEditor
18037b1d85bee5973704bd2e6c8ab6eab171d554
[ "Unlicense" ]
null
null
null
Sample_protocols/Protocols_from_OpenWetWare/OWW_DNA_extraction_salting_out.cpp
o-micron/BioCoderEditor
18037b1d85bee5973704bd2e6c8ab6eab171d554
[ "Unlicense" ]
null
null
null
Sample_protocols/Protocols_from_OpenWetWare/OWW_DNA_extraction_salting_out.cpp
o-micron/BioCoderEditor
18037b1d85bee5973704bd2e6c8ab6eab171d554
[ "Unlicense" ]
null
null
null
#include "biocoder.h" int main() { start_protocol("DNA Extraction - salting out"); Fluid dig_buffer = new_fluid("Digestion Buffer", "10mM NaCl, 10mM TRIS (pH 8.0), 10mM EDTA (pH 8.0), 0.5% SDS"); Fluid proteinasek = new_fluid("Proteinase K", "20mg/ml"); Fluid naac = new_fluid("Sodium Acetate pH 5.2", "3M"); Fluid eth98 = new_fluid("98% ethanol", ICE_COLD); Fluid eth70 = new_fluid("70% ethanol", ICE_COLD); Fluid te = new_fluid("1X TE"); Fluid water = new_fluid("water"); Tissue req_tissue = new_solid("tissue"); Container sterile_microfuge_tube1 = new_container(STERILE_MICROFUGE_TUBE, req_tissue); Container sterile_microfuge_tube2 = new_container(STERILE_MICROFUGE_TUBE); Container sterile_microfuge_tube3 = new_container(STERILE_MICROFUGE_TUBE); Container sterile_microfuge_tube4 = new_container(STERILE_MICROFUGE_TUBE); // * Tissue Digestion first_step("Tissue Digestion"); first_sub_step(); // 1. Add 5μL Proteinase K to each mL of Digestion Buffer (final 0.5mg/mL) measure_fluid(dig_buffer, sterile_microfuge_tube2); measure_prop(sterile_microfuge_tube2, proteinasek, 0.005); comment("That is, for each ml of Digestion Buffer, add 5 µl of ProteinaseK."); name_sample(sterile_microfuge_tube2, "solution"); // 2. Homogenise (or simply place) tissue in solution next_sub_step(); homogenize_tissue(sterile_microfuge_tube1, sterile_microfuge_tube2.contents); // 3. Incubate at 55°C for 1 hour to overnight next_sub_step(); incubate(sterile_microfuge_tube2, 55, time_range(1, 12, HRS)); // 4. Mix by vortexing then centrifuge at maximum speed in a benchtop // centrifuge for 2 minutes next_sub_step(); vortex(sterile_microfuge_tube2); centrifuge_phases_top(sterile_microfuge_tube2, speed(SPEED_MAX, RPM), 4, time(2, MINS), sterile_microfuge_tube3); // 5. Transfer supernatant into a new tube // * Precipitation of Protein and Cell Debris next_step("Precipitation of Protein and Cell Debris"); // 1. Add 1/10 volume of Sodium Acetate 3M pH 5.2 (final 0.3M) first_sub_step(); measure_prop(sterile_microfuge_tube3, naac, 0.1); // 2. Invert to mix and incubate at -20°C for ~15 minutes next_sub_step(); invert(sterile_microfuge_tube3); incubate(sterile_microfuge_tube3, -20, time(15, MINS)); // 3. Centrifuge (preferably at 4°C) at maximum speed in a benchtop centrifuge // for 20 minutes centrifuge_phases_top(sterile_microfuge_tube3, speed(SPEED_MAX, RPM), 4, time(20, MINS), sterile_microfuge_tube4); comment("Be careful not to transfer any of the white solid (cell debris and " "SDS) into the fresh tube."); // 4. Transfer supernatant to a new tube // * Precipitation of Nucleic Acids next_step("Precipitation of Nucleic Acids"); // 1. Add ~2 volumes of 98% ethanol (final 60-80%) first_sub_step(); measure_prop(sterile_microfuge_tube4, eth98, 2); // 2. Invert to mix and incubate at -20°C for ~15 minutes next_sub_step(); invert(sterile_microfuge_tube4); incubate(sterile_microfuge_tube4, -20, time(15, MINS)); // 3. Centrifuge (preferably at 4°C) at maximum speed in a benchtop centrifuge // for 20 minutes next_sub_step(); centrifuge_pellet( sterile_microfuge_tube4, speed(SPEED_MAX, RPM), 4, time(20, MINS)); // 4. Wash pellet with 98% ethanol, and once or twice with 70%. Allow to air // dry then resuspend in water or 1xTE next_sub_step(); measure_fluid(eth98, vol(1, ML), sterile_microfuge_tube4); vortex(sterile_microfuge_tube4); centrifuge_pellet( sterile_microfuge_tube4, speed(SPEED_MAX, RPM), 4, time(5, MINS)); measure_fluid(eth70, vol(1, ML), sterile_microfuge_tube4); vortex(sterile_microfuge_tube4); centrifuge_pellet( sterile_microfuge_tube4, speed(SPEED_MAX, RPM), 4, time(5, MINS)); optional_step(); measure_fluid(eth70, vol(1, ML), sterile_microfuge_tube4); vortex(sterile_microfuge_tube4); centrifuge_pellet( sterile_microfuge_tube4, speed(SPEED_MAX, RPM), 4, time(5, MINS)); next_step(); dry_pellet(sterile_microfuge_tube4, IN_AIR); first_option(); measure_fluid(te, vol(10, UL), sterile_microfuge_tube4); next_option(); measure_fluid(water, vol(10, UL), sterile_microfuge_tube4); end_option(); resuspend(sterile_microfuge_tube4); comment("Ensure to dry the pelletted DNA completely before attempting to " "resuspend."); end_protocol(); }
39.904348
80
0.705382
[ "solid" ]
1e098573d832b26c5e6037fc1245dd4284f3f2a5
12,022
inl
C++
projects/Phantom/phantom/utils/Variant.inl
vlmillet/phantom
e5579ea52dafded64fd2fe88aabfdf8a73534918
[ "MIT" ]
12
2019-12-26T00:55:39.000Z
2020-12-03T14:46:56.000Z
projects/Phantom/phantom/utils/Variant.inl
vlmillet/Phantom
e5579ea52dafded64fd2fe88aabfdf8a73534918
[ "MIT" ]
null
null
null
projects/Phantom/phantom/utils/Variant.inl
vlmillet/Phantom
e5579ea52dafded64fd2fe88aabfdf8a73534918
[ "MIT" ]
1
2020-12-09T11:47:13.000Z
2020-12-09T11:47:13.000Z
// license [ // This file is part of the Phantom project. Copyright 2011-2020 Vivien Millet. // Distributed under the MIT license. Text available here at // https://github.com/vlmillet/phantom // ] #include <phantom/lang/TypeOf.h> namespace phantom { namespace detail { template<class t_Ty> struct VariantTypeOf { PHANTOM_STATIC_ASSERT(!(std::is_same<t_Ty, Variant>::value)); static lang::Type* object() { return PHANTOM_TYPEOF(t_Ty); } }; template<class t_Ty> struct VariantTypeOf<t_Ty*> { static lang::Type* object() { if (auto pType = PHANTOM_TYPEOF(t_Ty)) return pType->addPointer(); return phantom::lang::BuiltInTypes::TYPE_VOID_PTR; } }; } #define PHANTOM_VARIANT_TYPEOF(...) phantom::detail::VariantTypeOf<__VA_ARGS__>::object() template<typename t_Ty, typename> inline Variant::Variant(const t_Ty& a_In) { void* pBuffer = (sizeof(t_Ty) > StaticBufferSize) ? (m_Buffer.dynamicBuffer = _Alloc(sizeof(t_Ty), alignof(t_Ty))) : m_Buffer.staticBuffer; m_pType = PHANTOM_VARIANT_TYPEOF(t_Ty); new (pBuffer) t_Ty(a_In); } template<typename t_Ty, typename> inline Variant::Variant(t_Ty&& a_In) { byte* pBuffer = (sizeof(std::remove_reference_t<t_Ty>) > StaticBufferSize) ? (m_Buffer.dynamicBuffer = _Alloc(sizeof(std::remove_reference_t<t_Ty>), alignof(std::remove_reference_t<t_Ty>))) : m_Buffer.staticBuffer; m_pType = PHANTOM_VARIANT_TYPEOF(std::remove_reference_t<t_Ty>); new (pBuffer) std::remove_reference_t<t_Ty>(std::forward<t_Ty>(a_In)); } inline Variant::Variant(const char* a_Str) { new (m_Buffer.dynamicBuffer = _Alloc(sizeof(String), alignof(String))) String(a_Str); PHANTOM_ASSERT(phantom::lang::BuiltInTypes::TYPE_STRING); m_pType = (lang::Type*)phantom::lang::BuiltInTypes::TYPE_STRING; } Variant::Variant(Variant&& a_Other) : m_pType(a_Other.m_pType) { if (a_Other.isValid()) { if ((a_Other.size() > StaticBufferSize)) { m_Buffer.dynamicBuffer = a_Other.m_Buffer.dynamicBuffer; a_Other.m_Buffer.dynamicBuffer = nullptr; a_Other.m_pType = nullptr; } else { m_pType->construct(m_Buffer.staticBuffer); m_pType->copy(m_Buffer.staticBuffer, a_Other.m_Buffer.staticBuffer); } } } inline Variant::Variant(const Variant& a_Other) : m_pType(a_Other.m_pType) { if(a_Other.isValid()) { byte* pBuffer = (a_Other.size() > StaticBufferSize) ? (m_Buffer.dynamicBuffer = _Alloc(a_Other.size(), a_Other.type()->getAlignment())) : m_Buffer.staticBuffer; m_pType->construct(pBuffer); m_pType->copy(pBuffer, a_Other._buffer()); } } inline Variant& Variant::operator=(const Variant& a_Other) { if (m_pType) { _release(); } if (a_Other.isValid()) { byte* pBuffer = (a_Other.size() > StaticBufferSize) ? (m_Buffer.dynamicBuffer = _Alloc(a_Other.size(), a_Other.type()->getAlignment())) : m_Buffer.staticBuffer; m_pType = a_Other.m_pType; m_pType->construct(pBuffer); m_pType->copy(pBuffer, a_Other._buffer()); } else m_pType = nullptr; return *this; } inline Variant& Variant::operator=(Variant&& a_Other) { if (m_pType) { _release(); } if (a_Other.isValid()) { if (a_Other.size() > StaticBufferSize) { m_Buffer.dynamicBuffer = a_Other.m_Buffer.dynamicBuffer; a_Other.m_Buffer.dynamicBuffer = nullptr; } else { memcpy(m_Buffer.staticBuffer, a_Other.m_Buffer.staticBuffer, StaticBufferSize); } m_pType = a_Other.m_pType; a_Other.m_pType = nullptr; } else m_pType = nullptr; return *this; } inline Variant& Variant::operator=(const char* a_Str) { if (m_pType) { _release(); } new (m_Buffer.dynamicBuffer = _Alloc(sizeof(String), alignof(String))) String(a_Str); m_pType = (lang::Type*)phantom::lang::BuiltInTypes::TYPE_STRING; return *this; } template<typename t_Ty, class> inline Variant& Variant::operator=(const t_Ty& a_In) { auto pType = PHANTOM_VARIANT_TYPEOF(t_Ty); PHANTOM_ASSERT(pType); if (m_pType == pType) { m_pType->copyAssign(_buffer(), &a_In); } else { if (m_pType) _release(); byte* pBuffer = (sizeof(t_Ty) > StaticBufferSize) ? (m_Buffer.dynamicBuffer = _Alloc(sizeof(t_Ty), alignof(t_Ty))) : m_Buffer.staticBuffer; m_pType = pType; m_pType->copyConstruct(pBuffer, &a_In); } return *this; } template<typename t_Ty, class> inline Variant& Variant::operator=(t_Ty&& a_In) { auto pType = PHANTOM_VARIANT_TYPEOF(std::remove_reference_t<t_Ty>); PHANTOM_ASSERT(pType); if (m_pType == pType) { *(std::remove_reference_t<t_Ty>*)_buffer() = std::forward<t_Ty>(a_In); } else { if (m_pType) _release(); byte* pBuffer = (sizeof(std::remove_reference_t<t_Ty>) > StaticBufferSize) ? (m_Buffer.dynamicBuffer = _Alloc(sizeof(std::remove_reference_t<t_Ty>), alignof(std::remove_reference_t<t_Ty>))) : m_Buffer.staticBuffer; m_pType = pType; new (pBuffer) std::remove_reference_t<t_Ty>(std::forward<t_Ty>(a_In)); } return *this; } inline void Variant::setType(lang::Type* a_pType) { if (m_pType) { _release(); } PHANTOM_ASSERT(a_pType->isCopyable() && a_pType->isDefaultInstanciable()); byte* pBuffer = (a_pType->getSize() > StaticBufferSize) ? (m_Buffer.dynamicBuffer = _Alloc(a_pType->getSize(), a_pType->getAlignment())) : m_Buffer.staticBuffer; m_pType = a_pType; m_pType->construct(pBuffer); } template<typename T> inline T* Variant::fundamental() { PHANTOM_STATIC_ASSERT(std::is_fundamental<T>::value, "T must be a fundamental type"); PHANTOM_STATIC_ASSERT(sizeof(T) <= StaticBufferSize, "T size must be less than static buffer size"); if (m_pType) { _release(); } m_pType = PHANTOM_VARIANT_TYPEOF(T); return (T*)m_Buffer.staticBuffer; } template<typename T> inline void Variant::fundamental(T value) { PHANTOM_STATIC_ASSERT(std::is_fundamental<T>::value, "T must be a fundamental type"); PHANTOM_STATIC_ASSERT(sizeof(T) <= StaticBufferSize, "T size must be less than static buffer size"); if (m_pType) { _release(); } m_pType = PHANTOM_VARIANT_TYPEOF(T); *(T*)m_Buffer.staticBuffer = value; } inline bool Variant::operator==(const char* other) const { return (m_pType == (lang::Type*)phantom::lang::BuiltInTypes::TYPE_STRING) &&(*((String*)_buffer()) == other); } inline bool Variant::operator==(StringView other) const { return (m_pType == (lang::Type*)phantom::lang::BuiltInTypes::TYPE_STRING) &&(*((String*)_buffer()) == other); } inline bool Variant::operator==(const Variant& other) const { if (m_pType == nullptr) return other.m_pType == nullptr; else if (other.m_pType == nullptr) return m_pType == nullptr; if (m_pType->isSame((lang::Type*)phantom::lang::BuiltInTypes::TYPE_STRING)) { return (m_pType->isSame(other.m_pType)) && (*((String*)_buffer()) == *((String*)other._buffer())); } return (m_pType->isSame(other.m_pType)) && m_pType->equal(_buffer(), other._buffer()); } inline bool Variant::operator!=(const char* other) const { return !operator==(other); } inline bool Variant::operator!=(StringView other) const { return !operator==(other); } inline bool Variant::operator!=(const Variant& other) const { return !operator==(other); } inline size_t Variant::size() const { return m_pType ? m_pType->getSize() : 0; } inline const char* Variant::c_str() const { PHANTOM_ASSERT(isString()); return (*(String*)_buffer()).c_str(); } inline bool Variant::isString() const { PHANTOM_ASSERT(phantom::lang::BuiltInTypes::TYPE_STRING); return m_pType == phantom::lang::BuiltInTypes::TYPE_STRING; } inline bool Variant::_as(lang::Type* a_pType, void* a_pDest) const { if(a_pType == nullptr || m_pType == nullptr) { return false; } if(m_pType->removeAllQualifiers()->isSame(a_pType->removeAllQualifiers())) { m_pType->copy(a_pDest, _buffer()); return true; } if (!GetTypeConverter().empty()) return GetTypeConverter()(a_pType, a_pDest, m_pType, _buffer()); else return m_pType->convert(a_pType, a_pDest, _buffer()); } inline Variant Variant::as(lang::Type* a_pType) const { if(a_pType == nullptr || m_pType == nullptr) { return phantom::Variant(); } Variant result; byte* pBuffer = (a_pType->getSize() > StaticBufferSize) ? (result.m_Buffer.dynamicBuffer = _Alloc(a_pType->getSize(), a_pType->getAlignment())) : result.m_Buffer.staticBuffer; result.m_pType = a_pType; if(m_pType->removeAllQualifiers()->isSame(a_pType->removeAllQualifiers())) { m_pType->copy(pBuffer, _buffer()); return result; } if (!GetTypeConverter().empty()) { if(GetTypeConverter()(a_pType, pBuffer, m_pType, _buffer())) return result; } else { if (m_pType->convert(a_pType, pBuffer, _buffer())) return result; } return Variant(); } inline void Variant::_release() { if(size() > StaticBufferSize) { m_pType->destroy(m_Buffer.dynamicBuffer); PHANTOM_FREE_ALIGNED(m_Buffer.dynamicBuffer); } else { m_pType->destroy(m_Buffer.staticBuffer); } } template<typename t_Ty> inline bool Variant::as(t_Ty* a_pDest) const { return as(PHANTOM_VARIANT_TYPEOF(t_Ty), a_pDest); } template<typename t_Ty> inline t_Ty Variant::as(bool* a_pOK) const { byte temp[sizeof(t_Ty)]; PHANTOM_STATIC_ASSERT(!std::is_class<t_Ty>::value, "template return type is a class, it must be a fundamental type" ", use 'as(t_Ty* a_pDest)' instead for class to have proper copy to pointed memory"); auto pType = PHANTOM_VARIANT_TYPEOF(t_Ty); pType->construct(&temp); if(a_pOK) { *a_pOK = as(pType, &temp); } else { as(pType, &temp); } return *((t_Ty*)&temp); } inline void Variant::toLiteral(StringBuffer& a_Buf) const { if(m_pType) m_pType->valueToLiteral(a_Buf, _buffer()); } inline void Variant::toString(StringBuffer& a_Buf) const { if(m_pType) m_pType->valueToString(a_Buf, _buffer()); } } // namespace phantom
32.058667
130
0.570621
[ "object" ]
1e0b1a0e88ddc6b74d2c3559b742dcb482a09692
32,783
cpp
C++
src/caffe/blob.cpp
naibaf7/caffe
29960153c828820b1abb55a5792283742f57caa2
[ "Intel", "BSD-2-Clause" ]
89
2015-04-20T01:25:01.000Z
2021-12-07T17:03:28.000Z
src/caffe/blob.cpp
Miaomz/caffe-opencl
505693d54298b89cf83b54778479087cff2f3bd6
[ "Intel", "BSD-2-Clause" ]
62
2015-06-18T13:11:20.000Z
2019-02-19T05:00:10.000Z
src/caffe/blob.cpp
Miaomz/caffe-opencl
505693d54298b89cf83b54778479087cff2f3bd6
[ "Intel", "BSD-2-Clause" ]
30
2015-07-05T17:08:09.000Z
2022-02-10T13:16:02.000Z
#include <climits> #include <vector> #include "caffe/blob.hpp" #include "caffe/backend/device.hpp" #include "caffe/common.hpp" #include "caffe/syncedmem.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/util/type_utils.hpp" #include "caffe/quantizer.hpp" #include "caffe/quantizer_creator.hpp" namespace caffe { // GPU AXPY helper inline void gpu_axpy(Device* dev, const uint_tp n, const half_fp alpha, vptr<const half_fp> x, vptr<half_fp> y) { #ifdef USE_HALF dev->template axpy<half_fp>(n, alpha, x, y); #else // USE_HALF NOT_IMPLEMENTED; #endif // USE_HALF } inline void gpu_axpy(Device* dev, const uint_tp n, const float alpha, vptr<const float> x, vptr<float> y) { #ifdef USE_SINGLE dev->template axpy<float>(n, alpha, x, y); #else // USE_SINGLE NOT_IMPLEMENTED; #endif // USE_SINGLE } inline void gpu_axpy(Device* dev, const uint_tp n, const double alpha, vptr<const double> x, vptr<double> y) { #ifdef USE_DOUBLE dev->template axpy<double>(n, alpha, x, y); #else // USE_DOUBLE NOT_IMPLEMENTED; #endif // USE_DOUBLE } inline void gpu_axpy(Device* dev, const uint_tp n, const uint8_t alpha, vptr<const uint8_t> x, vptr<uint8_t> y) { #ifdef USE_INT_QUANT_8 dev->template axpy<uint8_t>(n, alpha, x, y); #else // SE_INT_QUANT_8 NOT_IMPLEMENTED; #endif // SE_INT_QUANT_8 } inline void gpu_axpy(Device* dev, const uint_tp n, const uint16_t alpha, vptr<const uint16_t> x, vptr<uint16_t> y) { #ifdef USE_INT_QUANT_16 dev->template axpy<uint16_t>(n, alpha, x, y); #else // USE_INT_QUANT_16 NOT_IMPLEMENTED; #endif // USE_INT_QUANT_16 } inline void gpu_axpy(Device* dev, const uint_tp n, const uint32_t alpha, vptr<const uint32_t> x, vptr<uint32_t> y) { #ifdef USE_INT_QUANT_32 dev->template axpy<uint32_t>(n, alpha, x, y); #else // USE_INT_QUANT_32 NOT_IMPLEMENTED; #endif // USE_INT_QUANT_32 } inline void gpu_axpy(Device* dev, const uint_tp n, const uint64_t alpha, vptr<const uint64_t> x, vptr<uint64_t> y) { #ifdef USE_INT_QUANT_64 dev->template axpy<uint64_t>(n, alpha, x, y); #else // USE_INT_QUANT_64 NOT_IMPLEMENTED; #endif // USE_INT_QUANT_64 } // GPU DOT helper inline void gpu_dot(Device* dev, const uint_tp n, vptr<const half_fp> x, vptr<const half_fp> y, half_fp* out) { #ifdef USE_HALF dev->template dot<half_fp>(n, x, y, out); #else // USE_HALF NOT_IMPLEMENTED; #endif // USE_HALF } inline void gpu_dot(Device* dev, const uint_tp n, vptr<const float> x, vptr<const float> y, float* out) { #ifdef USE_SINGLE dev->template dot<float>(n, x, y, out); #else // USE_SINGLE NOT_IMPLEMENTED; #endif // USE_SINGLE } inline void gpu_dot(Device* dev, const uint_tp n, vptr<const double> x, vptr<const double> y, double* out) { #ifdef USE_DOUBLE dev->template dot<double>(n, x, y, out); #else // USE_DOUBLE NOT_IMPLEMENTED; #endif // USE_DOUBLE } inline void gpu_dot(Device* dev, const uint_tp n, vptr<const uint8_t> x, vptr<const uint8_t> y, uint8_t* out) { #ifdef USE_INT_QUANT_8 dev->template dot<uint8_t>(n, x, y, out); #else // SE_INT_QUANT_8 NOT_IMPLEMENTED; #endif // SE_INT_QUANT_8 } inline void gpu_dot(Device* dev, const uint_tp n, vptr<const uint16_t> x, vptr<const uint16_t> y, uint16_t* out) { #ifdef USE_INT_QUANT_16 dev->template dot<uint16_t>(n, x, y, out); #else // USE_INT_QUANT_16 NOT_IMPLEMENTED; #endif // USE_INT_QUANT_16 } inline void gpu_dot(Device* dev, const uint_tp n, vptr<const uint32_t> x, vptr<const uint32_t> y, uint32_t* out) { #ifdef USE_INT_QUANT_32 dev->template dot<uint32_t>(n, x, y, out); #else // USE_INT_QUANT_32 NOT_IMPLEMENTED; #endif // USE_INT_QUANT_32 } inline void gpu_dot(Device* dev, const uint_tp n, vptr<const uint64_t> x, vptr<const uint64_t> y, uint64_t* out) { #ifdef USE_INT_QUANT_64 dev->template dot<uint64_t>(n, x, y, out); #else // USE_INT_QUANT_64 NOT_IMPLEMENTED; #endif // USE_INT_QUANT_64 } // GPU ASUM helper inline void gpu_asum(Device* dev, const uint_tp n, vptr<const half_fp> x, half_fp* out) { #ifdef USE_HALF dev->template asum<half_fp>(n, x, out); #else // USE_HALF NOT_IMPLEMENTED; #endif // USE_HALF } inline void gpu_asum(Device* dev, const uint_tp n, vptr<const float> x, float* out) { #ifdef USE_SINGLE dev->template asum<float>(n, x, out); #else // USE_SINGLE NOT_IMPLEMENTED; #endif // USE_SINGLE } inline void gpu_asum(Device* dev, const uint_tp n, vptr<const double> x, double* out) { #ifdef USE_DOUBLE dev->template asum<double>(n, x, out); #else // USE_DOUBLE NOT_IMPLEMENTED; #endif // USE_DOUBLE } inline void gpu_asum(Device* dev, const uint_tp n, vptr<const uint8_t> x, uint8_t* out) { #ifdef USE_INT_QUANT_8 dev->template asum<uint8_t>(n, x, out); #else // SE_INT_QUANT_8 NOT_IMPLEMENTED; #endif // SE_INT_QUANT_8 } inline void gpu_asum(Device* dev, const uint_tp n, vptr<const uint16_t> x, uint16_t* out) { #ifdef USE_INT_QUANT_16 dev->template asum<uint16_t>(n, x, out); #else // USE_INT_QUANT_16 NOT_IMPLEMENTED; #endif // USE_INT_QUANT_16 } inline void gpu_asum(Device* dev, const uint_tp n, vptr<const uint32_t> x, uint32_t* out) { #ifdef USE_INT_QUANT_32 dev->template asum<uint32_t>(n, x, out); #else // USE_INT_QUANT_32 NOT_IMPLEMENTED; #endif // USE_INT_QUANT_32 } inline void gpu_asum(Device* dev, const uint_tp n, vptr<const uint64_t> x, uint64_t* out) { #ifdef USE_INT_QUANT_64 dev->template asum<uint64_t>(n, x, out); #else // USE_INT_QUANT_64 NOT_IMPLEMENTED; #endif // USE_INT_QUANT_64 } // GPU AXPY helper inline void gpu_scal(Device* dev, const uint_tp n, const half_fp alpha, vptr<half_fp> x) { #ifdef USE_HALF dev->template scal<half_fp>(n, alpha, x); #else // USE_HALF NOT_IMPLEMENTED; #endif // USE_HALF } inline void gpu_scal(Device* dev, const uint_tp n, const float alpha, vptr<float> x) { #ifdef USE_SINGLE dev->template scal<float>(n, alpha, x); #else // USE_SINGLE NOT_IMPLEMENTED; #endif // USE_SINGLE } inline void gpu_scal(Device* dev, const uint_tp n, const double alpha, vptr<double> x) { #ifdef USE_DOUBLE dev->template scal<double>(n, alpha, x); #else // USE_DOUBLE NOT_IMPLEMENTED; #endif // USE_DOUBLE } inline void gpu_scal(Device* dev, const uint_tp n, const uint8_t alpha, vptr<uint8_t> x) { #ifdef USE_INT_QUANT_8 dev->template scal<uint8_t>(n, alpha, x); #else // SE_INT_QUANT_8 NOT_IMPLEMENTED; #endif // SE_INT_QUANT_8 } inline void gpu_scal(Device* dev, const uint_tp n, const uint16_t alpha, vptr<uint16_t> x) { #ifdef USE_INT_QUANT_16 dev->template scal<uint16_t>(n, alpha, x); #else // USE_INT_QUANT_16 NOT_IMPLEMENTED; #endif // USE_INT_QUANT_16 } inline void gpu_scal(Device* dev, const uint_tp n, const uint32_t alpha, vptr<uint32_t> x) { #ifdef USE_INT_QUANT_32 dev->template scal<uint32_t>(n, alpha, x); #else // USE_INT_QUANT_32 NOT_IMPLEMENTED; #endif // USE_INT_QUANT_32 } inline void gpu_scal(Device* dev, const uint_tp n, const uint64_t alpha, vptr<uint64_t> x) { #ifdef USE_INT_QUANT_64 dev->template axpy<uint64_t>(n, alpha, x, y); #else // USE_INT_QUANT_64 NOT_IMPLEMENTED; #endif // USE_INT_QUANT_64 } template<typename Dtype> void Blob<Dtype>::Init() { this->quant_ = make_shared<Quantizer<Dtype, Dtype> >(this->device_); } template<> void Blob<int8_t>::Init() { } template<> void Blob<int16_t>::Init() { } template<> void Blob<int32_t>::Init() { } template<> void Blob<int64_t>::Init() { } template<typename Dtype> Blob<Dtype>::Blob(Device *dev) : BlobBase(dev) { Init(); } template<typename Dtype> bool Blob<Dtype>::Reshape(const int_tp num, const int_tp channels, const int_tp height, const int_tp width) { vector<int_tp> shape(4); shape[0] = num; shape[1] = channels; shape[2] = height; shape[3] = width; return Reshape(shape, shape); } template<typename Dtype> bool Blob<Dtype>::Reshape(const vector<int_tp>& shape) { return Reshape(shape, shape); } template<typename Dtype> bool Blob<Dtype>::Reshape(const vector<int_tp>& shape, const vector<int_tp>& shape_stride) { CHECK_LE(shape.size(), kMaxBlobAxes); count_ = 1; shape_.resize(shape.size()); shape_stride_.resize(shape_stride.size()); if (!shape_data_ || shape_data_->size() < shape.size() * sizeof(int_tp)) { shape_data_.reset( new SyncedMemory(shape.size() * sizeof(int_tp), device_)); } if (!shape_stride_data_ || shape_stride_data_->size() < shape.size() * sizeof(int_tp)) { shape_stride_data_.reset( new SyncedMemory(shape_stride.size() * sizeof(int_tp), device_)); } int_tp* shape_data = static_cast<int_tp*>( shape_data_->mutable_cpu_data()); int_tp* shape_stride_data = static_cast<int_tp*>( shape_stride_data_->mutable_cpu_data()); for (int_tp i = 0; i < shape.size(); ++i) { CHECK_GE(shape[i], 0); CHECK_GE(shape_stride[i], 0); if (count_ != 0) { #ifdef USE_INDEX_64 CHECK_LE(shape[i], LONG_MAX / count_) << "blob size exceeds INT_MAX"; CHECK_LE(shape_stride[i], LONG_MAX / count_) << "blob size exceeds INT_MAX"; #else CHECK_LE(shape[i], INT_MAX / count_) << "blob size exceeds INT_MAX"; CHECK_LE(shape_stride[i], INT_MAX / count_) << "blob size exceeds INT_MAX"; #endif // USE_INDEX_64 } count_ *= shape[i]; shape_[i] = shape[i]; shape_data[i] = shape[i]; shape_stride_[i] = shape_stride[i]; shape_stride_data[i] = shape_stride[i]; } if (count_ > capacity_) { capacity_ = count_; data_.reset(new SyncedMemory(capacity_ * sizeof(Dtype), device_)); diff_.reset(new SyncedMemory(capacity_ * sizeof(Dtype), device_)); return true; } return false; } template<typename Dtype> bool Blob<Dtype>::Reshape(const BlobShape& shape, const BlobShape& shape_stride) { CHECK_LE(shape.dim_size(), kMaxBlobAxes); vector<int_tp> shape_vec(shape.dim_size()); vector<int_tp> shape_stride_vec(shape.dim_size()); for (int_tp i = 0; i < shape.dim_size(); ++i) { shape_vec[i] = shape.dim(i); shape_stride_vec[i] = shape_stride.dim(i); } return Reshape(shape_vec, shape_stride_vec); } template<typename Dtype> bool Blob<Dtype>::Reshape(const BlobShape& shape) { CHECK_LE(shape.dim_size(), kMaxBlobAxes); vector<int_tp> shape_vec(shape.dim_size()); for (int_tp i = 0; i < shape.dim_size(); ++i) { shape_vec[i] = shape.dim(i); } return Reshape(shape_vec, shape_vec); } template<typename Dtype> bool Blob<Dtype>::ReshapeLike(const Blob<Dtype>& other) { return Reshape(other.shape(), other.shape_stride()); } template<typename Dtype> bool Blob<Dtype>::ReshapeLike(const BlobBase* other) { return Reshape(other->shape(), other->shape_stride()); } template<typename Dtype> Blob<Dtype>::Blob(const int_tp num, const int_tp channels, const int_tp height, const int_tp width, Device *dev) { // capacity_ must be initialized before calling Reshape capacity_ = 0; device_ = dev; Init(); Reshape(num, channels, height, width); } template<typename Dtype> Blob<Dtype>::Blob(const vector<int_tp>& shape, Device *dev) { // capacity_ must be initialized before calling Reshape capacity_ = 0; device_ = dev; Init(); Reshape(shape); } template<typename Dtype> uint_tp Blob<Dtype>::byte_count() const { return safe_sizeof<Dtype>() * count_; } template <typename Dtype> vptr<const int_tp> Blob<Dtype>::gpu_shape() const { CHECK(shape_data_); return shape_data_->gpu_data(); } template <typename Dtype> const Dtype* Blob<Dtype>::cpu_data() const { CHECK(data_); return static_cast<const Dtype*>(data_->cpu_data()); } template<typename Dtype> void Blob<Dtype>::set_cpu_data(Dtype* data) { CHECK(data); // Make sure CPU and GPU sizes remain equal size_t size = count_ * safe_sizeof<Dtype>(); if (data_->size() != size) { data_.reset(new SyncedMemory(size, device_)); diff_.reset(new SyncedMemory(size, device_)); } data_->set_cpu_data(data); } template<typename Dtype> vptr<const Dtype> Blob<Dtype>::gpu_data() const { CHECK(data_); return data_->gpu_data(); } template <typename Dtype> void Blob<Dtype>::set_gpu_data(vptr<Dtype> data) { // Make sure CPU and GPU sizes remain equal size_t size = count_ * sizeof(Dtype); if (data_->size() != size) { data_.reset(new SyncedMemory(size, device_)); diff_.reset(new SyncedMemory(size, device_)); } data_->set_gpu_data(data); } template <typename Dtype> const Dtype* Blob<Dtype>::cpu_diff() const { CHECK(diff_); return (const Dtype*) diff_->cpu_data(); } template<typename Dtype> vptr<const Dtype> Blob<Dtype>::gpu_diff() const { CHECK(diff_); return diff_->gpu_data(); } template<typename Dtype> Dtype* Blob<Dtype>::mutable_cpu_data() { CHECK(data_); return static_cast<Dtype*>(data_->mutable_cpu_data()); } template<typename Dtype> vptr<Dtype> Blob<Dtype>::mutable_gpu_data() { CHECK(data_); return vptr<Dtype>(data_->mutable_gpu_data()); } template<typename Dtype> Dtype* Blob<Dtype>::mutable_cpu_diff() { CHECK(diff_); return static_cast<Dtype*>(diff_->mutable_cpu_data()); } template<typename Dtype> vptr<Dtype> Blob<Dtype>::mutable_gpu_diff() { CHECK(diff_); return diff_->mutable_gpu_data(); } template<typename Dtype> void Blob<Dtype>::ShareData(const Blob& other) { CHECK_EQ(count_, other.count()); data_ = other.data(); } template<typename Dtype> void Blob<Dtype>::ShareDiff(const Blob& other) { CHECK_EQ(count_, other.count()); diff_ = other.diff(); } void BlobBase::ShareDataBase(const BlobBase* other) { CHECK_LE(byte_count(), other->byte_count()); data_ = other->data(); } void BlobBase::ShareDiffBase(const BlobBase* other) { CHECK_LE(byte_count(), other->byte_count()); diff_ = other->diff(); } // The "update" method is used for parameter blobs in a Net, which are stored // as Blob<float> or Blob<double> -- hence we do not define it for // Blob<int_tp> or Blob<int_tp>. template<typename Dtype> void Blob<Dtype>::Update() { // We will perform update based on where the data is located. switch (data_->head()) { case SyncedMemory::HEAD_AT_CPU: { // perform computation on CPU caffe_axpy<Dtype>(count_, Dtype(-1), static_cast<const Dtype*>(diff_->cpu_data()), static_cast<Dtype*>(data_->mutable_cpu_data())); break; } case SyncedMemory::HEAD_AT_GPU: case SyncedMemory::SYNCED: { #ifndef CPU_ONLY // perform computation on GPU gpu_axpy(device_, count_, Dtype(-1), diff_->gpu_data(), data_->mutable_gpu_data()); #else NO_GPU; #endif break; } default: LOG(FATAL)<< "Syncedmem not initialized."; } } template<> void Blob<int8_t>::Update() { NOT_IMPLEMENTED; } template<> void Blob<int16_t>::Update() { NOT_IMPLEMENTED; } template<> void Blob<int32_t>::Update() { NOT_IMPLEMENTED; } template<> void Blob<int64_t>::Update() { NOT_IMPLEMENTED; } template<typename Dtype> Dtype Blob<Dtype>::asum_data() const { if (!data_) { return (Dtype)0; } switch (data_->head()) { case SyncedMemory::HEAD_AT_CPU: return caffe_asum(count_, cpu_data()); case SyncedMemory::HEAD_AT_GPU: case SyncedMemory::SYNCED: { #ifndef CPU_ONLY Dtype asum; gpu_asum(device_, count_, gpu_data(), &asum); return asum; #else NO_GPU; #endif } case SyncedMemory::UNINITIALIZED: return 0; default: LOG(FATAL)<< "Unknown SyncedMemory head state: " << data_->head(); } return 0; } template<> int8_t Blob<int8_t>::asum_data() const { NOT_IMPLEMENTED; return 0; } template<> int16_t Blob<int16_t>::asum_data() const { NOT_IMPLEMENTED; return 0; } template<> int32_t Blob<int32_t>::asum_data() const { NOT_IMPLEMENTED; return 0; } template<> int64_t Blob<int64_t>::asum_data() const { NOT_IMPLEMENTED; return 0; } template<typename Dtype> Dtype Blob<Dtype>::asum_diff() const { if (!diff_) { return 0; } switch (diff_->head()) { case SyncedMemory::HEAD_AT_CPU: return caffe_asum(count_, cpu_diff()); case SyncedMemory::HEAD_AT_GPU: case SyncedMemory::SYNCED: { #ifndef CPU_ONLY Dtype asum; gpu_asum(device_, count_, gpu_diff(), &asum); return asum; #else NO_GPU; #endif } case SyncedMemory::UNINITIALIZED: return 0; default: LOG(FATAL)<< "Unknown SyncedMemory head state: " << diff_->head(); } return 0; } template<> int8_t Blob<int8_t>::asum_diff() const { NOT_IMPLEMENTED; return 0; } template<> int16_t Blob<int16_t>::asum_diff() const { NOT_IMPLEMENTED; return 0; } template<> int32_t Blob<int32_t>::asum_diff() const { NOT_IMPLEMENTED; return 0; } template<> int64_t Blob<int64_t>::asum_diff() const { NOT_IMPLEMENTED; return 0; } template<typename Dtype> Dtype Blob<Dtype>::sumsq_data() const { Dtype sumsq = 0; const Dtype* data; vptr<const Dtype> gpu_vptr_data; if (!data_) { return 0; } switch (data_->head()) { case SyncedMemory::HEAD_AT_CPU: { data = cpu_data(); sumsq = caffe_dot(count_, data, data); break; } case SyncedMemory::HEAD_AT_GPU: case SyncedMemory::SYNCED: { #ifndef CPU_ONLY gpu_vptr_data = gpu_data(); gpu_dot(device_, count_, gpu_vptr_data, gpu_vptr_data, &sumsq); #else NO_GPU; #endif break; } case SyncedMemory::UNINITIALIZED: return 0; default: LOG(FATAL)<< "Unknown SyncedMemory head state: " << data_->head(); } return sumsq; } template<> int8_t Blob<int8_t>::sumsq_data() const { NOT_IMPLEMENTED; return 0; } template<> int16_t Blob<int16_t>::sumsq_data() const { NOT_IMPLEMENTED; return 0; } template<> int32_t Blob<int32_t>::sumsq_data() const { NOT_IMPLEMENTED; return 0; } template<> int64_t Blob<int64_t>::sumsq_data() const { NOT_IMPLEMENTED; return 0; } template<typename Dtype> Dtype Blob<Dtype>::sumsq_diff() const { Dtype sumsq; Dtype gpu_sumsq; const Dtype* diff; vptr<const Dtype> gpu_vptr_diff; if (!diff_) { return 0; } switch (diff_->head()) { case SyncedMemory::HEAD_AT_CPU: { diff = cpu_diff(); sumsq = caffe_dot(count_, diff, diff); break; } case SyncedMemory::HEAD_AT_GPU: case SyncedMemory::SYNCED: { #ifndef CPU_ONLY gpu_vptr_diff = gpu_diff(); gpu_dot(device_, count_, gpu_vptr_diff, gpu_vptr_diff, &gpu_sumsq); sumsq = gpu_sumsq; #else NO_GPU; #endif break; } case SyncedMemory::UNINITIALIZED: return 0; default: LOG(FATAL)<< "Unknown SyncedMemory head state: " << data_->head(); } return sumsq; } template<> int8_t Blob<int8_t>::sumsq_diff() const { NOT_IMPLEMENTED; return 0; } template<> int16_t Blob<int16_t>::sumsq_diff() const { NOT_IMPLEMENTED; return 0; } template<> int32_t Blob<int32_t>::sumsq_diff() const { NOT_IMPLEMENTED; return 0; } template<> int64_t Blob<int64_t>::sumsq_diff() const { NOT_IMPLEMENTED; return 0; } template<typename Dtype> void Blob<Dtype>::scale_data(Dtype scale_factor) { Dtype* data; vptr<Dtype> gpu_data; if (!data_) { return; } switch (data_->head()) { case SyncedMemory::HEAD_AT_CPU: { data = mutable_cpu_data(); caffe_scal(count_, scale_factor, data); return; } case SyncedMemory::HEAD_AT_GPU: case SyncedMemory::SYNCED: { #ifndef CPU_ONLY gpu_data = mutable_gpu_data(); gpu_scal(device_, count_, scale_factor, gpu_data); return; #else NO_GPU; #endif } case SyncedMemory::UNINITIALIZED: return; default: LOG(FATAL)<< "Unknown SyncedMemory head state: " << data_->head(); } } template<> void Blob<int8_t>::scale_data(int8_t scale_factor) { NOT_IMPLEMENTED; } template<> void Blob<int16_t>::scale_data(int16_t scale_factor) { NOT_IMPLEMENTED; } template<> void Blob<int32_t>::scale_data(int32_t scale_factor) { NOT_IMPLEMENTED; } template<> void Blob<int64_t>::scale_data(int64_t scale_factor) { NOT_IMPLEMENTED; } template<typename Dtype> void Blob<Dtype>::scale_data(const void* scale_factor) { Dtype converted_scale_factor; this->quant_->Forward_cpu(1, scale_factor, &converted_scale_factor); this->scale_data(converted_scale_factor); } template<typename Dtype> void Blob<Dtype>::scale_diff(Dtype scale_factor) { Dtype* diff; vptr<Dtype> gpu_vptr_diff; if (!diff_) { return; } switch (diff_->head()) { case SyncedMemory::HEAD_AT_CPU: { diff = mutable_cpu_diff(); caffe_scal(count_, scale_factor, diff); return; } case SyncedMemory::HEAD_AT_GPU: case SyncedMemory::SYNCED: { #ifndef CPU_ONLY gpu_vptr_diff = mutable_gpu_diff(); gpu_scal(device_, count_, scale_factor, gpu_vptr_diff); return; #else NO_GPU; #endif } case SyncedMemory::UNINITIALIZED: return; default: LOG(FATAL)<< "Unknown SyncedMemory head state: " << diff_->head(); } } template<> void Blob<int8_t>::scale_diff(int8_t scale_factor) { NOT_IMPLEMENTED; } template<> void Blob<int16_t>::scale_diff(int16_t scale_factor) { NOT_IMPLEMENTED; } template<> void Blob<int32_t>::scale_diff(int32_t scale_factor) { NOT_IMPLEMENTED; } template<> void Blob<int64_t>::scale_diff(int64_t scale_factor) { NOT_IMPLEMENTED; } template<typename Dtype> void Blob<Dtype>::scale_diff(const void* scale_factor) { Dtype converted_scale_factor; this->quant_->Forward_cpu(1, scale_factor, &converted_scale_factor); this->scale_diff(converted_scale_factor); } bool BlobBase::ShapeEquals(const BlobProto& other) { if (other.has_num() || other.has_channels() || other.has_height() || other.has_width()) { // Using deprecated 4D Blob dimensions -- // shape is (num, channels, height, width). // Note: we do not use the normal Blob::num(), Blob::channels(), etc. // methods as these index from the beginning of the blob shape, where legacy // parameter blobs were indexed from the end of the blob shape (e.g., bias // Blob shape (1 X 1 X 1 X n), IP layer weight Blob shape (1 X 1 X m X n)). return shape_.size() <= 4 && LegacyShape(-4) == other.num() && LegacyShape(-3) == other.channels() && LegacyShape(-2) == other.height() && LegacyShape(-1) == other.width(); } vector<int_tp> other_shape(other.shape().dim_size()); for (int_tp i = 0; i < other.shape().dim_size(); ++i) { other_shape[i] = other.shape().dim(i); } return shape_ == other_shape; } template<typename Dtype> void Blob<Dtype>::CopyFrom(const Blob& source, bool copy_diff, bool reshape) { if (source.count() != count_ || source.shape() != shape_) { if (reshape) { ReshapeLike(source); } else { LOG(FATAL)<< "Trying to copy blobs of different sizes."; } } switch (Caffe::mode()) { case Caffe::GPU: { if (copy_diff) { device_->copy(count_, source.gpu_diff(), vptr<Dtype>(diff_->mutable_gpu_data())); } else { device_->copy(count_, source.gpu_data(), vptr<Dtype>(data_->mutable_gpu_data())); } break; } case Caffe::CPU: { if (copy_diff) { caffe_copy(count_, source.cpu_diff(), static_cast<Dtype*>(diff_->mutable_cpu_data())); } else { caffe_copy(count_, source.cpu_data(), static_cast<Dtype*>(data_->mutable_cpu_data())); } break; } default: LOG(FATAL)<< "Unknown caffe mode."; } } template<typename Dtype> void Blob<Dtype>::FromProto(const BlobProto& proto, bool reshape) { if (reshape) { vector<int_tp> shape; if (proto.has_num() || proto.has_channels() || proto.has_height() || proto.has_width()) { // Using deprecated 4D Blob dimensions -- // shape is (num, channels, height, width). shape.resize(4); shape[0] = proto.num(); shape[1] = proto.channels(); shape[2] = proto.height(); shape[3] = proto.width(); } else { shape.resize(proto.shape().dim_size()); for (int_tp i = 0; i < proto.shape().dim_size(); ++i) { shape[i] = proto.shape().dim(i); } } Reshape(shape); } else { CHECK(ShapeEquals(proto)) << "shape mismatch (reshape not set)"; } DataType proto_data_type = proto.has_data_type() ? proto.data_type() : (proto.data_size() > 0 || proto.diff_size() > 0 ? CAFFE_FLOAT : CAFFE_DOUBLE); QuantizerParameter param; if (this->quant_) { param.CopyFrom(this->quant_->quant_param()); } param.set_input_data_type(proto_data_type); param.set_output_data_type(this->data_type()); shared_ptr<QuantizerBase> quant = CreateQuantizer(param); // Copy data if (proto.double_data_size() > 0) { Dtype* data_vec = mutable_cpu_data(); CHECK_EQ(count_, proto.double_data_size()); if (quant->needs_quantization()) { for (int_tp i = 0; i < count_; ++i) { double proto_data = proto.double_data(i); quant->Forward_cpu(1, static_cast<const void*>(&proto_data), static_cast<void*>(&(data_vec[i]))); } } else { for (int_tp i = 0; i < count_; ++i) { data_vec[i] = proto.double_data(i); } } } else if (proto.data_size() > 0) { Dtype* data_vec = mutable_cpu_data(); CHECK_EQ(count_, proto.data_size()); if (quant->needs_quantization()) { for (int_tp i = 0; i < count_; ++i) { float proto_data = proto.data(i); quant->Forward_cpu(1, static_cast<const void*>(&proto_data), static_cast<void*>(&(data_vec[i]))); } } else { for (int_tp i = 0; i < count_; ++i) { data_vec[i] = proto.data(i); } } } else if (proto.has_packed_data()) { Dtype* data_vec = mutable_cpu_data(); const void* proto_data = proto.packed_data().c_str(); quant->Forward_cpu(count_, static_cast<const void*>(proto_data), static_cast<void*>(data_vec)); } // Copy diff if (proto.double_diff_size() > 0) { Dtype* diff_vec = mutable_cpu_diff(); CHECK_EQ(count_, proto.double_diff_size()); if (quant->needs_quantization()) { for (int_tp i = 0; i < count_; ++i) { double proto_diff = proto.double_diff(i); quant->Forward_cpu(1, static_cast<const void*>(&proto_diff), static_cast<void*>(&(diff_vec[i]))); } } else { for (int_tp i = 0; i < count_; ++i) { diff_vec[i] = proto.double_diff(i); } } } else if (proto.diff_size() > 0) { Dtype* diff_vec = mutable_cpu_diff(); CHECK_EQ(count_, proto.diff_size()); if (quant->needs_quantization()) { for (int_tp i = 0; i < count_; ++i) { float proto_diff = proto.diff(i); quant->Forward_cpu(1, static_cast<const void*>(&proto_diff), static_cast<void*>(&(diff_vec[i]))); } } else { for (int_tp i = 0; i < count_; ++i) { diff_vec[i] = proto.diff(i); } } } else if (proto.has_packed_diff()) { Dtype* diff_vec = mutable_cpu_diff(); const void* proto_diff = proto.packed_diff().c_str(); quant->Forward_cpu(count_, static_cast<const void*>(proto_diff), static_cast<void*>(diff_vec)); } } template<> void Blob<float>::ToProto(BlobProto* proto, bool write_diff) const { proto->clear_shape(); for (int_tp i = 0; i < shape_.size(); ++i) { proto->mutable_shape()->add_dim(shape_[i]); proto->mutable_shape_stride()->add_dim(shape_stride_[i]); } proto->set_data_type(this->data_type()); proto->clear_data(); proto->clear_diff(); proto->clear_double_data(); proto->clear_double_diff(); proto->clear_packed_data(); proto->clear_packed_diff(); const float* data_vec = cpu_data(); for (int_tp i = 0; i < count_; ++i) { proto->add_data(data_vec[i]); } if (write_diff) { const float* diff_vec = cpu_diff(); for (int_tp i = 0; i < count_; ++i) { proto->add_diff(diff_vec[i]); } } } template<> void Blob<double>::ToProto(BlobProto* proto, bool write_diff) const { proto->clear_shape(); for (int_tp i = 0; i < shape_.size(); ++i) { proto->mutable_shape()->add_dim(shape_[i]); proto->mutable_shape_stride()->add_dim(shape_stride_[i]); } proto->set_data_type(this->data_type()); proto->clear_data(); proto->clear_diff(); proto->clear_double_data(); proto->clear_double_diff(); proto->clear_packed_data(); proto->clear_packed_diff(); const double* data_vec = cpu_data(); for (int_tp i = 0; i < count_; ++i) { proto->add_double_data(data_vec[i]); } if (write_diff) { const double* diff_vec = cpu_diff(); for (int_tp i = 0; i < count_; ++i) { proto->add_double_diff(diff_vec[i]); } } } template<typename Dtype> void Blob<Dtype>::ToProto(BlobProto* proto, bool write_diff) const { proto->clear_shape(); for (int_tp i = 0; i < shape_.size(); ++i) { proto->mutable_shape()->add_dim(shape_[i]); proto->mutable_shape_stride()->add_dim(shape_stride_[i]); } proto->set_data_type(this->data_type()); proto->clear_data(); proto->clear_diff(); proto->clear_double_data(); proto->clear_double_diff(); proto->clear_packed_data(); proto->clear_packed_diff(); const char* data_vec = reinterpret_cast<const char*>(cpu_data()); proto->set_packed_data(data_vec, byte_count()); if (write_diff) { const char* diff_vec = reinterpret_cast<const char*>(cpu_diff()); proto->set_packed_data(diff_vec, byte_count()); } } template<typename Dtype> DataType Blob<Dtype>::data_type() const { return proto_data_type<Dtype>(); } template<typename Dtype> void Blob<Dtype>::asum_data(void* out) const { Dtype val = asum_data(); this->quant_->Backward_cpu(1, static_cast<void*>(&val), out); } template<typename Dtype> void Blob<Dtype>::asum_diff(void* out) const { Dtype val = asum_diff(); this->quant_->Backward_cpu(1, static_cast<void*>(&val), out); } template<typename Dtype> void Blob<Dtype>::sumsq_data(void* out) const { Dtype val = sumsq_data(); this->quant_->Backward_cpu(1, static_cast<void*>(&val), out); } template<typename Dtype> void Blob<Dtype>::sumsq_diff(void* out) const { Dtype val = sumsq_data(); this->quant_->Backward_cpu(1, static_cast<void*>(&val), out); } template<typename Dtype> void Blob<Dtype>::cpu_data(void* out) const { CHECK(data_->mutable_cpu_data()); this->quant_->Backward_cpu(count(), data_->mutable_cpu_data(), out); } template<typename Dtype> void Blob<Dtype>::cpu_diff(void* out) const { CHECK(diff_->mutable_cpu_data()); this->quant_->Backward_cpu(count(), diff_->mutable_cpu_data(), out); } template<typename Dtype> void Blob<Dtype>::gpu_data(vptr<void> out) const { this->quant_->Backward_gpu(count(), data_->mutable_gpu_data(), out); } template<typename Dtype> void Blob<Dtype>::gpu_diff(vptr<void> out) const { this->quant_->Backward_gpu(count(), diff_->mutable_gpu_data(), out); } template<typename Dtype> void Blob<Dtype>::set_cpu_data(const void* const in) { CHECK(data_->cpu_data()); this->quant_->Forward_cpu(count(), in, data_->mutable_cpu_data()); } template<typename Dtype> void Blob<Dtype>::set_cpu_diff(const void* const in) { CHECK(diff_->cpu_data()); this->quant_->Forward_cpu(count(), in, diff_->mutable_cpu_data()); } template<typename Dtype> void Blob<Dtype>::set_gpu_data(vptr<const void> in) { this->quant_->Forward_gpu(count(), in, data_->mutable_gpu_data()); } template<typename Dtype> void Blob<Dtype>::set_gpu_diff(vptr<const void> in) { this->quant_->Forward_gpu(count(), in, diff_->mutable_gpu_data()); } template<typename Dtype> void Blob<Dtype>::Clear() { switch (Caffe::mode()) { case Caffe::CPU: caffe_set(count(), static_cast<Dtype>(0), mutable_cpu_diff()); break; case Caffe::GPU: #ifndef CPU_ONLY device_->set<Dtype>(count(), static_cast<Dtype>(0), mutable_gpu_diff()); #else NO_GPU; #endif break; } } INSTANTIATE_CLASS_1T(Blob, (half_fp)(float)(double)); INSTANTIATE_CLASS_1T(Blob, (uint8_t)(uint16_t)(uint32_t)(uint64_t)); INSTANTIATE_CLASS_1T(Blob, (int8_t)(int16_t)(int32_t)(int64_t)); } // namespace caffe
28.38355
86
0.658207
[ "shape", "vector" ]
1e0b7329df7877b1baa963abbfde25354145b627
692
cpp
C++
Util/IDTriple.cpp
SoftlySpoken/gStore
b2cf71288ccef376640000965aff7c430101446a
[ "BSD-3-Clause" ]
150
2015-01-14T15:06:38.000Z
2018-08-28T09:34:17.000Z
Util/IDTriple.cpp
SoftlySpoken/gStore
b2cf71288ccef376640000965aff7c430101446a
[ "BSD-3-Clause" ]
28
2015-05-11T02:45:39.000Z
2018-08-24T11:43:17.000Z
Util/IDTriple.cpp
SoftlySpoken/gStore
b2cf71288ccef376640000965aff7c430101446a
[ "BSD-3-Clause" ]
91
2015-05-04T09:52:41.000Z
2018-08-18T13:02:15.000Z
#include "IDTriple.h" bool IDTriple::operator < (const IDTriple& a) const { if(this->subject < a.get_subject()) return true; else if(this->subject > a.get_subject()) return false; else { if(this->predicate < a.get_predicate()) return true; else if(this->predicate > a.get_predicate()) return false; else { if(this->object <= a.get_object()) return true; else if(this->object > a.get_object()) return false; } } } bool IDTriple::operator > (const IDTriple& a) const { return !(*this < a ); } bool IDTriple::operator = (const IDTriple& a) const { return (this->subject == a.get_subject() && this->predicate == a.get_predicate() && this->object == a.get_object()); }
23.066667
117
0.66185
[ "object" ]
1e0eb9c103a71df75abaa97b62e4f670a880004f
483
hpp
C++
src/Kononov/Task5/Renderable.hpp
sadads1337/fit-gl
88d9ae1f1935301d71ae6e090aff24e6829a7580
[ "MIT" ]
2
2021-04-25T15:18:40.000Z
2022-02-27T15:44:04.000Z
src/Kononov/Task5/Renderable.hpp
sadads1337/fit-gl
88d9ae1f1935301d71ae6e090aff24e6829a7580
[ "MIT" ]
31
2021-02-17T21:12:59.000Z
2021-05-26T07:06:59.000Z
src/Kononov/Task5/Renderable.hpp
sadads1337/fit-gl
88d9ae1f1935301d71ae6e090aff24e6829a7580
[ "MIT" ]
9
2021-02-08T08:52:51.000Z
2022-02-27T15:43:55.000Z
#pragma once #include <optional> #include "Geometry.hpp" namespace Kononov { class Renderable { public: Renderable() = default; Renderable(const Renderable &) = default; Renderable(Renderable &&) noexcept = default; virtual ~Renderable() = default; Renderable &operator=(const Renderable &) = default; Renderable &operator=(Renderable &&) noexcept = default; [[nodiscard]] virtual std::optional<RayHit> getHit(const Ray &ray) const = 0; }; } // namespace Kononov
21.954545
79
0.710145
[ "geometry" ]
1f6154db3fd310b80559df4b7c95094d61c18a8d
10,868
cpp
C++
goodEatsSystem/src/System.cpp
PashaBarahimi/GoodEatsWeb
a8c173298323b072c973a8218bb63485fc1aba33
[ "MIT" ]
null
null
null
goodEatsSystem/src/System.cpp
PashaBarahimi/GoodEatsWeb
a8c173298323b072c973a8218bb63485fc1aba33
[ "MIT" ]
null
null
null
goodEatsSystem/src/System.cpp
PashaBarahimi/GoodEatsWeb
a8c173298323b072c973a8218bb63485fc1aba33
[ "MIT" ]
null
null
null
#include "include/System.hpp" System::~System() { for (Chef* chef : chefs_) delete chef; for (User* user : users_) delete user; for (Shelf* shelf : shelves_) delete shelf; for (Recipe* recipe : recipes_) delete recipe; for (Recipe* recipe : deletedRecipes_) delete recipe; } std::string System::randString(int length) { std::string str(length, '0'); const char charset[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; std::generate_n(str.begin(), length, [charset]() -> char {return charset[rand() % (sizeof(charset) - 1)]; }); return str; } std::string System::sessionIdGenerator() { while (true) { const std::string id = randString(9); const auto uItr = userIds_.find("u" + id); if (uItr != userIds_.end()) continue; const auto cItr = chefIds_.find("c" + id); if (cItr != chefIds_.end()) continue; return id; } } std::string System::signUp(std::string& username, std::string& password, MemberType type) { checkMemberType(MemberType::NA); if (findInstance(username, users_, &User::checkNameCredential) != nullptr || findInstance(username, chefs_, &Chef::checkNameCredential) != nullptr) throw BadRequest("Username Already Exists!"); User* user; Chef* chef; const std::string sessionId = sessionIdGenerator(); switch (type) { case MemberType::User: user = new User(username, password); userIds_["u" + sessionId] = user; users_.insert(std::upper_bound(users_.begin(), users_.end(), user, compareByName<User*>), user); return "u" + sessionId; case MemberType::Chef: chef = new Chef(username, password); chefIds_["c" + sessionId] = chef; chefs_.insert(std::upper_bound(chefs_.begin(), chefs_.end(), chef, compareByName<Chef*>), chef); return "c" + sessionId; case MemberType::NA: throw BadRequest("Wrong Member Type!"); } return std::string(); } std::string System::login(std::string& username, std::string& password) { checkMemberType(MemberType::NA); const std::string sessionId = sessionIdGenerator(); User* user = findInstance(username, users_, &User::checkNameCredential); if (user != nullptr) { if (user->isPasswordCorrect(password)) { userIds_["u" + sessionId] = user; return "u" + sessionId; } throw BadRequest("Wrong Password!"); } Chef* chef = findInstance(username, chefs_, &Chef::checkNameCredential); if (chef == nullptr) throw BadRequest("Username Doesn't Exist!"); if (chef->isPasswordCorrect(password)) { chefIds_["c" + sessionId] = chef; return "c" + sessionId; } throw BadRequest("Wrong Password!"); } System::MemberType System::checkSessionId(std::string id) { if (id.empty()) { loggedInMember_ = MemberType::NA; return MemberType::NA; } const char identifier = id[0]; if (identifier == 'u') { const auto itr = userIds_.find(id); if (itr == userIds_.end()) return MemberType::NA; user_ = (*itr).second; chef_ = nullptr; loggedInMember_ = MemberType::User; return MemberType::User; } if (identifier == 'c') { const auto itr = chefIds_.find(id); if (itr == chefIds_.end()) return MemberType::NA; user_ = nullptr; chef_ = (*itr).second; loggedInMember_ = MemberType::Chef; return MemberType::Chef; } loggedInMember_ = MemberType::NA; return MemberType::NA; } void System::logout(std::string sessionId) { if (loggedInMember_ == MemberType::NA) throw PermissionDenied("Login First!"); if (loggedInMember_ == MemberType::User) { user_->logout(); const auto itr = userIds_.find(sessionId); if (itr != userIds_.end()) userIds_.erase(itr); } else if (loggedInMember_ == MemberType::Chef) { const auto itr = chefIds_.find(sessionId); if (itr != chefIds_.end()) chefIds_.erase(itr); } } std::vector<Recipe::InterfaceRecipe> System::getRecipesList() const { checkMemberType(MemberType::User); std::vector<Recipe::InterfaceRecipe> recipes; auto mainRecipes = recipes_; auto filters = user_->getFilters(); for (auto* filter : filters) if (filter != nullptr) mainRecipes = filter->meetFilter(mainRecipes); for (Recipe* rec : mainRecipes) recipes.push_back(rec->getInterfaceRecipe()); return recipes; } std::vector<Recipe::InterfaceRecipe> System::getAllRecipesForShelfEdit(int shelfId) const { checkMemberType(MemberType::User); std::vector<Recipe::InterfaceRecipe> recipes; for (auto* rec : recipes_) recipes.push_back(rec->getInterfaceRecipe()); Shelf* shelf = findInstance(shelfId, shelves_, &Shelf::checkIdCredential); if (shelf == nullptr) throw NotFoundError("Shelf Not Found!"); std::vector<Recipe::InterfaceRecipe> shelfRecipes = shelf->getInterfaceShelf().recipes; std::vector<Recipe::InterfaceRecipe> deletedRecipes; for (auto* rec : deletedRecipes_) deletedRecipes.push_back(rec->getInterfaceRecipe()); for (const auto& rec : shelfRecipes) { const auto itr = std::find_if(deletedRecipes.begin(), deletedRecipes.end(), [&rec](Recipe::InterfaceRecipe& recipe) ->bool {return rec.id == recipe.id; }); if (itr != deletedRecipes.end()) recipes.insert(std::upper_bound(recipes.begin(), recipes.end(), rec, [](const Recipe::InterfaceRecipe& first, const Recipe::InterfaceRecipe& second) -> bool {return first.name < second.name; }), rec); } return recipes; } Recipe::InterfaceRecipe System::getRecipeInfo(int recipeId) const { checkMemberType(MemberType::User); Recipe* recipe = findInstance(recipeId, recipes_, &Recipe::checkIdCredential); if (recipe == nullptr) throw NotFoundError("Recipe Not Found!"); return recipe->getInterfaceRecipe(user_); } void System::deleteAllShelfRecipes(int shelfId) { checkMemberType(MemberType::User); Shelf* shelf = findInstance(shelfId, shelves_, &Shelf::checkIdCredential); if (shelf == nullptr) throw NotFoundError("Shelf Not Found!"); shelf->deleteAllRecipes(); } void System::rate(int recipeId, double score) { checkMemberType(MemberType::User); Recipe* recipe = findInstance(recipeId, recipes_, &Recipe::checkIdCredential); if (recipe == nullptr) throw NotFoundError("Recipe Not Found!"); if (score < 0 || score > 5) throw BadRequest("Wrong Score!"); recipe->rate(user_, score); } void System::makeShelf(std::string& name) { checkMemberType(MemberType::User); Shelf* shelf = new Shelf(name, static_cast<int>(shelves_.size() + 1)); shelves_.push_back(shelf); user_->addShelf(shelf); } std::vector<Shelf::InterfaceShelf> System::getUsersShelves() const { checkMemberType(MemberType::User); return user_->getInterfaceShelves(); } void System::addRecipeToShelf(int shelfId, int recipeId) { checkMemberType(MemberType::User); Shelf* shelf = findInstance(shelfId, shelves_, &Shelf::checkIdCredential); if (shelf == nullptr) throw PermissionDenied("Shelf Not Found!"); // Either Not Found or Bad Request or Permission Denied if (!user_->doesShelfExist(shelf)) throw PermissionDenied("This Shelf Is Not Yours!"); Recipe* recipe = findInstance(recipeId, recipes_, &Recipe::checkIdCredential); if (recipe == nullptr) { recipe = findInstance(recipeId, deletedRecipes_, &Recipe::checkIdCredential); if (recipe == nullptr) throw NotFoundError("Recipe Not Found!"); // Either Not Found or Bad Request } if (!shelf->addRecipe(recipe)) throw BadRequest("Recipe Already Exists!"); } Shelf::InterfaceShelf System::getShelf(int shelfId) const { checkMemberType(MemberType::User); Shelf* shelf = findInstance(shelfId, shelves_, &Shelf::checkIdCredential); if (shelf == nullptr) throw NotFoundError("Shelf Not Found!"); return shelf->getInterfaceShelf(); } void System::deleteRecipeFromShelf(int shelfId, int recipeId) { checkMemberType(MemberType::User); Shelf* shelf = findInstance(shelfId, shelves_, &Shelf::checkIdCredential); if (shelf == nullptr) throw PermissionDenied("Shelf Doesn't Exist!"); // Either Permission Denied or Not Found if (!user_->doesShelfExist(shelf)) throw PermissionDenied("This Shelf Is Not Yours!"); Recipe* recipe = findInstance(recipeId, recipes_, &Recipe::checkIdCredential); if (recipe == nullptr) throw BadRequest("Recipe Doesn't Exist!"); // Either Bad Request or Not Found if (!shelf->removeRecipe(recipe)) throw BadRequest("Recipe Is Not In The Shelf!"); } void System::makeRecipe(std::string& title, std::vector<std::string>& ingredients, bool isVegetarian, int minutesToReady, std::vector<std::string>& tags, std::string& imageAddress) { checkMemberType(MemberType::Chef); Recipe* recipe = new Recipe(title, recipesCount_ + 1, isVegetarian, ingredients, minutesToReady, tags, imageAddress); recipesCount_++; chef_->addRecipe(recipe); recipes_.insert(std::upper_bound(recipes_.begin(), recipes_.end(), recipe, compareByName<Recipe*>), recipe); } void System::deleteRecipe(int recipeId) { checkMemberType(MemberType::Chef); Recipe* recipe = findInstance(recipeId, recipes_, &Recipe::checkIdCredential); if (recipe == nullptr) throw PermissionDenied("Recipe Doesn't Exist!"); // Either Permission Denied or Not Found if (!chef_->doesRecipeExist(recipe)) throw PermissionDenied("This Recipe Is Not Yours!"); chef_->removeRecipe(recipe); deletedRecipes_.push_back(recipe); const auto itr = std::find(recipes_.begin(), recipes_.end(), recipe); recipes_.erase(itr); } std::vector<Recipe::InterfaceRecipe> System::getChefsRecipes() const { checkMemberType(MemberType::Chef); return chef_->getInterfaceRecipes(); } void System::makeTagFilter(std::string& tag) { checkMemberType(MemberType::User); user_->makeTagFilter(tag); } void System::makeVegetarianFilter() { checkMemberType(MemberType::User); user_->makeVegetarianFilter(); } void System::makeTimeFilter(int min, int max) { checkMemberType(MemberType::User); user_->makeTimeFilter(min, max); } void System::makeRatingFilter(double min, double max) { checkMemberType(MemberType::User); user_->makeRatingFilter(min, max); } void System::deleteFilter() { checkMemberType(MemberType::User); user_->deleteFilter(); } User::FilterStatus System::getFilterStatus() const { checkMemberType(MemberType::User); return user_->getFilterStatus(); } template <typename T, typename U> T* System::findInstance(U& argument, const std::vector<T*>& instances, bool (T::* ptr)(U& arg) const) const { auto itr = std::find_if(instances.begin(), instances.end(), [&argument, ptr](T* t) { return (t->*ptr)(argument); }); if (itr == instances.end()) return nullptr; return *itr; } void System::checkMemberType(MemberType member) const { switch (member) { case MemberType::User: if (loggedInMember_ != member) throw PermissionDenied("You Should Be Logged In As A Normal User To Use This Command!"); break; case MemberType::Chef: if (loggedInMember_ != member) throw PermissionDenied("You Should Be Logged In As A Chef To Use This Command!"); break; case MemberType::NA: if (loggedInMember_ != member) throw BadRequest("Logout First To Use This Command!"); break; } }
29.939394
135
0.71982
[ "vector" ]
1f6283a6f200854cb89a9e28ff255b00e9cf1132
2,165
cpp
C++
lab_dict/anagram_dict.cpp
RongW99/fa21_cs225
60f546c4867e6e20e48d7775fc3efb2365b87e6e
[ "MIT" ]
null
null
null
lab_dict/anagram_dict.cpp
RongW99/fa21_cs225
60f546c4867e6e20e48d7775fc3efb2365b87e6e
[ "MIT" ]
null
null
null
lab_dict/anagram_dict.cpp
RongW99/fa21_cs225
60f546c4867e6e20e48d7775fc3efb2365b87e6e
[ "MIT" ]
null
null
null
/** * @file anagram_dict.cpp * Implementation of the AnagramDict class. * * @author Matt Joras * @date Winter 2013 */ #include "anagram_dict.h" #include <algorithm> /* I wonder why this is included... */ #include <fstream> using std::string; using std::vector; using std::ifstream; /** * Constructs an AnagramDict from a filename with newline-separated * words. * @param filename The name of the word list file. */ AnagramDict::AnagramDict(const string& filename) { /* Your code goes here! */ string line; ifstream infile (filename); if(infile.is_open()){ while(getline(infile, line)){ string word = line; std::sort(word.begin(), word.end()); dict[word].push_back(line); } } infile.close(); } /** * Constructs an AnagramDict from a vector of words. * @param words The vector of strings to be used as source words. */ AnagramDict::AnagramDict(const vector<string>& words) { /* Your code goes here! */ for(auto&line:words){ string word = line; std::sort(word.begin(), word.end()); dict[word].push_back(line); } } /** * @param word The word to find anagrams of. * @return A vector of strings of anagrams of the given word. Empty * vector returned if no anagrams are found or the word is not in the * word list. */ vector<string> AnagramDict::get_anagrams(const string& word) const { /* Your code goes here! */ string word1 = word; std::sort(word1.begin(), word1.end()); if(dict.find(word1) == dict.end() || dict.at(word1).size() == 1) return vector<string>(); return dict.at(word1); } /** * @return A vector of vectors of strings. Each inner vector contains * the "anagram siblings", i.e. words that are anagrams of one another. * NOTE: It is impossible to have one of these vectors have less than * two elements, i.e. words with no anagrams are ommitted. */ vector<vector<string>> AnagramDict::get_all_anagrams() const { /* Your code goes here! */ vector<vector<string>>res; for(auto&it: dict) if(it.second.size() > 1) res.push_back(it.second); return res; }
26.084337
71
0.642956
[ "vector" ]
1f6654ce16e64ceb5e214a97a3e65d30008589f8
5,376
cpp
C++
NetcodeClient/Network/NetwUtil.cpp
tyekx/netcode
c46fef1eeb33ad029d0c262d39309dfa83f76c4d
[ "MIT" ]
null
null
null
NetcodeClient/Network/NetwUtil.cpp
tyekx/netcode
c46fef1eeb33ad029d0c262d39309dfa83f76c4d
[ "MIT" ]
null
null
null
NetcodeClient/Network/NetwUtil.cpp
tyekx/netcode
c46fef1eeb33ad029d0c262d39309dfa83f76c4d
[ "MIT" ]
null
null
null
#include "NetwUtil.h" #include "../Services.h" #include "ReplArguments.hpp" #include "../Asset/ClientConverters.h" np::ClientUpdate * ParseClientUpdate(nn::GameMessage * message) { if(message == nullptr) { return nullptr; } np::ClientUpdate * upd = message->allocator->MakeProto<np::ClientUpdate>(); if(upd->ParseFromArray(message->content.Data(), static_cast<int32_t>(message->content.Size()))) { return upd; } return nullptr; } Netcode::Float3 ConvertFloat3(const np::Float3 & f3) { return Netcode::Float3{ f3.x(), f3.y(), f3.z() }; } void ConvertFloat3(np::Float3 * dst, const Netcode::Float3 & src) { dst->set_x(src.x); dst->set_y(src.y); dst->set_z(src.z); } GameObject * CreateScoreboard(uint32_t id) { GameScene * scene = Service::Get<GameSceneManager>()->GetScene(); GameObject * object = scene->Create("Scoreboard"); Network * networkComponent = object->AddComponent<Network>(); Script * script = object->AddComponent<Script>(); std::unique_ptr<ScoreboardScript> ss = std::make_unique<ScoreboardScript>(); networkComponent->id = id; networkComponent->owner = 0; networkComponent->replDesc = CreateScoreboardReplDesc(ss.get()); script->AddScript(std::move(ss)); return object; } GameObject * CreateRemoteAvatar(Netcode::Duration interpDelay, physx::PxControllerManager * controllerManager) { GameScene * gameScene = Service::Get<GameSceneManager>()->GetScene(); GameObject * avatarController = gameScene->Create("remoteAvatarCtrl"); auto [ctrlTransform, ctrlScript, ctrlNetwork, ctrlCamera] = avatarController->AddComponents<Transform, Script, Network, Camera>(); ctrlCamera->ahead = Netcode::Float3::UnitZ; ctrlCamera->up = Netcode::Float3::UnitY; ctrlNetwork->state = PlayerState::SPECTATOR; ctrlNetwork->owner = -1; ctrlNetwork->id = 0; Netcode::PxPtr<physx::PxController> pxController = GameScene::CreateController(controllerManager); std::unique_ptr<RemotePlayerScript> rps = std::make_unique<RemotePlayerScript>(std::move(pxController), interpDelay); rps->Construct(avatarController); ctrlScript->AddScript(std::move(rps)); return avatarController; } std::string ReplicateWrite(GameObject * gameObject, Network * networkComponent) { uint32_t requiredSize = 0; for(std::unique_ptr<ReplArgumentBase> & arg : networkComponent->replDesc) { requiredSize += arg->GetReplicatedSize(gameObject); } if(requiredSize == 0) return std::string{}; std::string binary; binary.resize(requiredSize); Netcode::MutableArrayView<uint8_t> view{ reinterpret_cast<uint8_t *>(binary.data()), binary.size() }; for(std::unique_ptr<ReplArgumentBase> & arg : networkComponent->replDesc) { const uint32_t writtenSize = arg->Write(gameObject, view); if(writtenSize == 0) throw Netcode::UndefinedBehaviourException{ "Failed to write replication data" }; view = view.Offset(writtenSize); } return binary; } void ReplicateRead(GameObject* gameObject, Network * networkComponent, const std::string & content, Netcode::GameClock * clock, int32_t connectionId, ActorType actor) { if(content.empty()) return; Netcode::ArrayView<uint8_t> src{ reinterpret_cast<const uint8_t *>(content.data()), content.size() }; for(std::unique_ptr<ReplArgumentBase> & arg : networkComponent->replDesc) { const uint32_t replicatedSize = arg->QueryReplicatedSize(src); const ReplType type = arg->GetType(); if(replicatedSize == 0) throw Netcode::UndefinedBehaviourException{ "Failed to read from replication data" }; /** * Client predicted values are rejected by the server regardless of the owner */ if(actor == ActorType::SERVER && type == ReplType::CLIENT_PREDICTED) { src = src.Offset(replicatedSize); continue; } /** * The owner client rejects the replication because it is the one predicting it */ if(actor == ActorType::CLIENT && type == ReplType::CLIENT_PREDICTED && connectionId == networkComponent->owner) { src = src.Offset(replicatedSize); continue; } const uint32_t readSize = arg->Read(gameObject, src); networkComponent->updatedAt = clock->GetLocalTime(); if(replicatedSize != readSize) throw Netcode::UndefinedBehaviourException{ "Replication failed due to mismatching sizes" }; src = src.Offset(readSize); } } ReplDesc CreateLocalAvatarReplDesc(Camera* cameraComponent) { ReplDesc replDesc; replDesc.emplace_back(ReplicateAsIsFromComponent(ReplType::CLIENT_PREDICTED, &Transform::position)); replDesc.emplace_back(ReplicateAsIsFromState(ReplType::DEFAULT, cameraComponent, &Camera::ahead)); return replDesc; } ReplDesc CreateScoreboardReplDesc(ScoreboardScript * scoreboard) { ReplDesc replDesc; replDesc.emplace_back(ReplicateAsIsFromState(ReplType::DEFAULT, scoreboard, &ScoreboardScript::stats)); return replDesc; } ReplDesc ClientCreateRemoteAvatarReplDesc(RemotePlayerScript * rps) { ReplDesc replDesc; replDesc.emplace_back(ReplicateAsIsFromState(ReplType::CLIENT_PREDICTED, rps, &RemotePlayerScript::IND_position)); replDesc.emplace_back(ReplicateAsIsFromState(ReplType::DEFAULT, rps, &RemotePlayerScript::IND_ahead)); return replDesc; } ReplDesc CreateRemoteAvatarReplDesc() { ReplDesc replDesc; replDesc.emplace_back(ReplicateAsIsFromComponent(ReplType::CLIENT_PREDICTED, &Transform::position)); replDesc.emplace_back(ReplicateAsIsFromComponent(ReplType::DEFAULT, &Camera::ahead)); return replDesc; }
33.391304
168
0.751116
[ "object", "transform" ]
1f76d8656e4abd99b3d62e7248cd0f205a6363f2
2,725
cpp
C++
data/transcoder_evaluation_gfg/cpp/SMALLEST_DIFFERENCE_PAIR_VALUES_TWO_UNSORTED_ARRAYS.cpp
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
241
2021-07-20T08:35:20.000Z
2022-03-31T02:39:08.000Z
data/transcoder_evaluation_gfg/cpp/SMALLEST_DIFFERENCE_PAIR_VALUES_TWO_UNSORTED_ARRAYS.cpp
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
49
2021-07-22T23:18:42.000Z
2022-03-24T09:15:26.000Z
data/transcoder_evaluation_gfg/cpp/SMALLEST_DIFFERENCE_PAIR_VALUES_TWO_UNSORTED_ARRAYS.cpp
mxl1n/CodeGen
e5101dd5c5e9c3720c70c80f78b18f13e118335a
[ "MIT" ]
71
2021-07-21T05:17:52.000Z
2022-03-29T23:49:28.000Z
// Copyright (c) 2019-present, Facebook, Inc. // All rights reserved. // // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. // #include <iostream> #include <cstdlib> #include <string> #include <vector> #include <fstream> #include <iomanip> #include <bits/stdc++.h> using namespace std; int f_gold ( int A [ ], int B [ ], int m, int n ) { sort ( A, A + m ); sort ( B, B + n ); int a = 0, b = 0; int result = INT_MAX; while ( a < m && b < n ) { if ( abs ( A [ a ] - B [ b ] ) < result ) result = abs ( A [ a ] - B [ b ] ); if ( A [ a ] < B [ b ] ) a ++; else b ++; } return result; } //TOFILL int main() { int n_success = 0; vector<vector<int>> param0 {{2,2,11,13,18,18,23,25,28,28,37,39,53,56,67,70,74,74,75,79,80,82,84,89,94,95,95,98,98},{-78,10,-8,30,-70,-94,-48,-4,-22,-40,-36,-48,-4,86,-50,62,-72,-44,-62,22,-30,-72,6,-24,-78,72,-44,56,38,-36,0,-72,-10,-12,-70,-64,-24},{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1},{57,82,90,9,61,71,15,2,39,24,28,28,47},{-92,-90,-90,-28,-16,-14,-14,-8,42,52,62,84},{1,0,0,0,1,0,0,0,1,0,1,0,1,0,0,1,1,1,0,0,1,1,0,0,1,0,1,0,1,1,1,1,0,1,1,1,0,1,0,1,1,1,0,1,0},{6,7,7,12,15,15,21,24,26,26,28,36,38,42,46,52,55,56,59,62,63,65,65,66,68,71,73,77,77,77,77,85,87,87,88,90,93,94,98},{-68,44,88,-68,22,34,-82,18,-60,30,24,18,78,90,-20,-60,94,70,4,-16,-38},{0,0,1},{14,7,9,71,37,20,85,62,70,67,26,47,61,99,2,90,70,46,53,16,56,7,15,81,85,94,73,40,35,58,21,98,45}}; vector<vector<int>> param1 {{5,6,11,13,13,16,17,19,23,25,28,31,31,39,41,44,45,52,62,64,70,71,73,78,78,79,85,86,92},{78,-80,-24,-50,-26,-62,26,-12,22,-90,84,10,18,62,26,-68,92,64,-52,76,-84,64,50,36,-24,-98,42,72,-78,-98,-24,86,2,60,-30,14,-42},{0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1},{85,92,84,27,54,77,26,49,47,51,70,11,41},{-98,-98,-58,-6,14,16,18,46,52,52,52,56},{0,1,1,1,0,0,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,1,0,0,1,0,1},{1,3,4,4,6,7,8,8,15,17,18,18,20,23,23,24,25,25,26,33,39,43,46,54,59,67,69,69,69,69,76,76,81,81,85,86,86,91,95},{-18,-30,-74,-50,98,-44,-62,-20,18,84,62,-64,-2,62,-32,-34,-14,-52,-36,-60,-68},{0,0,1},{99,72,29,55,88,1,88,19,7,80,79,18,28,41,48,49,67,27,24,94,86,14,45,84,37,71,92,98,16,64,67,44,29}}; vector<int> param2 {28,23,14,7,11,35,30,16,2,20}; vector<int> param3 {14,33,16,8,6,33,20,12,1,25}; for(int i = 0; i < param0.size(); ++i) { if(f_filled(&param0[i].front(),&param1[i].front(),param2[i],param3[i]) == f_gold(&param0[i].front(),&param1[i].front(),param2[i],param3[i])) { n_success+=1; } } cout << "#Results:" << " " << n_success << ", " << param0.size(); return 0; }
57.978723
778
0.559633
[ "vector" ]
1f7942be403cb861d47bd540c4f575b4ed4f26c7
1,048
cpp
C++
3sum.cpp
kunwar-vikrant/LeetCode-Problems
cf432b7723c53563dc7635617f53e43376493daa
[ "MIT" ]
1
2020-05-13T15:21:24.000Z
2020-05-13T15:21:24.000Z
3sum.cpp
kunwar-vikrant/Codechef
96d89e5efd0f32e88fdf2b9199adac99ef33804d
[ "MIT" ]
null
null
null
3sum.cpp
kunwar-vikrant/Codechef
96d89e5efd0f32e88fdf2b9199adac99ef33804d
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<algorithm> #include<unordered_set> using namespace std; // vector<vector<int>> find_duplicates(vector<vector<int>> v, int n){ // vector<vecto<int>> r; // for(int i = 0; i < n; i++){ // for(int j = 0; j < v[i].size(); j++){ // } // } // } int main(){ int n; cout<<"Enter Size of the array :"<<endl; cin>>n; vector<int> v(n); cout<<"Enter vector Elements "<<endl; for(int i = 0; i < n; i++){ cin>>v[i]; } vector<vector<int> > result; for(int i = 0; i < n-2; i++){ unordered_set<int> s; int curr_sum = 0-v[i]; for(int j = i+1; j < n; j++){ if(s.find(curr_sum-v[j]) != s.end()){ result.push_back({v[i],curr_sum-v[j], v[j]}); // result.push_back(); // result.push_back(); } s.insert(v[j]); } } // find_duplicates(result, result.size()); for(int i = 0; i < result.size(); i++){ for(int j = 0; j < result[i].size(); j++){ cout<<result[i][j]<<" "; } cout<<endl; } }
16.903226
70
0.501908
[ "vector" ]
1f7967adb481d2880453e5797092e0dc45586858
6,224
cpp
C++
mlir/transforms/optimizations/IdentityPairRemovalPass.cpp
tnguyen-ornl/qcor
f198798cdf8229906a52b54f872512debdb2e835
[ "BSD-3-Clause" ]
null
null
null
mlir/transforms/optimizations/IdentityPairRemovalPass.cpp
tnguyen-ornl/qcor
f198798cdf8229906a52b54f872512debdb2e835
[ "BSD-3-Clause" ]
null
null
null
mlir/transforms/optimizations/IdentityPairRemovalPass.cpp
tnguyen-ornl/qcor
f198798cdf8229906a52b54f872512debdb2e835
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************************* * Copyright (c) 2018-, UT-Battelle, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the BSD 3-Clause License * which accompanies this distribution. * * Contributors: * Alexander J. McCaskey - initial API and implementation * Thien Nguyen - implementation *******************************************************************************/ #include "IdentityPairRemovalPass.hpp" #include "Quantum/QuantumOps.h" #include "mlir/Dialect/LLVMIR/LLVMDialect.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/IR/Matchers.h" #include "mlir/IR/PatternMatch.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassManager.h" #include "mlir/Target/LLVMIR.h" #include "mlir/Transforms/DialectConversion.h" #include "mlir/Transforms/Passes.h" #include <iostream> namespace qcor { void SingleQubitIdentityPairRemovalPass::getDependentDialects( DialectRegistry &registry) const { registry.insert<LLVM::LLVMDialect>(); } void SingleQubitIdentityPairRemovalPass::runOnOperation() { // Walk the operations within the function. std::vector<mlir::quantum::ValueSemanticsInstOp> deadOps; getOperation().walk([&](mlir::quantum::ValueSemanticsInstOp op) { if (std::find(deadOps.begin(), deadOps.end(), op) != deadOps.end()) { // Skip this op since it was merged (forward search) return; } auto inst_name = op.name(); auto return_value = *op.result().begin(); if (return_value.hasOneUse()) { // get that one user auto user = *return_value.user_begin(); // cast to a inst op if (auto next_inst = dyn_cast_or_null<mlir::quantum::ValueSemanticsInstOp>(user)) { // check that it is one of our known id pairs if (should_remove(next_inst.name().str(), inst_name.str())) { // need to get users of next_inst and point them to use // op.getOperands (*next_inst.result_begin()).replaceAllUsesWith(op.getOperand(0)); deadOps.emplace_back(op); deadOps.emplace_back(next_inst); } } } }); for (auto &op : deadOps) { op->dropAllUses(); op.erase(); } } bool SingleQubitIdentityPairRemovalPass::should_remove( std::string name1, std::string name2) const { if (search_gates.count(name1)) { return search_gates.at(name1) == name2; } return false; } void CNOTIdentityPairRemovalPass::getDependentDialects( DialectRegistry &registry) const { registry.insert<LLVM::LLVMDialect>(); } void CNOTIdentityPairRemovalPass::runOnOperation() { // Walk the operations within the function. std::vector<mlir::quantum::ValueSemanticsInstOp> deadOps; getOperation().walk([&](mlir::quantum::ValueSemanticsInstOp op) { if (std::find(deadOps.begin(), deadOps.end(), op) != deadOps.end()) { // Skip this op since it was merged (forward search) return; } auto inst_name = op.name(); if (inst_name != "cnot" && inst_name != "cx") { return; } // Get the src ret qubit and the tgt ret qubit auto src_return_val = op.result().front(); auto tgt_return_val = op.result().back(); // Make sure they are used if (src_return_val.hasOneUse() && tgt_return_val.hasOneUse()) { // get the users of these values auto src_user = *src_return_val.user_begin(); auto tgt_user = *tgt_return_val.user_begin(); // Cast them to InstOps auto next_inst = dyn_cast_or_null<mlir::quantum::ValueSemanticsInstOp>(src_user); auto tmp_tgt = dyn_cast_or_null<mlir::quantum::ValueSemanticsInstOp>(tgt_user); if (!next_inst || !tmp_tgt) { // not inst ops return; } // We want the case where src_user and tgt_user are the same if (next_inst.getOperation() != tmp_tgt.getOperation()) { return; } // Need src_return_val to map to next_inst operand 0, // and tgt_return_val to map to next_inst operand 1. // if not drop out if (next_inst.getOperand(0) != src_return_val && next_inst.getOperand(1) != tgt_return_val) { return; } // Next instruction must be a CNOT to merge if (next_inst.name() != "cnot" && next_inst.name() != "cx") { return; } // They are the same operation, a cnot // so we have cnot src, tgt | cnot src, tgt auto next_inst_result_0 = next_inst.result().front(); auto next_inst_result_1 = next_inst.result().back(); next_inst_result_0.replaceAllUsesWith(op.getOperand(0)); next_inst_result_1.replaceAllUsesWith(op.getOperand(1)); // Remove the identity pair deadOps.emplace_back(op); deadOps.emplace_back(src_user); } }); for (auto &op : deadOps) { op->dropAllUses(); op.erase(); } } void DuplicateResetRemovalPass::getDependentDialects( DialectRegistry &registry) const { registry.insert<LLVM::LLVMDialect>(); } void DuplicateResetRemovalPass::runOnOperation() { // Walk the operations within the function. std::vector<mlir::quantum::ValueSemanticsInstOp> deadOps; getOperation().walk([&](mlir::quantum::ValueSemanticsInstOp op) { if (std::find(deadOps.begin(), deadOps.end(), op) != deadOps.end()) { // Skip this op since it was deleted (forward search) return; } auto inst_name = op.name(); if (inst_name != "reset") { return; } auto return_value = *op.result().begin(); if (return_value.hasOneUse()) { // get that one user auto user = *return_value.user_begin(); // cast to a inst op if (auto next_inst = dyn_cast_or_null<mlir::quantum::ValueSemanticsInstOp>(user)) { if (next_inst.name().str() == "reset") { // Two resets in a row: // Chain the input -> output and mark this second reset to delete: (*next_inst.result_begin()) .replaceAllUsesWith(next_inst.getOperand(0)); deadOps.emplace_back(next_inst); } } } }); for (auto &op : deadOps) { op->dropAllUses(); op.erase(); } } } // namespace qcor
32.416667
81
0.632873
[ "vector" ]
1f79bafc50b985ac399c57d171c48a893507ebcf
7,617
cpp
C++
BGSubtractor.cpp
rlczddl/avatar
8c03dbdf4eed15219797285dbac6ca04e8f1b6f4
[ "Apache-2.0" ]
1
2022-02-14T09:38:16.000Z
2022-02-14T09:38:16.000Z
BGSubtractor.cpp
SFM2020/avatar
8c03dbdf4eed15219797285dbac6ca04e8f1b6f4
[ "Apache-2.0" ]
null
null
null
BGSubtractor.cpp
SFM2020/avatar
8c03dbdf4eed15219797285dbac6ca04e8f1b6f4
[ "Apache-2.0" ]
null
null
null
#include "BGSubtractor.h" #include <atomic> #include <thread> #include <opencv2/imgcodecs.hpp> #include "Util.h" namespace ark { namespace { cv::Mat ffill( const cv::Mat& background, const cv::Mat& image, int size, int num_threads, float nn_dist_thresh, float neighb_thresh, std::vector<std::array<int, 2> >* comps_by_size, cv::Point& top_left, cv::Point& bot_right) { cv::Mat absimg(image.size(), CV_8UC1); const uint8_t UNVISITED = 254, INVALID = 255; absimg.setTo(UNVISITED); std::vector<int> stk, curCompVis; int min_pts = std::max( background.rows * background.cols / 1000, 100); stk.reserve(background.rows * background.cols); curCompVis.reserve(background.rows * background.cols); int hi_bit = (1<<16); int lo_mask = hi_bit - 1; uint8_t compid = 0; if (comps_by_size != nullptr) { comps_by_size->reserve(254); comps_by_size->clear(); } { std::atomic<int> row(0); auto check = [size, nn_dist_thresh, &background](int rr, int cc, const cv::Vec3f& val, uint8_t& invalid_bit) { int minc = std::max(cc - size, 0), maxc = std::min(cc + size, background.cols - 1); int minr = std::max(rr - size, 0), maxr = std::min(rr + size, background.rows - 1); // float best_norm = std::numeric_limits<float>::max(); // const cv::Vec3f bg_val = background.at<cv::Vec3f>(rr, cc); // if (bg_val[2] == 0.0) { // invalid_bit = INVALID; // return; // } for (int r = minr; r <= maxr; ++r) { const cv::Vec3f* rptr = background.ptr<cv::Vec3f>(r); for (int c = minc; c <= maxc; ++c) { const auto& neighb = rptr[c]; if (neighb[2] == 0.0) continue; cv::Vec3f diff = neighb - val; float norm = diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]; if (norm < nn_dist_thresh) { invalid_bit = INVALID; return; } } } }; auto worker = [&] () { int rr = 0; while (true) { rr = row++; if (rr >= image.rows) break; auto* ptr = image.ptr<cv::Vec3f>(rr); auto* absptr = absimg.ptr<uint8_t>(rr); for (int cc = 0 ; cc < image.cols; ++cc) { if (ptr[cc][2] == 0.0) { absptr[cc] = INVALID; continue; } check(rr, cc, ptr[cc], absptr[cc]); } } }; std::vector<std::thread> thds; for (int i = 0; i < num_threads; ++i) { thds.emplace_back(worker); } for (int i = 0; i < num_threads; ++i) { thds[i].join(); } } auto maybe_visit = [&](int curr_r, int curr_c, const cv::Vec3f& curr_val, int new_r, int new_c, int new_id) { if (absimg.at<uint8_t>(new_r, new_c) == UNVISITED) { const cv::Vec3f& val = image.at<cv::Vec3f>(new_r, new_c); cv::Vec3f diff = curr_val - val; if (diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2] > neighb_thresh) { return; } absimg.at<uint8_t>(new_r, new_c) = compid; curCompVis.push_back(new_id); stk.push_back(curCompVis.back()); } }; for (int rr = 0; rr < image.rows; ++rr) { const cv::Vec3f* ptr = image.ptr<cv::Vec3f>(rr); auto* outptr = absimg.ptr<uint8_t>(rr); for (int cc = 0 ; cc < image.cols; ++cc) { if (outptr[cc] != UNVISITED) continue; outptr[cc] = compid; stk.push_back((rr << 16) + cc); curCompVis.clear(); curCompVis.push_back(stk.back()); while (stk.size()) { int id = stk.back(); const int cur_r = (id >> 16), cur_c = (id & lo_mask); stk.pop_back(); cv::Vec3f val = image.at<cv::Vec3f>(cur_r, cur_c); if (cur_r > 0) maybe_visit(cur_r, cur_c, val, cur_r - 1, cur_c, id - hi_bit); if (cur_r < background.rows - 1) maybe_visit(cur_r, cur_c, val, cur_r + 1, cur_c, id + hi_bit); if (cur_c > 0) maybe_visit(cur_r, cur_c, val, cur_r, cur_c - 1, id - 1); if (cur_c < background.cols - 1) maybe_visit(cur_r, cur_c, val, cur_r, cur_c + 1, id + 1); } if (curCompVis.size() < min_pts) { for (int val : curCompVis) { absimg.at<uint8_t>((val >> 16), (val & lo_mask)) = INVALID; } } else { if (comps_by_size != nullptr) { comps_by_size->push_back({static_cast<int>(curCompVis.size()), compid}); } ++compid; } if (compid == UNVISITED) return absimg; } } top_left.x = image.cols - 1; top_left.y = image.rows - 1; bot_right.x = bot_right.y = 0; for (int rr = 0; rr < image.rows; ++rr) { auto* outptr = absimg.ptr<uint8_t>(rr); bool nz = false; for (int cc = 0 ; cc < image.cols; ++cc) { if (outptr[cc] != INVALID) { nz = true; top_left.x = std::min(top_left.x, cc); break; } } if (nz) { for (int cc = image.cols - 1; cc >= 0; --cc) { if (outptr[cc] != INVALID) { bot_right.x = std::max(bot_right.x, cc); break; } } if (top_left.y == image.rows - 1) top_left.y = rr; bot_right.y = rr; } } if (comps_by_size != nullptr) { std::sort(comps_by_size->begin(), comps_by_size->end(), std::greater<std::array<int, 2> >()); } return absimg; } } cv::Mat BGSubtractor::run(const cv::Mat& image, std::vector<std::array<int, 2> >* comps_by_size) { return ffill(background, image, 1, numThreads, 1200000.0 / (background.rows * background.cols) * nnDistThreshRel, 1200000.0 / (background.rows * background.cols) * neighbThreshRel, comps_by_size, topLeft, botRight); } }
46.163636
126
0.406591
[ "vector" ]
1f7b2aa0f32b2a604e645ef51397262541a1646e
9,063
cpp
C++
problem-solver/cxx/inferenceModule/test/units/TestTemplateSearchModule.cpp
NikitaZotov/ostis-inference
6c5c7ca37668e6b22ba1cf261101e12e1e46589d
[ "Apache-2.0" ]
null
null
null
problem-solver/cxx/inferenceModule/test/units/TestTemplateSearchModule.cpp
NikitaZotov/ostis-inference
6c5c7ca37668e6b22ba1cf261101e12e1e46589d
[ "Apache-2.0" ]
null
null
null
problem-solver/cxx/inferenceModule/test/units/TestTemplateSearchModule.cpp
NikitaZotov/ostis-inference
6c5c7ca37668e6b22ba1cf261101e12e1e46589d
[ "Apache-2.0" ]
null
null
null
/* * This source file is part of an OSTIS project. For the latest info, see http://ostis.net * Distributed under the MIT License * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ #include "sc_test.hpp" #include "builder/src/scs_loader.hpp" #include "sc-agents-common/keynodes/coreKeynodes.hpp" #include "searcher/TemplateSearcher.hpp" #include "keynodes/InferenceKeynodes.hpp" namespace inferenceTest { ScsLoader loader; const std::string TEST_FILES_DIR_PATH = TEMPLATE_SEARCH_MODULE_TEST_SRC_PATH "/testStructures/TemplateSearchModule/"; const std::string TEST_SEARCH_TEMPLATE_ID = "search_template"; using TemplateSearchManagerTest = ScMemoryTest; void initialize() { inference::InferenceKeynodes::InitGlobal(); scAgentsCommon::CoreKeynodes::InitGlobal(); } TEST_F(TemplateSearchManagerTest, SearchWithContent_NoStructuresTestCase) { ScMemoryContext& context = *m_ctx; loader.loadScsFile(context,TEST_FILES_DIR_PATH + "searchWithContentNoStructures.scs"); initialize(); ScAddr searchTemplateAddr = context.HelperFindBySystemIdtf(TEST_SEARCH_TEMPLATE_ID); inference::TemplateSearcher templateSearcher = inference::TemplateSearcher(&context); ScTemplateParams templateParams; std::vector<ScTemplateSearchResultItem> searchResults = templateSearcher.searchTemplate(searchTemplateAddr, templateParams); EXPECT_TRUE(searchResults.empty()); } TEST_F(TemplateSearchManagerTest, SearchWithContent_EmptyResultsTestCase) { ScMemoryContext& context = *m_ctx; loader.loadScsFile(context,TEST_FILES_DIR_PATH + "searchWithContentEmptyResultsTestStucture.scs"); initialize(); ScAddr searchTemplateAddr = context.HelperFindBySystemIdtf(TEST_SEARCH_TEMPLATE_ID); inference::TemplateSearcher templateSearcher = inference::TemplateSearcher(&context); ScTemplateParams templateParams; std::vector<ScTemplateSearchResultItem> searchResults = templateSearcher.searchTemplate(searchTemplateAddr, templateParams); EXPECT_TRUE(searchResults.empty()); } TEST_F(TemplateSearchManagerTest, SearchWithContent_SingleResultTestCase) { std::string correctResultLinkIdentifier = "correct_result_link"; std::string searchLinkIdentifier = "search_link"; ScMemoryContext& context = *m_ctx; loader.loadScsFile(context,TEST_FILES_DIR_PATH + "searchWithContentSingleResultTestStucture.scs"); initialize(); ScAddr searchTemplateAddr = context.HelperFindBySystemIdtf(TEST_SEARCH_TEMPLATE_ID); inference::TemplateSearcher templateSearcher = inference::TemplateSearcher(&context); ScTemplateParams templateParams; std::vector<ScTemplateSearchResultItem> searchResults = templateSearcher.searchTemplate(searchTemplateAddr, templateParams); EXPECT_TRUE(searchResults.size() == 1); EXPECT_TRUE(searchResults[0][searchLinkIdentifier] == context.HelperFindBySystemIdtf(correctResultLinkIdentifier)); } TEST_F(TemplateSearchManagerTest, SearchWithContent_MultipleResultTestCase) { std::string firstCorrectResultLinkIdentifier = "first_correct_result_link"; std::string secondCorrectResultLinkIdentifier = "second_correct_result_link"; std::string searchLinkIdentifier = "search_link"; ScMemoryContext& context = *m_ctx; loader.loadScsFile(context,TEST_FILES_DIR_PATH + "searchWithContentMultipleResultTestStucture.scs"); initialize(); ScAddr searchTemplateAddr = context.HelperFindBySystemIdtf(TEST_SEARCH_TEMPLATE_ID); inference::TemplateSearcher templateSearcher = inference::TemplateSearcher(&context); ScTemplateParams templateParams; std::vector<ScTemplateSearchResultItem> searchResults = templateSearcher.searchTemplate(searchTemplateAddr, templateParams); EXPECT_TRUE(searchResults.size() == 2); EXPECT_TRUE(searchResults[1][searchLinkIdentifier] == context.HelperFindBySystemIdtf(firstCorrectResultLinkIdentifier)); EXPECT_TRUE(searchResults[0][searchLinkIdentifier] == context.HelperFindBySystemIdtf(secondCorrectResultLinkIdentifier)); } TEST_F(TemplateSearchManagerTest, SearchWithoutContent_NoStructuresTestCase) { ScMemoryContext& context = *m_ctx; loader.loadScsFile(context,TEST_FILES_DIR_PATH + "searchWithoutContentNoStructures.scs"); initialize(); ScAddr searchTemplateAddr = context.HelperFindBySystemIdtf(TEST_SEARCH_TEMPLATE_ID); inference::TemplateSearcher templateSearcher = inference::TemplateSearcher(&context); ScTemplateParams templateParams; std::vector<ScTemplateSearchResultItem> searchResults = templateSearcher.searchTemplate(searchTemplateAddr, templateParams); EXPECT_TRUE(searchResults.empty()); } TEST_F(TemplateSearchManagerTest, SearchWithoutContent_SingleResultTestCase) { std::string correctResultLinkIdentifier = "correct_result_link"; std::string searchLinkIdentifier = "search_link"; ScMemoryContext& context = *m_ctx; loader.loadScsFile(context,TEST_FILES_DIR_PATH + "searchWithoutContentSingleResultTestStucture.scs"); initialize(); ScAddr searchTemplateAddr = context.HelperFindBySystemIdtf(TEST_SEARCH_TEMPLATE_ID); inference::TemplateSearcher templateSearcher = inference::TemplateSearcher(&context); ScTemplateParams templateParams; std::vector<ScTemplateSearchResultItem> searchResults = templateSearcher.searchTemplate(searchTemplateAddr, templateParams); EXPECT_TRUE(searchResults.size() == 1); EXPECT_TRUE(searchResults[0][searchLinkIdentifier] == context.HelperFindBySystemIdtf(correctResultLinkIdentifier)); } TEST_F(TemplateSearchManagerTest, SearchWithoutContent_MultipleResultTestCase) { std::string firstCorrectResultLinkIdentifier = "first_correct_result_link"; std::string secondCorrectResultLinkIdentifier = "second_correct_result_link"; std::string searchLinkIdentifier = "search_link"; ScMemoryContext& context = *m_ctx; loader.loadScsFile(context,TEST_FILES_DIR_PATH + "searchWithoutContentMultipleResultTestStucture.scs"); initialize(); ScAddr searchTemplateAddr = context.HelperFindBySystemIdtf(TEST_SEARCH_TEMPLATE_ID); inference::TemplateSearcher templateSearcher = inference::TemplateSearcher(&context); ScTemplateParams templateParams; std::vector<ScTemplateSearchResultItem> searchResults = templateSearcher.searchTemplate(searchTemplateAddr, templateParams); EXPECT_TRUE(searchResults.size() == 2); EXPECT_TRUE(searchResults[1][searchLinkIdentifier] == context.HelperFindBySystemIdtf(firstCorrectResultLinkIdentifier)); EXPECT_TRUE(searchResults[0][searchLinkIdentifier] == context.HelperFindBySystemIdtf(secondCorrectResultLinkIdentifier)); } TEST_F(TemplateSearchManagerTest, SearchWithoutContent_SelectiveTestCase) { std::string correctResultLinkIdentifier = "correct_result_link"; std::string searchLinkIdentifier = "search_link"; ScMemoryContext& context = *m_ctx; loader.loadScsFile(context,TEST_FILES_DIR_PATH + "searchWithContentSelectiveSearchTestStucture.scs"); initialize(); ScAddr searchTemplateAddr = context.HelperFindBySystemIdtf(TEST_SEARCH_TEMPLATE_ID); inference::TemplateSearcher templateSearcher = inference::TemplateSearcher(&context); ScTemplateParams templateParams; std::vector<ScTemplateSearchResultItem> searchResults = templateSearcher.searchTemplate(searchTemplateAddr, templateParams); EXPECT_TRUE(searchResults.size() == 1); EXPECT_TRUE(searchResults[0][searchLinkIdentifier] == context.HelperFindBySystemIdtf(correctResultLinkIdentifier)); } TEST_F(TemplateSearchManagerTest, SearchWithoutContent_EmptyLinkTestCase) { std::string correctResultLinkIdentifier = "correct_result_link"; std::string searchLinkIdentifier = "search_link"; ScMemoryContext& context = *m_ctx; loader.loadScsFile(context,TEST_FILES_DIR_PATH + "searchWithoutContentEmptyLinkTest.scs"); initialize(); ScAddr searchTemplateAddr = context.HelperFindBySystemIdtf(TEST_SEARCH_TEMPLATE_ID); inference::TemplateSearcher templateSearcher = inference::TemplateSearcher(&context); ScTemplateParams templateParams; std::vector<ScTemplateSearchResultItem> searchResults = templateSearcher.searchTemplate(searchTemplateAddr, templateParams); EXPECT_TRUE(searchResults.size() == 1); EXPECT_TRUE(searchResults[0][searchLinkIdentifier] == context.HelperFindBySystemIdtf(correctResultLinkIdentifier)); } TEST_F(TemplateSearchManagerTest, SearchWithContent_EmptyLinkTestCase) { std::string correctResultLinkIdentifier = "correct_result_link"; std::string searchLinkIdentifier = "search_link"; ScMemoryContext& context = *m_ctx; loader.loadScsFile(context,TEST_FILES_DIR_PATH + "searchWithContentEmptyLinkTest.scs"); initialize(); ScAddr searchTemplateAddr = context.HelperFindBySystemIdtf(TEST_SEARCH_TEMPLATE_ID); inference::TemplateSearcher templateSearcher = inference::TemplateSearcher(&context); ScTemplateParams templateParams; std::vector<ScTemplateSearchResultItem> searchResults = templateSearcher.searchTemplate(searchTemplateAddr, templateParams); EXPECT_TRUE(searchResults.size() == 1); EXPECT_TRUE(searchResults[0][searchLinkIdentifier] == context.HelperFindBySystemIdtf(correctResultLinkIdentifier)); } }//namespace inferenceTest
42.549296
126
0.828644
[ "vector" ]
1f7fbcda2d501b014420f7ef318197f1040071bb
15,660
cpp
C++
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/dmlproc/batchinsertprocessor.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/dmlproc/batchinsertprocessor.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
null
null
null
src/vendor/mariadb-10.6.7/storage/columnstore/columnstore/dmlproc/batchinsertprocessor.cpp
zettadb/zettalib
3d5f96dc9e3e4aa255f4e6105489758944d37cc4
[ "Apache-2.0" ]
2
2022-02-27T14:00:01.000Z
2022-03-31T06:24:22.000Z
/* Copyright (C) 2014 InfiniDB, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // $Id: batchinsertprocessor.h 525 2010-01-19 23:18:05Z xlou $ // /** @file */ #include <boost/thread/mutex.hpp> #include <boost/scoped_ptr.hpp> #include <boost/scoped_array.hpp> using namespace boost; using namespace std; #include "liboamcpp.h" using namespace oam; #include "batchinsertprocessor.h" using namespace dmlprocessor; #include "we_messages.h" using namespace WriteEngine; #include "dmlpackageprocessor.h" using namespace batchloader; #include "calpontsystemcatalog.h" using namespace execplan; #include "idberrorinfo.h" #include "errorids.h" using namespace logging; #include "dbrm.h" using namespace BRM; using namespace messageqcpp; boost::mutex mute; boost::condition_variable cond; boost::mutex fLock; namespace dmlprocessor { BatchInsertProc::BatchInsertProc(bool isAutocommitOn, uint32_t tableOid, execplan::CalpontSystemCatalog::SCN txnId, BRM::DBRM* aDbrm) : fTxnid(txnId), fIsAutocommitOn(isAutocommitOn), fTableOid(tableOid), fDbrm(aDbrm) { fErrorCode = 0; fErrMsg = ""; fLastpkg = false; fUniqueId = fDbrm->getUnique64(); fWEClient = new WriteEngine::WEClients(WriteEngine::WEClients::DMLPROC); fWEClient->addQueue(fUniqueId); fOamcache = OamCache::makeOamCache(); std::vector<int> moduleIds = fOamcache->getModuleIds(); //cout << "moduleIds size is " << moduleIds.size() << endl; for (unsigned i = 0; i < moduleIds.size(); i++) { fPMs.push_back((uint32_t)moduleIds[i]); //cout << "got module id " << (uint32_t)moduleIds[i] << endl; //cout << "fPMs[0] is " << fPMs[0] << endl; } fBatchLoader = new BatchLoader(fTableOid, fTxnid, fPMs); for (unsigned i = 0; i < fPMs.size(); i++) { fPmState[fPMs[i]] = true; } //cout << "Constructor: There are " << (int)fPMs.size() << " pms" << endl; fInsertPkgQueue.reset(new pkg_type); } BatchInsertProc::~BatchInsertProc() { fWEClient->removeQueue(fUniqueId); delete fWEClient; } uint64_t BatchInsertProc::grabTableLock(int32_t sessionId) { uint32_t processID = ::getpid(); int32_t txnId = fTxnid; std::string processName("DMLProc batchinsert"); int32_t tmpSessionId = sessionId; uint32_t tableOid = fTableOid; int i = 0; try { //cout << "In grabTableLock, fPMs[0] is "<< fPMs[0] << endl; fTableLockid = fDbrm->getTableLock(fPMs, tableOid, &processName, &processID, &tmpSessionId, &txnId, BRM::LOADING ); } catch (std::exception&) { setError(dmlpackageprocessor::DMLPackageProcessor::INSERT_ERROR, IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); return 0; } if ( fTableLockid == 0 ) { int waitPeriod = 10; int sleepTime = 100; // sleep 100 milliseconds between checks int numTries = 10; // try 10 times per second string waitPeriodStr = config::Config::makeConfig()->getConfig("SystemConfig", "WaitPeriod"); if ( waitPeriodStr.length() != 0 ) waitPeriod = static_cast<int>(config::Config::fromText(waitPeriodStr)); numTries = waitPeriod * 10; struct timespec rm_ts; rm_ts.tv_sec = sleepTime / 1000; rm_ts.tv_nsec = sleepTime % 1000 * 1000000; for (; i < numTries; i++) { #ifdef _MSC_VER Sleep(rm_ts.tv_sec * 1000); #else struct timespec abs_ts; do { abs_ts.tv_sec = rm_ts.tv_sec; abs_ts.tv_nsec = rm_ts.tv_nsec; } while (nanosleep(&abs_ts, &rm_ts) < 0); #endif try { processID = ::getpid(); txnId = fTxnid; tmpSessionId = sessionId; processName = "DMLProc batchinsert"; fTableLockid = fDbrm->getTableLock(fPMs, tableOid, &processName, &processID, &tmpSessionId, &txnId, BRM::LOADING ); } catch (std::exception&) { setError(dmlpackageprocessor::DMLPackageProcessor::INSERT_ERROR, IDBErrorInfo::instance()->errorMsg(ERR_HARD_FAILURE)); return 0; } if (fTableLockid > 0) return fTableLockid; } if (i >= numTries) //error out { logging::Message::Args args; string strOp("batch insert"); args.add(strOp); args.add(processName); args.add((uint64_t)processID); args.add(tmpSessionId); setError(dmlpackageprocessor::DMLPackageProcessor::TABLE_LOCK_ERROR, IDBErrorInfo::instance()->errorMsg(ERR_TABLE_LOCKED, args)); return 0; } } return fTableLockid; } BatchInsertProc::SP_PKG BatchInsertProc::getInsertQueue() { boost::mutex::scoped_lock lk(fLock); return fInsertPkgQueue; } void BatchInsertProc::setLastPkg (bool lastPkg) { fLastpkg = lastPkg; } void BatchInsertProc::addPkg(messageqcpp::ByteStream& insertBs) { boost::mutex::scoped_lock lk(fLock); fInsertPkgQueue->push(insertBs); } messageqcpp::ByteStream BatchInsertProc::getPkg() { messageqcpp::ByteStream bs; boost::mutex::scoped_lock lk(fLock); bs = fInsertPkgQueue->front(); fInsertPkgQueue->pop(); return bs; } void BatchInsertProc::buildPkg(messageqcpp::ByteStream& bs) { bs.reset(); bs << (ByteStream::byte) WE_SVR_BATCH_INSERT; bs << fUniqueId; bs << (uint32_t) fTxnid; bs << fCurrentPMid; //to keep track of PMs bs += getPkg(); } void BatchInsertProc::buildLastPkg(messageqcpp::ByteStream& bs) { ByteStream::byte rt; // Bug 757. WriteEngineServer deletes metadata if ErrorCode != 0. With range warning, // we still inserted data, just truncated. Kludge to keep WriteEngineServer on track. if (fErrorCode == dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING) rt = 0; else rt = fErrorCode; bs.reset(); bs << (ByteStream::byte) WE_SVR_BATCH_INSERT_END; bs << fUniqueId; bs << (ByteStream::quadbyte) fTxnid; bs << (ByteStream::byte)fIsAutocommitOn; bs << fTableOid; bs << rt; } void BatchInsertProc::sendFirstBatch() { uint32_t firstPmId = 0; int rc = 0; try { firstPmId = fBatchLoader->selectNextPM(); } catch (std::exception& ex) { rc = 1; setError(rc, ex.what()); return; } if (firstPmId == 0) { rc = 1; setError(rc, "Request cannot be sent to PM 0."); return; } fCurrentPMid = firstPmId; messageqcpp::ByteStream bs; buildPkg(bs); fWEClient->write(bs, fCurrentPMid); //cout << "in sendFirstBatch: batchinsertprocessor sent pkg to pmnum " << fCurrentPMid << endl; fPmState[fCurrentPMid] = false; } void BatchInsertProc::sendNextBatch() { int rc = 0; try { fCurrentPMid = fBatchLoader->selectNextPM(); } catch (std::exception& ex) { rc = 1; setError(rc, ex.what()); return; } messageqcpp::ByteStream bs; buildPkg(bs); string errorMsg; //cout << "in sendNextBatch: fCurrentPMid changed to " << fCurrentPMid << " this = " << this << endl; if (fPmState[fCurrentPMid]) { //cout << "current pm state for pm is true for pm " << fCurrentPMid << " this = " << this<< endl; fWEClient->write(bs, fCurrentPMid); //cout << "batchinsertprocessor sent pkg to pmnum " << fCurrentPMid << endl; fPmState[fCurrentPMid] = false; //cout << "set pm state to false for pm " << fCurrentPMid << " this = " << this << endl; } else { //cout << "current pm state for pm is false for pm " << fCurrentPMid<< endl; while (1) { //cout << "Read from WES for pm id " << (uint32_t) tmp32 << endl; bsIn.reset(new ByteStream()); fWEClient->read(fUniqueId, bsIn); if ( bsIn->length() == 0 ) //read error { errorMsg = "Lost connection to WES."; setError(dmlpackageprocessor::DMLPackageProcessor::NETWORK_ERROR, errorMsg); break; } else { *bsIn >> tmp8; rc = tmp8; *bsIn >> errorMsg; *bsIn >> tmp32; //cout << "got response from WES for pm id " << (uint32_t) tmp32 << endl; if (rc != 0) { //cout << "Batch insert got error code:errormsg = " << (uint32_t)tmp8<<":"<<errorMsg<<endl; setError(rc, errorMsg); fPmState[tmp32] = true; break; } } fPmState[tmp32] = true; //cout << "set pm state to true for pm " << (uint32_t) tmp32 << " and current PM id is " << fCurrentPMid<< " this = " << this << endl; if (tmp32 == fCurrentPMid) break; } //cout << "before batchinsertprocessor sent pkg to pm " << fCurrentPMid << endl; fWEClient->write(bs, fCurrentPMid); //cout << "batchinsertprocessor sent pkg to pm " << fCurrentPMid << endl; fPmState[fCurrentPMid] = false; //cout << "set pm state to false for pm " << fCurrentPMid << " this = " << this << endl; } } void BatchInsertProc::sendlastBatch() { messageqcpp::ByteStream bs; buildLastPkg(bs); try { fWEClient->write_to_all(bs); //cout << "sent the last pkg" << endl; } catch (std::exception& ex) { ostringstream oss; oss << "Exception on communicating to WES "; oss << ex.what(); setError(1, oss.str()); //cout << oss.str() << endl; } } void BatchInsertProc::receiveOutstandingMsg() { //check how many message we need to receive uint32_t messagesNotReceived = 0; int rc = 0; for (unsigned i = 0; i < fPMs.size(); i++) { if (!fPmState[fPMs[i]]) messagesNotReceived++; } //cout << "receiveOutstandingMsg: Need to receive " << messagesNotReceived << " messages. this = " << this << endl; if ((messagesNotReceived > 0) && (messagesNotReceived <= fWEClient->getPmCount())) { string errorMsg; uint32_t msgReceived = 0; while (1) { if (msgReceived == messagesNotReceived) break; bsIn.reset(new ByteStream()); try { fWEClient->read(fUniqueId, bsIn); if ( bsIn->length() == 0 ) //read error { rc = 1; setError(rc, errorMsg); } else { *bsIn >> tmp8; *bsIn >> errorMsg; *bsIn >> tmp32; fPmState[tmp32] = true; msgReceived++; if ( tmp8 != 0 ) setError(tmp8, errorMsg); } } catch (runtime_error& ex) //write error { errorMsg = ex.what(); setError(dmlpackageprocessor::DMLPackageProcessor::NETWORK_ERROR, errorMsg); break; } catch (...) { errorMsg = "Lost connection to WES."; setError(dmlpackageprocessor::DMLPackageProcessor::NETWORK_ERROR, errorMsg); break; } } } } void BatchInsertProc::receiveAllMsg() { uint32_t msgRevd = 0; int rc = 0; string errorMsg; try { while (1) { if (msgRevd == fWEClient->getPmCount()) break; //cout << "Read last from WES bytestream" << endl; fWEClient->read(fUniqueId, bsIn); if ( bsIn->length() == 0 ) //read error { errorMsg = "Lost connection to WES."; setError(dmlpackageprocessor::DMLPackageProcessor::NETWORK_ERROR, errorMsg); msgRevd++; if (!fIsAutocommitOn) { BulkSetHWMArgs setHWMArgs; fHwmArgsAllPms.push_back(setHWMArgs); } } else { *bsIn >> tmp8; rc = tmp8; *bsIn >> errorMsg; msgRevd++; if (!fIsAutocommitOn) //collect Hwm { BulkSetHWMArgs setHWMArgs; deserializeInlineVector(*(bsIn.get()), setHWMArgs); fHwmArgsAllPms.push_back(setHWMArgs); } if (rc == dmlpackageprocessor::DMLPackageProcessor::IDBRANGE_WARNING) { setError(rc, errorMsg); } else if (rc != 0) { //cout << "Batch insert lastpkg got error code:errormsg = " << (uint32_t)tmp8<<":"<<errorMsg<<endl; setError(rc, errorMsg); } } } } catch (std::exception& ex) { ostringstream oss; oss << "Exception on communicating to WES "; oss << ex.what(); rc = 1; setError(rc, oss.str()); } if (!fIsAutocommitOn && (fHwmArgsAllPms.size() == fWEClient->getPmCount())) setHwm(); } void BatchInsertProc::collectHwm() { BulkSetHWMArgs setHWMArgs; //cout << "received from WES bytestream length = " << bsIn->length() << endl; deserializeInlineVector(*(bsIn.get()), setHWMArgs); //cout << "get hwm info from WES size " << setHWMArgs.size() << endl; fHwmArgsAllPms.push_back(setHWMArgs); } void BatchInsertProc::setHwm() { std::vector<BRM::BulkSetHWMArg> allHwm; BulkSetHWMArgs::const_iterator itor; //cout << "total hwmArgsAllPms size " << hwmArgsAllPms.size() << endl; for (unsigned i = 0; i < fWEClient->getPmCount(); i++) { itor = fHwmArgsAllPms[i].begin(); while (itor != fHwmArgsAllPms[i].end()) { allHwm.push_back(*itor); //cout << "received hwm info: " << itor->oid << ":" << itor->hwm << endl; itor++; } } if (allHwm.size() > 0) { //cout << "setting hwm allHwm size " << allHwm.size() << endl; int rc = fDbrm->bulkSetHWM(allHwm, 0); if ( rc != 0 ) { string errorMsg; BRM::errString(rc, errorMsg); setError(rc, errorMsg); } } } void BatchInsertProc::setError(int errorCode, std::string errMsg) { boost::mutex::scoped_lock lk(fLock); fErrorCode = errorCode; fErrMsg = errMsg; } void BatchInsertProc::getError(int& errorCode, std::string& errMsg) { boost::mutex::scoped_lock lk(fLock); errorCode = fErrorCode; errMsg = fErrMsg; } } // vim:ts=4 sw=4:
28.472727
146
0.559898
[ "vector" ]
1f81c07e1cd33d146fc665cda3db87c69cda1ba3
2,909
cpp
C++
SwaggerApi/source/model/SourceCodeFilesModel.cpp
macias2k4/Swagger-Qt
58182290f527a0999f7bda5fbfea3a338c29218a
[ "MIT" ]
1
2018-11-07T19:37:11.000Z
2018-11-07T19:37:11.000Z
SwaggerApi/source/model/SourceCodeFilesModel.cpp
macias2k4/Swagger-Qt
58182290f527a0999f7bda5fbfea3a338c29218a
[ "MIT" ]
1
2021-05-09T17:48:37.000Z
2021-05-09T17:48:37.000Z
SwaggerApi/source/model/SourceCodeFilesModel.cpp
macias2k4/Swagger-Qt
58182290f527a0999f7bda5fbfea3a338c29218a
[ "MIT" ]
null
null
null
#include "SourceCodeFilesModel.h" namespace Swagger { namespace Model { // ────────────────────────────────────────────────────────────────────────────────────────────── // SourceCodeFilesModel::SourceCodeFilesModel ( QObject *parent ) : QObject ( parent ) { } // ────────────────────────────────────────────────────────────────────────────────────────────── // SourceCodeFilesModel::SourceCodeFilesModel ( const SourceCodeFilesModel &object ) : QObject ( nullptr ) { for ( QFileInfo fileInfo : object.sourceCodeFilesReadOnly ( ) ) { _sourceCodeFiles.append ( QFileInfo ( fileInfo ) ); } } // ────────────────────────────────────────────────────────────────────────────────────────────── // SourceCodeFilesModel::~SourceCodeFilesModel ( ) { } // ────────────────────────────────────────────────────────────────────────────────────────────── // // Methods & Slots // // ────────────────────────────────────────────────────────────────────────────────────────────── // // ────────────────────────────────────────────────────────────────────────────────────────────── // void SourceCodeFilesModel::fillModelWithRelativeRootPath ( const QString &rootPath ) { _clearModel ( ); QDirIterator dirIterator ( rootPath, _SourceCodeFilesExtension, QDir::Files | QDir::Dirs, QDirIterator::Subdirectories | QDirIterator::FollowSymlinks ); while ( dirIterator.hasNext ( ) ) { _currentSourceCodeFile = dirIterator.fileInfo ( ); _addCurrentSourceCodeFileToModel ( ); dirIterator.next ( ); } } // ────────────────────────────────────────────────────────────────────────────────────────────── // void SourceCodeFilesModel::_clearModel ( ) { _sourceCodeFiles.clear ( ); } // ───────────────────────────────────────────────────────────────────────────────────────────── // void SourceCodeFilesModel::_addCurrentSourceCodeFileToModel ( ) { if ( _isCurrentSourceCodeFileValid ( ) ) { _sourceCodeFiles.append ( _currentSourceCodeFile ); } } // ───────────────────────────────────────────────────────────────────────────────────────────── // bool SourceCodeFilesModel::_isCurrentSourceCodeFileValid ( ) { return ( !_currentSourceCodeFile.fileName ( ).isEmpty ( ) && ( _currentSourceCodeFile.fileName ( ) != '.' ) && ( _currentSourceCodeFile.fileName ( ) != ".." ) ); } // ────────────────────────────────────────────────────────────────────────────────────────────── // // - proeprty QFileInfoList &SourceCodeFilesModel::sourceCodeFiles ( ) { return _sourceCodeFiles; } // ────────────────────────────────────────────────────────────────────────────────────────────── // QFileInfoList SourceCodeFilesModel::sourceCodeFilesReadOnly ( ) const { return _sourceCodeFiles; } } // Swagger } // Model
44.753846
100
0.407356
[ "object", "model" ]
1f82f51ca50aa72dde73942ce4293c2262654e47
3,020
cc
C++
ecs/src/model/DescribeStorageSetDetailsResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
ecs/src/model/DescribeStorageSetDetailsResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
ecs/src/model/DescribeStorageSetDetailsResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/ecs/model/DescribeStorageSetDetailsResult.h> #include <json/json.h> using namespace AlibabaCloud::Ecs; using namespace AlibabaCloud::Ecs::Model; DescribeStorageSetDetailsResult::DescribeStorageSetDetailsResult() : ServiceResult() {} DescribeStorageSetDetailsResult::DescribeStorageSetDetailsResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeStorageSetDetailsResult::~DescribeStorageSetDetailsResult() {} void DescribeStorageSetDetailsResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allDisksNode = value["Disks"]["Disk"]; for (auto valueDisksDisk : allDisksNode) { Disk disksObject; if(!valueDisksDisk["CreationTime"].isNull()) disksObject.creationTime = valueDisksDisk["CreationTime"].asString(); if(!valueDisksDisk["DiskName"].isNull()) disksObject.diskName = valueDisksDisk["DiskName"].asString(); if(!valueDisksDisk["ZoneId"].isNull()) disksObject.zoneId = valueDisksDisk["ZoneId"].asString(); if(!valueDisksDisk["StorageSetId"].isNull()) disksObject.storageSetId = valueDisksDisk["StorageSetId"].asString(); if(!valueDisksDisk["DiskId"].isNull()) disksObject.diskId = valueDisksDisk["DiskId"].asString(); if(!valueDisksDisk["Category"].isNull()) disksObject.category = valueDisksDisk["Category"].asString(); if(!valueDisksDisk["StorageSetPartitionNumber"].isNull()) disksObject.storageSetPartitionNumber = std::stoi(valueDisksDisk["StorageSetPartitionNumber"].asString()); if(!valueDisksDisk["RegionId"].isNull()) disksObject.regionId = valueDisksDisk["RegionId"].asString(); disks_.push_back(disksObject); } if(!value["PageSize"].isNull()) pageSize_ = std::stoi(value["PageSize"].asString()); if(!value["PageNumber"].isNull()) pageNumber_ = std::stoi(value["PageNumber"].asString()); if(!value["TotalCount"].isNull()) totalCount_ = std::stoi(value["TotalCount"].asString()); } int DescribeStorageSetDetailsResult::getTotalCount()const { return totalCount_; } int DescribeStorageSetDetailsResult::getPageSize()const { return pageSize_; } int DescribeStorageSetDetailsResult::getPageNumber()const { return pageNumber_; } std::vector<DescribeStorageSetDetailsResult::Disk> DescribeStorageSetDetailsResult::getDisks()const { return disks_; }
32.473118
109
0.757616
[ "vector", "model" ]