void CEnvironmentGrid::ReadFromStream (SLoadCtx &Ctx) // ReadFromStream // // Read // // DWORD m_iTileSize // DWORD No. of atom entries // For each entry // DWORD UNID of space environment // // CTileMap Tile Map { ALERROR error; int i; if (Ctx.dwVersion >= 82) { // Read the size of each tile if (Ctx.dwVersion >= 88) Ctx.pStream->Read((char *)&m_iTileSize, sizeof(DWORD)); else m_iTileSize = tileSizeCompatible; // Read the environment list m_EnvList.DeleteAll(); // Since we saved the list in atom-order, we can reload and expect to // add them and get back the same atom. We rely on the fact that the // atom is the same as the order in which they are added. int iCount; Ctx.pStream->Read((char *)&iCount, sizeof(DWORD)); for (i = 0; i < iCount; i++) { DWORD dwUNID; Ctx.pStream->Read((char *)&dwUNID, sizeof(DWORD)); CSpaceEnvironmentType *pEnv = g_pUniverse->FindSpaceEnvironment(dwUNID); DWORD dwAtom; m_EnvList.atom_Insert(pEnv, &dwAtom); ASSERT(dwAtom == i); } // Now load the tile map. if (error = m_Map.ReadFromStream(Ctx.pStream)) throw CException(error); m_iTileCount = m_Map.GetTotalSize(); } // In old versions we just save the UNID of the environment type for // each tile. else { // Load into a separate map CTileMap Env; if (error = Env.ReadFromStream(Ctx.pStream)) throw CException(error); // Convert to the new storage method ConvertSpaceEnvironmentToPointers(Env); m_iTileSize = tileSizeCompatible; } }
int main (int argc, char** argv) { int returnCode = 0; try { const char* epocRoot = getenv("EPOCROOT"); if(NULL == epocRoot) { throw CException("EPOCROOT environment variable not specified.", ExceptionCodes::EEnvNotSpecified); } std::string epocRootStr(epocRoot); COptions options(argc, argv); std::string logFileName(options.GetLogFileName()); std::auto_ptr<CLogger> logger(new CLogger(logFileName, options.GetLogLevel())); #ifdef __LINUX__ std::string dllPath = "sqlite-3.6.1.so"; #else std::string dllPath = "sqlite3.dll"; #endif std::auto_ptr<CDbLayer> db( new CDbLayer(dllPath, options.GetDbFileName())); std::auto_ptr<CScrXmlParser> xmlParser( new CScrXmlParser()); if(options.IsDbAbsent()) { #ifdef __LINUX__ std::string dbFileName = epocRootStr + "epoc32/tools/create_db.xml"; #else std::string dbFileName = epocRootStr + "epoc32\\tools\\create_db.xml"; #endif std::auto_ptr<SchemaDetails> schema(xmlParser->ParseDbSchema(dbFileName)); db->CreateScrDatabase(*schema); } std::vector<std::string> xmlFileNames = options.GetEnvFileNames(); for(StringIterator xmlIter=xmlFileNames.begin(); xmlIter != xmlFileNames.end(); ++xmlIter) { std::auto_ptr<EnvDetails> envDetails(xmlParser->GetEnvironmentDetails(*xmlIter)); db->PopulateScrDatabase(*envDetails); } if(options.IsPreProvisionInfoAvailable()) { std::string preProvFileName = options.GetPrePovisionFileName(); XmlDetails::TScrPreProvisionDetail preProvisionDetailList = xmlParser->GetPreProvisionDetails(preProvFileName); db->PopulatePreProvisionDetails(preProvisionDetailList); } } catch(CException& aException) { const std::string& exc = aException.GetMessageA(); returnCode = aException.GetCode(); std::cout << "Exception caught::" << exc << std::endl; std::cout << "Error Code::" << returnCode << std::endl; } return returnCode; }
void CUnit::CheckUdunits (uint32_t Code, const std::string &Msg1 /*= ""*/, const std::string &Msg2 /*= ""*/) { static CUnitSmartCleaner object; // can throw - but otherwise initializes the units system std::string Message; if ((Code == 0) && CUnit::m_ErrInit.empty()) return; switch ((int32_t)Code) { case 0: break; case UT_ENOFILE: Message = "No unit file ("+Msg1+")"; break; case UT_ESYNTAX: Message = "Syntax error in unit '"+Msg1+"'"; break; case UT_EUNKNOWN: Message = "Unknown unit '"+Msg1+"'"; break; case UT_EIO: Message = "I/O error for unit file "+Msg1; break; case UT_EINVALID: Message = "Invalid unit description for '"+Msg1+"' or '"+Msg2+"'"; break; case UT_ENOINIT: Message = "PROGRAM ERROR: udunit package non initialized"; break; case UT_ECONVERT: Message = "Units are not compatible for conversion ('"+Msg1+"' vs '"+Msg2+"')"; break; case UT_EALLOC: Message = "Memory allocation problem for unit management"; break; case UT_ENOROOM: Message = "Not enough room"; break; case UT_ENOTTIME: Message = "Not a time unit: '"+Msg1+"'"; break; default: Message = CTools::Format("Unknown error code %d from udunits", Code); break; } if (! CUnit::m_initialized) { if (Code != 0) { CUnit::m_ErrInit.append(Message); CUnit::m_ErrInit.append("\n"); } Message = CUnit::m_ErrInit; } throw CException(Message, BRATHL_UNIT_ERROR); }
template<size_t NoOfPZD> bool CLeyboldSimPortDriver::process(asynUser* IOUser, USSPacket<NoOfPZD> const& USSReadPacket, USSPacket<NoOfPZD>& USSWritePacket, size_t TableIndex) { if ((TableIndex < 0) || (TableIndex >= m_RunRecord.size())) throw CException(IOUser, asynError, __FUNCTION__, "User / pump not configured"); RunStates RunState = static_cast<RunStates>(getIntegerParam(TableIndex, RUNNING)); // Means the running state is in effect or has been requested. bool Running = ((RunState == On) || (RunState == Accel)); // control bit 10 = 1 bool RemoteActivated = ((USSReadPacket.m_USSPacketStruct.m_PZD[0] & (1 << 10)) != 0); if (RemoteActivated) { // Running state change can be requested both ways! Running = (USSReadPacket.m_USSPacketStruct.m_PZD[0] & (1 << 0)); // 0 to 1 transition = Error reset Is only run provided if: // the cause for the error has been removed // and control bit 0 = 0 and control bit 10 = 1 if ((USSReadPacket.m_USSPacketStruct.m_PZD[0] & (1 << 7)) && (RunState==Off)) { // Clear the fault condition. setIntegerParam(TableIndex, FAULT, 0); } } { epicsGuard < epicsMutex > guard ( CLeyboldSimPortDriver::m_Mutex ); if ((Running) && (m_RunRecord[TableIndex].m_RunState != On)) { // The running state has just been enabled. if (m_RunRecord[TableIndex].m_RunState == Off) { setIntegerParam(TableIndex, RUNNING, Accel); setDoubleParam(TableIndex, MOTORCURRENT, 15.2); m_RunRecord[TableIndex].m_RunState = Accel; m_RunRecord[TableIndex].m_TimeStamp = getTickCount(); } else { // Accel. // It is intended that the (simulated) pump speed ramps up to full speed in Duration static const unsigned Duration = 2000; unsigned ElapsedTime = getTickCount() - m_RunRecord[TableIndex].m_TimeStamp; setIntegerParam(TableIndex, STATORFREQUENCY, (ElapsedTime * NormalStatorFrequency) / Duration); if (ElapsedTime >= Duration) { setDefaultValues(TableIndex); m_RunRecord[TableIndex].m_RunState = On; m_RunRecord[TableIndex].m_TimeStamp = getTickCount(); } } } else if ((!Running) && (m_RunRecord[TableIndex].m_RunState != Off)) { // The running state has just been disabled. if (m_RunRecord[TableIndex].m_RunState == On) { setIntegerParam(TableIndex, RUNNING, Decel); m_RunRecord[TableIndex].m_RunState = Decel; m_RunRecord[TableIndex].m_TimeStamp = getTickCount(); } else if (m_RunRecord[TableIndex].m_RunState == Decel) { // It is intended that the (simulated) pump speed ramps down to nothing in Duration static const int Duration = 2000; int ElapsedTime = getTickCount() - m_RunRecord[TableIndex].m_TimeStamp; int StatorFrequency = ((Duration - ElapsedTime) * NormalStatorFrequency) / Duration; if (StatorFrequency < 3) StatorFrequency = 3; setIntegerParam(TableIndex, STATORFREQUENCY, StatorFrequency); if (ElapsedTime >= Duration) { setIntegerParam(TableIndex, RUNNING, Moving); m_RunRecord[TableIndex].m_RunState = Moving; m_RunRecord[TableIndex].m_TimeStamp = getTickCount(); } } else if (m_RunRecord[TableIndex].m_RunState == Moving) { // It is intended that the pump remains in the 'Moving' state for another Duration static const unsigned Duration = 2000; unsigned ElapsedTime = getTickCount() - m_RunRecord[TableIndex].m_TimeStamp; if (ElapsedTime >= Duration) { setIntegerParam(TableIndex, STATORFREQUENCY, 0); setIntegerParam(TableIndex, RUNNING, Off); m_RunRecord[TableIndex].m_RunState = Off; m_RunRecord[TableIndex].m_TimeStamp = getTickCount(); } } } } USSWritePacket.m_USSPacketStruct.m_PZD[0] = 0; RunState = m_RunRecord[TableIndex].m_RunState; if (RunState == On) USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 10); else if (RunState == Accel) USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 4); else if (RunState == Decel) USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 5); else if (RunState == Moving) USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 11); // Remote has been activated 1 = start/stop (control bit 0) and reset(control bit 7) through serial interface is possible. USSWritePacket.m_USSPacketStruct.m_PZD[0] |= ((RemoteActivated ? 1 : 0) << 15); bool Fault = (getIntegerParam(TableIndex, FAULT) != 0); if (Fault) { // A fault condition causes the controller to stop the pump. USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 3); setIntegerParam(TableIndex, STATORFREQUENCY, 0); setIntegerParam(TableIndex, RUNNING, Off); m_RunRecord[TableIndex].m_RunState = Off; } if (getIntegerParam(TableIndex, WARNINGTEMPERATURE) != 0) USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 7); if (getIntegerParam(TableIndex, WARNINGHIGHLOAD) != 0) USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 13); if (getIntegerParam(TableIndex, WARNINGPURGE) != 0) USSWritePacket.m_USSPacketStruct.m_PZD[0] |= (1 << 14); // Frequency - actual value. This is equivalent to parameter 3. Both packet types have this field. USSWritePacket.m_USSPacketStruct.m_PZD[1] = getIntegerParam(TableIndex, STATORFREQUENCY); epicsUInt16 PKE = 0; if (USSReadPacket.m_USSPacketStruct.m_PKE & (1 << 12)) // The requested parameter is in the least 12 bits. PKE = USSReadPacket.m_USSPacketStruct.m_PKE & 0X0FFF; switch (PKE) { case 3 : // Frequency - actual value. This is equivalent to PZD[1]. USSWritePacket.m_USSPacketStruct.m_PWE = getIntegerParam(TableIndex, STATORFREQUENCY); break; case 11: // Converter temperature - actual value. This is equivalent to PZD[2]. USSWritePacket.m_USSPacketStruct.m_PWE = getIntegerParam(TableIndex, CONVERTERTEMPERATURE); break; case 5 : // Motor current - actual value. This is equivalent to PZD[3]. USSWritePacket.m_USSPacketStruct.m_PWE = epicsUInt32(10.0 * getDoubleParam(TableIndex, MOTORCURRENT) + 0.5); break; case 7 : // Motor temperature - actual value. This is equivalent to PZD[4]. USSWritePacket.m_USSPacketStruct.m_PWE = getIntegerParam(TableIndex, PUMPTEMPERATURE); break; case 4 : // Intermediate circuit voltage Uzk. This is equivalent to PZD[5]. USSWritePacket.m_USSPacketStruct.m_PWE = epicsUInt32(10.0 * getDoubleParam(TableIndex, CIRCUITVOLTAGE) + 0.5); break; case 2 : // Software version (I assume this means firmware). e.g. 3.03.05 char CBuf[8]; // 7 chars plus null termination. int Major, Minor1, Minor2; getStringParam(TableIndex, FIRMWAREVERSION, sizeof(CBuf), CBuf); sscanf(CBuf, "%1d.%02d.%02d", &Major, &Minor1, &Minor2); USSWritePacket.m_USSPacketStruct.m_PWE = Major * 10000 + Minor1 * 100 + Minor2; break; case 171: // Error code USSWritePacket.m_USSPacketStruct.m_PWE = getIntegerParam(TableIndex, FAULT); break; case 227: // Temperature Warning code USSWritePacket.m_USSPacketStruct.m_PWE = getIntegerParam(TableIndex, WARNINGTEMPERATURE); break; case 228: // Load warning code. USSWritePacket.m_USSPacketStruct.m_PWE = getIntegerParam(TableIndex, WARNINGHIGHLOAD); break; case 230: // Purge warning code. USSWritePacket.m_USSPacketStruct.m_PWE = getIntegerParam(TableIndex, WARNINGPURGE); break; default: break; // No action. } USSWritePacket.GenerateChecksum(); USSWritePacket.m_USSPacketStruct.HToN(); size_t nbytesOut; asynStatus status = pasynOctetSyncIO->write(IOUser, reinterpret_cast<char*>(&USSWritePacket.m_Bytes), USSPacketStruct<NoOfPZD>::USSPacketSize, -1, &nbytesOut); if (status == asynDisconnected) return false; if (status != asynSuccess) throw CException(IOUser, status, __FUNCTION__, "Can't write/read:"); callParamCallbacks(int(TableIndex)); asynPrint(IOUser, ASYN_TRACE_FLOW, "Packet success %s %s\n", __FILE__, __FUNCTION__); return true; }
void InitOpenGL(SWrapper &wrapper, HWND hParWnd) { GLuint PixelFormat; DWORD dwExStyle; DWORD dwStyle; RECT WindowRect; g_WC.cbSize = sizeof(WNDCLASSEX); g_WC.style = CS_DBLCLKS | CS_HREDRAW | CS_VREDRAW | CS_OWNDC; g_WC.lpfnWndProc = wrapper.lpfnProc; g_WC.cbClsExtra = 0; g_WC.cbWndExtra = 0; g_WC.hInstance = wrapper.hInst; g_WC.hIcon = LoadIcon(wrapper.hInst, MAKEINTRESOURCE(IDI_IKONA)); g_WC.hCursor = LoadCursor(NULL, IDC_ARROW); g_WC.hbrBackground = NULL; g_WC.lpszMenuName = NULL; g_WC.lpszClassName = wrapper.szTitle; g_WC.hIconSm = NULL; if (!RegisterClassEx(&g_WC)) throw CException("InitOpenGL: RegisterClassEx()"); WindowRect.left = (long)0; WindowRect.right = (long)wrapper.nWidth; WindowRect.top = (long)0; WindowRect.bottom = (long)wrapper.nHeight; dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; if (wrapper.bFullS) { DEVMODE dmSettings; dwStyle = WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; ZeroMemory(&dmSettings, sizeof(dmSettings)); if (!EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dmSettings)) throw CException("InitOpenGL: EnumDisplaySettings"); dmSettings.dmPelsWidth = wrapper.nWidth; dmSettings.dmPelsHeight = wrapper.nHeight; int result = ChangeDisplaySettings(&dmSettings, CDS_FULLSCREEN); if (result != DISP_CHANGE_SUCCESSFUL) throw CException("InitOpenGL: ChangeDisplaySettings"); ::ShowCursor(FALSE); } else { dwStyle = WS_SYSMENU|WS_CAPTION|WS_BORDER|WS_OVERLAPPED|WS_VISIBLE|WS_MINIMIZEBOX|WS_POPUP; } /// ustaw parametry okna: if (!AdjustWindowRectEx(&WindowRect, dwStyle, false, dwExStyle)) throw CException("InitOpenGL: AdjustWindowRectEx"); /// stwórz okno: if (!(g_hWnd = ::CreateWindowEx( dwExStyle, wrapper.szTitle, wrapper.szTitle, dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top, hParWnd, NULL, /// bez menu wrapper.hInst, NULL))) throw CException("InitOpenGL: CreateWindowEx"); /// ustaw odpowiednio 'PIXELFORMATDESCRIPTOR': ZeroMemory(&g_pfd, sizeof(PIXELFORMATDESCRIPTOR)); g_pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); g_pfd.nVersion = 1; g_pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; g_pfd.iPixelType = PFD_TYPE_RGBA; g_pfd.cColorBits = wrapper.nBPP; g_pfd.cDepthBits = 16; /// 16-bitowy z-bufor g_pfd.iLayerType = PFD_MAIN_PLANE; if (!(g_hDC = GetDC(g_hWnd))) throw CException("Nie mogê utworzyæ Device Context."); if (!(PixelFormat = ChoosePixelFormat(g_hDC, &g_pfd))) throw CException("Ten format pixeli nie pasuje do aktualnego DC."); if (!SetPixelFormat(g_hDC, PixelFormat, &g_pfd)) throw CException("Nie mo¿na ustawiæ tego formatu pixeli."); if (!(g_hGLRC = wglCreateContext(g_hDC))) throw CException("Nie mogê utworzyæ GL Rendering Context."); if (!wglMakeCurrent(g_hDC, g_hGLRC)) throw CException("Nie mogê uaktywniæ GL Rendering Context."); ::ShowWindow(g_hWnd, SW_SHOW); ::SetForegroundWindow(g_hWnd); ::SetFocus(g_hWnd); ResizeWindow(wrapper.nWidth, wrapper.nHeight); }
// If WantedUnit is "", the returned value is in base (SI) unit. void CExternalFilesAvisoGrid::GetValue (const string &name, double &value, const string &wantedUnit) { uint32_t start[3]; uint32_t count[3] = {1, 1, 1}; MustBeOpened(); if (m_latIndex == AT_BEGINNING) { throw CFileException(CTools::Format("PROGRAM ERROR: Try to access file ('%s' field) while file is already rewinded (NextRecord must be called)", name.c_str()), GetName(), BRATHL_LOGIC_ERROR); } if (CurrentMeasure() >= m_nbMeasures) { throw CFileException(CTools::Format("PROGRAM ERROR: Try to access file ('%s' field) while all measurements have been read", name.c_str()), GetName(), BRATHL_LOGIC_ERROR); } start[0] = m_lonIndex; start[1] = m_latIndex; start[2] = m_depthIndex; // Find field def. CFieldNetCdf* var = GetFieldNetCdf(name); int32_t netCdfId = var->GetNetCdfId(); if (netCdfId < 0) { int32_t index; switch (netCdfId) { //--------------------------- case INTERNAL_LAT_ID: //--------------------------- index = m_latIndex; break; //--------------------------- case INTERNAL_LON_ID: //--------------------------- index = m_lonIndex; break; //--------------------------- case INTERNAL_DEPTH_ID: //--------------------------- index = m_depthIndex; break; //--------------------------- default: //--------------------------- throw CException(CTools::Format("PROGRAM ERROR: Unknown pseudo netcdf id %d", netCdfId), BRATHL_LOGIC_ERROR); } value = var->GetValues()[index]; CUnit unit = var->GetUnit(); if ((wantedUnit != "") && (wantedUnit != CUnit::m_UNIT_SI)) { unit.SetConversionTo(wantedUnit); } value = unit.Convert(value); } else { int nbDims = m_file.GetVarNbDims(netCdfId); if (nbDims != 2) { nbDims = 3; } m_file.ReadVar(name, nbDims, start, count, &value, wantedUnit); } }
//---------------------------------------- void CExternalFilesAvisoGrid::AddVar (int32_t netcdfId, const string &name, const string &description, const string &unit, int32_t type /*= NC_NAT*/, const CUIntArray* dimValues /*= NULL*/, const CStringArray* dimNames /*= NULL*/, const CIntArray* dimIds /*= NULL*/, const CStringMap* mapAttributes /*= NULL*/) { try { CheckNetCDFDimensions(); } catch(CException& e) { throw CException(CTools::Format("ERROR: CExternalFilesAvisoGrid::AddVar - %s", e.what()), BRATHL_LOGIC_ERROR); } CNetCDFVarDef netCDFVarDef(name, unit, static_cast<nc_type>(type)); netCDFVarDef.SetVarId(netcdfId); if (mapAttributes != NULL) { netCDFVarDef.AddAttributes(*mapAttributes); } if (netcdfId >= 0) { m_file.LoadAttributes(&netCDFVarDef); } if ( (dimNames != NULL) && (dimValues != NULL) && (dimIds != NULL) ) { /* CStringArray replaced; dimNames->Replace(CExternalFilesAvisoGrid::m_INTERNAL_LAT_DIM_NAME, m_latDim->GetName(), replaced, true, false); CStringArray replacedDims = replaced; replaced.RemoveAll(); replacedDims.Replace(CExternalFilesAvisoGrid::m_INTERNAL_LON_DIM_NAME, m_lonDim->GetName(), replaced, true, false); netCDFVarDef.SetNetCDFDims(&replaced, dimValues, dimIds); CFieldNetCdf* field = GetFieldNetCdf(name); field->SetDimNames(replaced); */ netCDFVarDef.SetNetCDFDims(dimNames, dimValues, dimIds); } m_file.AddNetCDFVarDef(netCDFVarDef); CExternalFilesNetCDF::AddVar(netcdfId, name, description, unit, type, dimValues, dimNames, dimIds, mapAttributes); }
void CBuilder::loadData(const string & data) { size_t start = data.find_first_of('{'); if (start == string::npos) throw CException("\"" + name + "\" - invalid format."); if (data.find_first_not_of(' ') != start) throw CException("\"" + name + "\" - invalid format."); size_t end = 0; for (int rws = 0; rws < rows; rws++) { start = data.find_first_of('{', start + 1); if (start == string::npos) throw CException("\"" + name + "\" - invalid format."); //control between rows bool wasComma = false; for (unsigned int z = end + 1; z < start; z++) { if (data[z] == ',' && rws > 0) { if (wasComma) throw CException("\"" + name + "\" - invalid format."); else wasComma = true; } else if (data[z] == ' '); else throw CException("\"" + name + "\" - invalid format."); } end = data.find_first_of("}", end + 1); if (end == string::npos) throw CException("\"" + name + "\" - invalid format."); size_t startNum, endNum = start; //load and save fractions in line for (int col = 0; col < columns; col++) { startNum = endNum + 1; if (col + 1 < columns) { endNum = data.find_first_of(',', startNum); if (endNum >= end) throw CException("\"" + name + "\" - invalid format."); } else { endNum = data.find_first_of('}', startNum); if (endNum != end) throw CException("\"" + name + "\" - invalid format."); } if (endNum == string::npos || startNum == string::npos) throw CException("\"" + name + "\" - invalid format."); try { CFraction fract(string(data.begin() + startNum, data.begin() + endNum)); insertFract(fract, rws, col); } catch( CException & ex){ throw CException("\"" + name + "\" - invalid format. "); } } } //control behind last rows size_t checkEnd = data.find_first_not_of(' ', end + 1); end = data.find_first_of("}", end + 1); if (checkEnd == string::npos || end == string::npos || checkEnd != end) throw CException("\"" + name + "\" - invalid format."); }
// // Convert system exceptions to a C++ exception. // extern "C" void _cdecl SystemExceptionTranslator( unsigned int uiWhat, struct _EXCEPTION_POINTERS * pexcept ) { throw CException( uiWhat ) ; }
bool CKadHandler::ProcessPacket(const string& Name, const CVariant& Packet, CComChannel* pChannel) { CKadNode* pNode = NULL; try { // Process cahnnel initialisation if(Name == KAD_INIT) { if(GetParent<CKademlia>()->Cfg()->GetBool("DebugTL")) LogLine(LOG_DEBUG, L"Recived 'Transaction Init' from %s", CUInt128(Packet["NID"]).ToHex().c_str()); bool bAdded = false; SKadData* pData = pChannel->GetData<SKadData>(&bAdded); if(!pData->pNode) { pData->pNode = GetParent<CKademlia>()->Root()->GetNode(Packet["NID"]); if(!pData->pNode) { pData->pNode = new CKadNode(GetParent<CKademlia>()->Root()); pData->pNode->SetID(Packet["NID"]); GetParent<CKademlia>()->Root()->AddNode(pData->pNode); } pChannel->AddUpLimit(pData->pNode->GetUpLimit()); pChannel->AddDownLimit(pData->pNode->GetDownLimit()); } else if(pData->pNode->GetID() != Packet["NID"]) throw CException(LOG_ERROR, L"KadNode Miss Match"); // this should never ever happen! pData->pNode->SetProtocol(Packet["PROT"]); pData->pNode->SetVersion(Packet.Get("VER")); // Version is optional pData->Connected = true; if(bAdded) // if it was added it means its an incomming connectziona dnwe have to answer { SendInit(pData->pNode, pChannel); pData->pNode->UpdateAddress(pChannel->GetAddress()); // If this is incomming update addresses } return true; } else { if(SKadData* pData = pChannel->GetData<SKadData>()) pNode = pData->pNode; if(!pNode || !pNode->GetParent()) throw CException(LOG_WARNING, L"Kad Packet Recived %S on not initialized channel", Name.c_str()); } if(Name.compare(KAD_CRYPTO_REQUEST) == 0) HandleCryptoRequest(Packet, pNode, pChannel); else if(Name.compare(KAD_CRYPTO_RESPONSE) == 0) HandleCryptoResponse(Packet, pNode, pChannel); else if(Name.compare(KAD_HELLO_REQUEST) == 0) HandleHello(Packet, pNode, pChannel, true); else if(Name.compare(KAD_HELLO_RESPONSE) == 0) HandleHello(Packet, pNode, pChannel, false); else if(Name.compare(KAD_NODE_REQUEST) == 0) HandleNodeReq(Packet, pNode, pChannel); else if(Name.compare(KAD_NODE_RESPONSE) == 0) HandleNodeRes(Packet, pNode, pChannel); // Lookup Handling else if(Name.compare(KAD_PROXY_REQUEST) == 0) HandleProxyReq(Packet, pNode, pChannel); else if(Name.compare(KAD_PROXY_RESPONSE) == 0) HandleProxyRes(Packet, pNode, pChannel); else if(Name.compare(KAD_CODE_REQUEST) == 0) HandleCodeReq(Packet, pNode, pChannel); else if(Name.compare(KAD_CODE_RESPONSE) == 0) HandleCodeRes(Packet, pNode, pChannel); else if(Name.compare(KAD_LOOKUP_MESSAGE) == 0) HandleMessagePkt(Packet, pNode, pChannel); else if(Name.compare(KAD_EXECUTE_REQUEST) == 0) HandleExecuteReq(Packet, pNode, pChannel); else if(Name.compare(KAD_EXECUTE_RESPONSE) == 0) HandleExecuteRes(Packet, pNode, pChannel); else if(Name.compare(KAD_STORE_REQUEST) == 0) HandleStoreReq(Packet, pNode, pChannel); else if(Name.compare(KAD_STORE_RESPONSE) == 0) HandleStoreRes(Packet, pNode, pChannel); else if(Name.compare(KAD_LOAD_REQUEST) == 0) HandleLoadReq(Packet, pNode, pChannel); else if(Name.compare(KAD_LOAD_RESPONSE) == 0) HandleLoadRes(Packet, pNode, pChannel); else if(Name.compare(KAD_LOOKUP_REPORT) == 0) HandleReportPkt(Packet, pNode, pChannel); // Routing Handling else if(Name.compare(KAD_ROUTE_REQUEST) == 0) HandleRouteReq(Packet, pNode, pChannel); else if(Name.compare(KAD_ROUTE_RESPONSE) == 0) HandleRouteRes(Packet, pNode, pChannel); else if(Name.compare(KAD_RELAY_REQUEST) == 0) HandleRelayReq(Packet, pNode, pChannel); else if(Name.compare(KAD_RELAY_RESPONSE) == 0) HandleRelayRes(Packet, pNode, pChannel); else if(Name.compare(KAD_RELAY_RETURN) == 0) HandleRelayRet(Packet, pNode, pChannel); else if(Name.compare(KAD_RELAY_CONTROL) == 0) HandleRelayCtrl(Packet, pNode, pChannel); else if(Name.compare(KAD_RELAY_STATUS) == 0) HandleRelayStat(Packet, pNode, pChannel); else throw CException(LOG_WARNING, L"Unsupported Kad Packet Recived %S", Name.c_str()); } catch(const CException& Exception) { LogLine(Exception.GetFlag(), L"Packet \'%S\' Error: '%s' from: %s (%s)", Name.c_str(), Exception.GetLine().c_str(), pNode ? pNode->GetID().ToHex().c_str() : L"Unknown", pChannel->GetAddress().ToString().c_str()); pChannel->Close(); return false; } return true; }
void CKadHandler::HandleCryptoResponse(const CVariant& Response, CKadNode* pNode, CComChannel* pChannel) { SKadData* pData = pChannel->GetData<SKadData>(); if(GetParent<CKademlia>()->Cfg()->GetBool("DebugTL")) LogLine(LOG_DEBUG, L"Recived 'CryptoResponse' to %s", pNode->GetID().ToHex().c_str()); SKeyExchange* Key = NULL; TExchangeMap::iterator I = m_KeyExchanges.find(SKadNode(pNode)); for(; I != m_KeyExchanges.end() && I->first.pNode == pNode; I++) { if(I->first.pChannel == pChannel) { Key = &I->second; break; } } if(!Key) throw CException(LOG_ERROR | LOG_DEBUG, L"Unsolicited Crypto Response"); CScoped<CSymmetricKey> pCryptoKey; try { if(Response.Has("ERR")) { string Error = Response["ERR"]; if(Error == "UnknownKey") { pNode->SetTrustedKey(NULL); Key->pExchange = NULL; ResumeExchange(I->first.pNode); return; } else throw CException(LOG_ERROR | LOG_DEBUG, L"Crypto Response Returned Error: %S", Error.c_str()); } CScoped<CAbstractKey> pSessionKey; if(Key->pExchange->GetAlgorithm() & CAbstractKey::eKeyExchange) { if(!Response.Has("EK")) throw "MissingEK"; CScoped<CAbstractKey> pRemKey = new CAbstractKey(Response["EK"].GetData(), Response["EK"].GetSize()); pSessionKey = Key->pExchange->FinaliseKeyExchange(pRemKey); if(!pSessionKey) throw "ExchangeFailed"; if(Key->bAuthenticate) { CPublicKey* pPubKey; if(Response.Has("PK")) pPubKey = pNode->SetIDKey(Response); else pPubKey = pNode->GetID().GetKey(); if(!pPubKey) throw "MissingKey"; if(!Response.Verify(pPubKey)) throw "InvalidSign"; } pData->Authenticated = Key->bAuthenticate; pNode->SetTrustedKey(new CTrustedKey(pSessionKey->GetKey(), pSessionKey->GetSize(), Key->bAuthenticate)); ResumeExchange(I->first.pNode); } else { pData->Authenticated = Key->bAuthenticate; pSessionKey = Key->pExchange->FinaliseKeyExchange(NULL); } if(Response.Has("IV")) { UINT eAlgorithm = PrepSC(Key->eAlgorithm); // UINT eAlgorithm = PrepSC(Key->pExchange->GetIV()->GetAlgorithm()); CAbstractKey InIV(Response["IV"].GetData(), Response["IV"].GetSize()); pCryptoKey = NewSymmetricKey(eAlgorithm, pSessionKey, &InIV, Key->pExchange->GetIV()); } } catch(const char* Error) { throw CException(LOG_ERROR | LOG_DEBUG, L"Crypto Response Error: %S", Error); } m_KeyExchanges.erase(I); if(pCryptoKey) { pChannel->Encrypt(pCryptoKey.Detache()); pChannel->SetQueueLock(false); // release the packet queue lock such that we can start sending encrypted payload packets } }
void SCSIPersistentReserveOut::SetReservationKey(const std::string &key) { if (key.length() != 8) throw CException("Invalid Value"); SetOutBufferString(0, key); }
void CBitMatrix::set(IndexType row, IndexType col, bool value) { if(row >= m_row || row < 0) throw CException("soda::CBitMatrix", "Index out of bound!"); m_data[row].set(col, value); }
bool CBitMatrix::get(IndexType row, IndexType col) const { if(row >= m_row || row < 0) throw CException("soda::CBitMatrix", "Index out of bound!"); return m_data[row].at(col); }
Shader* ShadersLoader::LoadFromFile(const std::string& Filename) { TiXmlDocument doc(Filename.c_str()); if (!doc.LoadFile()) { Logger::Log() << "[ERROR] TinyXML error : " << doc.ErrorDesc() << "\n"; throw CLoadingFailed(Filename, "unable to load xml with TinyXML"); } // Get the root TiXmlHandle hdl(&doc); TiXmlElement *root = hdl.FirstChild("Shader").Element(); // Problem to find the root if (!root) { throw CLoadingFailed(Filename, "unable to find root (Shader)"); } // Get the shader name and display it std::string name; std::string shaderTypeName; TinyXMLGetAttributeValue<std::string>(root, "name", &name); TinyXMLGetAttributeValue<std::string>(root, "type", &shaderTypeName); Logger::Log() << "[INFO] Load shader : " << name << " ( " << shaderTypeName << " ) ... \n"; ShaderType shaderType; if (shaderTypeName == "Basic") shaderType = BASIC_SHADER; else if (shaderTypeName == "GBuffer") shaderType = GBUFFER_SHADER; else throw CException("unknow shader type"); // Load the shader compiler config ShaderCompilerConfig config = LoadShaderCompilerConfig(root); // Get the 2 files name // * Vertex shader TiXmlElement *shadername = root->FirstChildElement("VertexShader"); if (!shadername) { throw CLoadingFailed(Filename, "unable to find VertexShader (Shader)"); } std::string vertexShadername = std::string( shadername->Attribute("filename")); Logger::Log() << " * Vertex shader : " << vertexShadername << "\n"; // * Fragment shader shadername = root->FirstChildElement("FragmentShader"); if (!shadername) { throw CLoadingFailed(Filename, "unable to find VertexShader (Shader)"); } std::string fragmentShadername = std::string( shadername->Attribute("filename")); Logger::Log() << " * Fragment shader : " << fragmentShadername << "\n"; /* * Find full path */ vertexShadername = CMediaManager::Instance().FindMedia(vertexShadername).Fullname(); fragmentShadername = CMediaManager::Instance().FindMedia(fragmentShadername).Fullname(); Shader* shader = 0; shadername = root->FirstChildElement("GeometryShader"); if (shadername != 0) { std::string geometryShadername = std::string( shadername->Attribute("filename")); Logger::Log() << " * Geometry shader : " << geometryShadername << "\n"; geometryShadername = CMediaManager::Instance().FindMedia( geometryShadername).Fullname(); std::string in, out; TinyXMLGetAttributeValue(shadername, "in", &in); TinyXMLGetAttributeValue(shadername, "out", &out); shader = CShaderManager::Instance().loadfromFile( vertexShadername.c_str(), fragmentShadername.c_str(), geometryShadername.c_str(), shaderType, config); shader->SetGeometryShaderParameters(OpenGLEnumFromString(in), OpenGLEnumFromString(out)); } else { Logger::Log() << " * No Geometry shader\n"; // Shader creation .... shader = CShaderManager::Instance().loadfromFile( vertexShadername.c_str(), fragmentShadername.c_str(), shaderType, config); } shader->Link(); // Attrib blinding ... LoadShaderAttributs(shader, root); // Textures uniform LoadShaderTextures(shader, root); // Matrix uniform LoadShaderMatrix(shader, root); // FBO LoadShaderFBO(shader, root); // Materials LoadMaterials(shader, root); // Update all bindings // * Warning : Need to relink after shader->UpdateAll(); return shader; }
//unused void FzOR::ClearDOM() { throw CException("<FzOR::ClearDOM>: invalid context"); }
void ShadersLoader::LoadShaderFBO(Shader* shader, TiXmlElement *root) { TiXmlElement *rootFBO = root->FirstChildElement("OutputFrame"); if (!rootFBO) { Logger::Log() << "[INFO] No FBO is available ... \n"; return; } // Get the depth buffer type std::string typeDepthString; TinyXMLGetAttributeValue<std::string>(rootFBO, "depthType", &typeDepthString); Logger::Log() << " * Depth buffer type " << typeDepthString << "\n"; FBODepthType typeDepth; if (typeDepthString == "None") { typeDepth = FBODEPTH_NONE; } else if (typeDepthString == "RenderTarget") { typeDepth = FBODEPTH_RENDERTARGET; } else if (typeDepthString == "Texture") { typeDepth = FBODEPTH_TEXTURE; } else throw CException("invalid buffer type"); // Get the size of buffer std::string typeSize; int X = 0; int Y = 0; TinyXMLGetAttributeValue<std::string>(rootFBO, "size", &typeSize); if (typeSize == "Screen") { Math::TVector2I sizeScreen = CSettingsManager::Instance().GetSizeRenderingWindow(); X = sizeScreen.x; Y = sizeScreen.y; } else if (typeSize == "HalfScreen") { Math::TVector2I sizeScreen = CSettingsManager::Instance().GetSizeRenderingWindow(); X = sizeScreen.x / 2; Y = sizeScreen.y / 2; } else if (typeSize == "Custom") { TinyXMLGetAttributeValue<int>(rootFBO, "width", &X); TinyXMLGetAttributeValue<int>(rootFBO, "height", &Y); } else { throw CException("unknow type of size"); } // Get all buffers std::map<std::string, FBOTextureBufferParam> buffers; Logger::Log() << " * Chargement des differents buffers .... \n"; TiXmlElement *frameNode = rootFBO->FirstChildElement("Frame"); shader->Begin(); while (frameNode) { std::string name; std::string typeString; TinyXMLGetAttributeValue<std::string>(frameNode, "name", &name); TinyXMLGetAttributeValue<std::string>(frameNode, "type", &typeString); Logger::Log() << " * Create buffer : " << name << " ( " << typeString << " ) \n"; FBOTextureBufferParam param; // Mipmapping parsing bool mipmapping = false; frameNode->Attribute("mipmapping", &mipmapping); if (mipmapping) { Logger::Log() << " * Mipmapping enable \n"; param.GenerateMipMapping = true; param.MinFiltering = GL_LINEAR_MIPMAP_NEAREST; param.MaxFiltering = GL_LINEAR; } bool bilinear = false; frameNode->Attribute("bilinear", &bilinear); if(bilinear) { Logger::Log() << " * Bilinear enable \n"; param.MinFiltering = GL_LINEAR; param.MaxFiltering = GL_LINEAR; } if(bilinear && mipmapping) throw CException("Impossible to activate Bilinear & mipmapping on the same texture"); // Parse the Image format if (typeString == "RGBA") { // Nothing to do } else if (typeString == "RGB16") { param.InternalFormat = GL_RGB16F; param.ExternalFormat = GL_RGB; } else if (typeString == "RGB32") { param.InternalFormat = GL_RGB32F; param.ExternalFormat = GL_RGB; } else if (typeString == "RGBA16") { param.InternalFormat = GL_RGBA16F; param.ExternalFormat = GL_RGBA; } else if (typeString == "RGBA32") { param.InternalFormat = GL_RGBA32F; param.ExternalFormat = GL_RGBA; } else if (typeString == "L") { param.InternalFormat = GL_LUMINANCE32F_ARB; param.ExternalFormat = GL_LUMINANCE; } else throw CException("unknow buffer type"); param.Attachment = glGetFragDataLocation(shader->GetProgramObject(), name.c_str()); Logger::Log() << " * Attachment : " << param.Attachment << "\n"; buffers[name] = param; frameNode = frameNode->NextSiblingElement("Frame"); } shader->End(); FBODepthBufferParam bufferDepth; FBO* fbo = new FBO(Math::TVector2I(X, Y), buffers, typeDepth, bufferDepth); // FIXME: Inversion des tailles ??? shader->SetFBO(fbo); }
void FzOR::ORwithDOM(float /*val*/) { throw CException("<FzOR::ORwithDOM>: invalid context"); }
//---------------------------------------- void CExternalFilesAvisoGrid::AddVirtualVariables() { int32_t dimId = -1; try { CheckNetCDFDimensions(); } catch(CException& e) { throw CException(CTools::Format("ERROR: CExternalFilesAvisoGrid::AddVirtualVariables - %s", e.what()), BRATHL_LOGIC_ERROR); } CStringMap mapAttributes; //-------------- // add latitude var //-------------- mapAttributes.RemoveAll(); mapAttributes.Insert(STANDARD_NAME_ATTR, "latitude"); dimId = m_latDim->GetDimId(); AddVar(dimId, CExternalFilesAvisoGrid::m_LAT_DIM_NAME, "Latitude of measurement", CLatLonPoint::m_DEFAULT_UNIT_LATITUDE, NC_DOUBLE, m_nbLatitudes, CExternalFilesAvisoGrid::m_LAT_DIM_NAME, dimId, &mapAttributes); CNetCDFCoordinateAxis latVar(CExternalFilesAvisoGrid::m_LAT_DIM_NAME, CLatLonPoint::m_DEFAULT_UNIT_LATITUDE, Latitude); latVar.AddNetCDFDim(*m_latDim); m_latDim->AddCoordinateVariable(latVar.GetName()); m_file.AddNetCDFVarDef(latVar, true); //-------------- // add longitude var //-------------- mapAttributes.RemoveAll(); mapAttributes.Insert(STANDARD_NAME_ATTR, "longitude"); dimId = m_lonDim->GetDimId(); AddVar(dimId, CExternalFilesAvisoGrid::m_LON_DIM_NAME, "Longitude of measurement", CLatLonPoint::m_DEFAULT_UNIT_LONGITUDE, NC_DOUBLE, m_nbLongitudes, CExternalFilesAvisoGrid::m_LON_DIM_NAME, dimId, &mapAttributes); CNetCDFCoordinateAxis lonVar(CExternalFilesAvisoGrid::m_LON_DIM_NAME, CLatLonPoint::m_DEFAULT_UNIT_LONGITUDE, Longitude); lonVar.AddNetCDFDim(*m_lonDim); m_lonDim->AddCoordinateVariable(lonVar.GetName()); m_file.AddNetCDFVarDef(lonVar, true); //-------------- // add depth //-------------- if (m_file.VarExists(CExternalFilesAvisoGrid::m_INTERNAL_DEPTH_DIM_NAME)) { AddVar(CExternalFilesAvisoGrid::m_INTERNAL_DEPTH_DIM_NAME); } else { mapAttributes.RemoveAll(); mapAttributes.Insert(STANDARD_NAME_ATTR, "depth"); dimId = m_depthDim->GetDimId(); AddVar(dimId, CExternalFilesAvisoGrid::m_INTERNAL_DEPTH_DIM_NAME, "Depth layer", "count", NC_DOUBLE, m_nbDepths, CExternalFilesAvisoGrid::m_INTERNAL_DEPTH_DIM_NAME, dimId, &mapAttributes); CNetCDFCoordinateAxis depthVar(CExternalFilesAvisoGrid::m_INTERNAL_DEPTH_DIM_NAME, "count", Z); depthVar.AddNetCDFDim(*m_depthDim); m_depthDim->AddCoordinateVariable(depthVar.GetName()); m_file.AddNetCDFVarDef(depthVar, true); } }
//---------------------------------------- int32_t CBratProcessExportAscii::Execute(string& msg) { int32_t result = BRATHL_SUCCESS; CDate startExec; startExec.SetDateNow(); if (m_product == NULL) { throw CException("PROGRAM ERROR: product is NULL (CBratProcessExportAscii::Execute) - Perhaps, initialization has not been called", BRATHL_LOGIC_ERROR); } m_product->SetExpandArray(m_expandArray); // Always 'expand array' for Netcdf Product (To show data in column and data value by line) m_product->SetForceReadDataOneByOne(true); m_writeHeader = true; uint32_t nbFiles = m_inputFiles.size(); uint32_t cptFile = 0; CStringArray::iterator itFile; //for each file, read and write data for (itFile = m_inputFiles.begin() ; itFile != m_inputFiles.end() ; itFile++) { cptFile++; CTrace::Tracer(1,"File %d/%d - Reading record data from %s ... and registering data ...", cptFile, nbFiles, (*itFile).c_str()); // open file an set record name and list of field to read m_product->SetFieldSpecificUnits(m_fieldSpecificUnit); m_product->Open(*itFile, m_recordName); m_product->SetListFieldToRead(m_listFieldsToRead, false); // Get the number of record for the default record name (set in Open method of CProduct above) int32_t nRecords = m_product->GetNumberOfRecords(); for (int32_t iRecord = 0 ; iRecord < nRecords ; iRecord++) { //Read fields for the record name (listof field and record name are set in Open method of CProduct above) m_product->ReadBratRecord(iRecord); WriteData(); //m_writeHeader = false; } m_product->Close(); } if (m_product->GetSkippedRecordCount() > 0) { string msg = CTools::Format("WARNING - %d input data records have been skipped due to inconsistency between two measures", m_product->GetSkippedRecordCount()); CTrace::Tracer(1, msg); } CTrace::Tracer(1,"End processing - OK"); CDate endExec; endExec.SetDateNow(); CTrace::Tracer(1, CTools::Format("Processing time: %.3f seconds (%.2f minutes)\n", (endExec - startExec), (endExec - startExec) / 60.0)); return result; }
////////////////////////////////////////////////////////////////////////////////////////////////// // // // void CLeyboldSimPortDriver::CThreadRunable::run() // // // // Description: // // static method, implements a thread that waits for connecting sockets and responds // /// to packet requests. // // // ////////////////////////////////////////////////////////////////////////////////////////////////// void CLeyboldSimPortDriver::CThreadRunable::run() { asynUser* IOUser; const char* IOPortName = epicsThreadGetNameSelf(); size_t TableIndex; { epicsGuard < epicsMutex > guard ( CLeyboldSimPortDriver::m_Mutex ); std::string LookupPortName = IOPortName; size_t Colon1Pos = LookupPortName.rfind(":1"); LookupPortName = LookupPortName.substr(0, Colon1Pos); std::map<std::string, size_t>::const_iterator Iter = m_This->m_TableLookup.find(LookupPortName); if (Iter == m_This->m_TableLookup.end()) throw CException(m_This->pasynUserSelf, asynError, __FUNCTION__, "Pump name not found"); TableIndex = int(Iter->second); } asynUser* asynUser = m_This->m_asynUsers[TableIndex]; try { asynStatus Status = pasynOctetSyncIO->connect(IOPortName, int(TableIndex), &IOUser, NULL); if (Status != asynSuccess) throw CException(m_This->pasynUserSelf, Status, __FUNCTION__, "connecting to IO port=" + std::string(IOPortName)); { epicsGuard < epicsMutex > guard ( CLeyboldSimPortDriver::m_Mutex ); m_This->m_RunRecord.push_back(RunRecord(On, getTickCount())); } while (!m_Exiting) { if (m_This->getNoOfPZD() == NoOfPZD2) { USSPacket<NoOfPZD2> USSReadPacket, USSWritePacket(false); if (m_This->read<NoOfPZD2>(asynUser, IOUser, USSReadPacket, TableIndex)) { if (!m_This->process<NoOfPZD2>(IOUser, USSReadPacket, USSWritePacket, TableIndex)) break; } } else { USSPacket<NoOfPZD6> USSReadPacket, USSWritePacket(false); if (m_This->read<NoOfPZD6>(asynUser, IOUser, USSReadPacket, TableIndex)) { m_This->process(USSWritePacket, int(TableIndex)); if (!m_This->process<NoOfPZD6>(IOUser, USSReadPacket, USSWritePacket, TableIndex)) break; } } } } catch(CException const&) { } asynStatus status = pasynOctetSyncIO->disconnect(IOUser); if (status != asynSuccess) { asynPrint(asynUser, ASYN_TRACE_ERROR, "ListenerThread: Can't disconnect port %s IOUser\n", IOPortName); } { epicsGuard < epicsMutex > guard ( CLeyboldSimPortDriver::m_Mutex ); status = pasynManager->freeAsynUser(IOUser); if (status != asynSuccess) asynPrint(asynUser, ASYN_TRACE_ERROR, "echoListener: Can't free port %s IOUser\n", IOPortName); status = pasynManager->freeAsynUser(asynUser); if (status != asynSuccess) asynPrint(m_This->pasynUserSelf, ASYN_TRACE_ERROR, "echoListener: Can't free port %s asynUser\n", IOPortName); if (m_This->m_asynUsers.size() > TableIndex) m_This->m_asynUsers.erase(m_This->m_asynUsers.begin()+TableIndex); if (m_This->m_RunRecord.size() > TableIndex) m_This->m_RunRecord.erase(m_This->m_RunRecord.begin()+TableIndex); } }
void CClient::UserCommand(CString& sLine) { if (!m_pUser) { return; } if (sLine.empty()) { return; } NETWORKMODULECALL(OnStatusCommand(sLine), m_pUser, m_pNetwork, this, return); const CString sCommand = sLine.Token(0); if (sCommand.Equals("HELP")) { HelpUser(); } else if (sCommand.Equals("LISTNICKS")) { if (!m_pNetwork) { PutStatus("You must be connected with a network to use this command"); return; } CString sChan = sLine.Token(1); if (sChan.empty()) { PutStatus("Usage: ListNicks <#chan>"); return; } CChan* pChan = m_pNetwork->FindChan(sChan); if (!pChan) { PutStatus("You are not on [" + sChan + "]"); return; } if (!pChan->IsOn()) { PutStatus("You are not on [" + sChan + "] [trying]"); return; } const map<CString,CNick>& msNicks = pChan->GetNicks(); CIRCSock* pIRCSock = m_pNetwork->GetIRCSock(); const CString& sPerms = (pIRCSock) ? pIRCSock->GetPerms() : ""; if (!msNicks.size()) { PutStatus("No nicks on [" + sChan + "]"); return; } CTable Table; for (unsigned int p = 0; p < sPerms.size(); p++) { CString sPerm; sPerm += sPerms[p]; Table.AddColumn(sPerm); } Table.AddColumn("Nick"); Table.AddColumn("Ident"); Table.AddColumn("Host"); for (map<CString,CNick>::const_iterator a = msNicks.begin(); a != msNicks.end(); ++a) { Table.AddRow(); for (unsigned int b = 0; b < sPerms.size(); b++) { if (a->second.HasPerm(sPerms[b])) { CString sPerm; sPerm += sPerms[b]; Table.SetCell(sPerm, sPerm); } } Table.SetCell("Nick", a->second.GetNick()); Table.SetCell("Ident", a->second.GetIdent()); Table.SetCell("Host", a->second.GetHost()); } PutStatus(Table); } else if (sCommand.Equals("DETACH")) { if (!m_pNetwork) { PutStatus("You must be connected with a network to use this command"); return; } CString sChan = sLine.Token(1); if (sChan.empty()) { PutStatus("Usage: Detach <#chan>"); return; } const vector<CChan*>& vChans = m_pNetwork->GetChans(); vector<CChan*>::const_iterator it; unsigned int uMatches = 0, uDetached = 0; for (it = vChans.begin(); it != vChans.end(); ++it) { if (!(*it)->GetName().WildCmp(sChan)) continue; uMatches++; if ((*it)->IsDetached()) continue; uDetached++; (*it)->DetachUser(); } PutStatus("There were [" + CString(uMatches) + "] channels matching [" + sChan + "]"); PutStatus("Detached [" + CString(uDetached) + "] channels"); } else if (sCommand.Equals("VERSION")) { PutStatus(CZNC::GetTag()); PutStatus(CZNC::GetCompileOptionsString()); } else if (sCommand.Equals("MOTD") || sCommand.Equals("ShowMOTD")) { if (!SendMotd()) { PutStatus("There is no MOTD set."); } } else if (m_pUser->IsAdmin() && sCommand.Equals("Rehash")) { CString sRet; if (CZNC::Get().RehashConfig(sRet)) { PutStatus("Rehashing succeeded!"); } else { PutStatus("Rehashing failed: " + sRet); } } else if (m_pUser->IsAdmin() && sCommand.Equals("SaveConfig")) { if (CZNC::Get().WriteConfig()) { PutStatus("Wrote config to [" + CZNC::Get().GetConfigFile() + "]"); } else { PutStatus("Error while trying to write config."); } } else if (sCommand.Equals("LISTCLIENTS")) { CUser* pUser = m_pUser; CString sNick = sLine.Token(1); if (!sNick.empty()) { if (!m_pUser->IsAdmin()) { PutStatus("Usage: ListClients"); return; } pUser = CZNC::Get().FindUser(sNick); if (!pUser) { PutStatus("No such user [" + sNick + "]"); return; } } vector<CClient*> vClients = pUser->GetAllClients(); if (vClients.empty()) { PutStatus("No clients are connected"); return; } CTable Table; Table.AddColumn("Host"); Table.AddColumn("Network"); for (unsigned int a = 0; a < vClients.size(); a++) { Table.AddRow(); Table.SetCell("Host", vClients[a]->GetRemoteIP()); if (vClients[a]->GetNetwork()) { Table.SetCell("Network", vClients[a]->GetNetwork()->GetName()); } } PutStatus(Table); } else if (m_pUser->IsAdmin() && sCommand.Equals("LISTUSERS")) { const map<CString, CUser*>& msUsers = CZNC::Get().GetUserMap(); CTable Table; Table.AddColumn("Username"); Table.AddColumn("Networks"); Table.AddColumn("Clients"); for (map<CString, CUser*>::const_iterator it = msUsers.begin(); it != msUsers.end(); ++it) { Table.AddRow(); Table.SetCell("Username", it->first); Table.SetCell("Networks", CString(it->second->GetNetworks().size())); Table.SetCell("Clients", CString(it->second->GetAllClients().size())); } PutStatus(Table); } else if (m_pUser->IsAdmin() && sCommand.Equals("SetMOTD")) { CString sMessage = sLine.Token(1, true); if (sMessage.empty()) { PutStatus("Usage: SetMOTD <Message>"); } else { CZNC::Get().SetMotd(sMessage); PutStatus("MOTD set to [" + sMessage + "]"); } } else if (m_pUser->IsAdmin() && sCommand.Equals("AddMOTD")) { CString sMessage = sLine.Token(1, true); if (sMessage.empty()) { PutStatus("Usage: AddMOTD <Message>"); } else { CZNC::Get().AddMotd(sMessage); PutStatus("Added [" + sMessage + "] to MOTD"); } } else if (m_pUser->IsAdmin() && sCommand.Equals("ClearMOTD")) { CZNC::Get().ClearMotd(); PutStatus("Cleared MOTD"); } else if (m_pUser->IsAdmin() && sCommand.Equals("BROADCAST")) { CZNC::Get().Broadcast(sLine.Token(1, true)); } else if (m_pUser->IsAdmin() && (sCommand.Equals("SHUTDOWN") || sCommand.Equals("RESTART"))) { bool bRestart = sCommand.Equals("RESTART"); CString sMessage = sLine.Token(1, true); bool bForce = false; if (sMessage.Token(0).Equals("FORCE")) { bForce = true; sMessage = sMessage.Token(1, true); } if (sMessage.empty()) { sMessage = (bRestart ? "ZNC is being restarted NOW!" : "ZNC is being shut down NOW!"); } if(!CZNC::Get().WriteConfig() && !bForce) { PutStatus("ERROR: Writing config file to disk failed! Aborting. Use " + sCommand.AsUpper() + " FORCE to ignore."); } else { CZNC::Get().Broadcast(sMessage); throw CException(bRestart ? CException::EX_Restart : CException::EX_Shutdown); } } else if (sCommand.Equals("JUMP") || sCommand.Equals("CONNECT")) { if (!m_pNetwork) { PutStatus("You must be connected with a network to use this command"); return; } if (!m_pNetwork->HasServers()) { PutStatus("You don't have any servers added."); return; } CString sArgs = sLine.Token(1, true); CServer *pServer = NULL; if (!sArgs.empty()) { pServer = m_pNetwork->FindServer(sArgs); if (!pServer) { PutStatus("Server [" + sArgs + "] not found"); return; } m_pNetwork->SetNextServer(pServer); // If we are already connecting to some server, // we have to abort that attempt Csock *pIRCSock = GetIRCSock(); if (pIRCSock && !pIRCSock->IsConnected()) { pIRCSock->Close(); } } if (GetIRCSock()) { GetIRCSock()->Quit(); if (pServer) PutStatus("Connecting to [" + pServer->GetName() + "]..."); else PutStatus("Jumping to the next server in the list..."); } else { if (pServer) PutStatus("Connecting to [" + pServer->GetName() + "]..."); else PutStatus("Connecting..."); } m_pNetwork->SetIRCConnectEnabled(true); return; } else if (sCommand.Equals("DISCONNECT")) { if (!m_pNetwork) { PutStatus("You must be connected with a network to use this command"); return; } if (GetIRCSock()) { CString sQuitMsg = sLine.Token(1, true); GetIRCSock()->Quit(sQuitMsg); } m_pNetwork->SetIRCConnectEnabled(false); PutStatus("Disconnected from IRC. Use 'connect' to reconnect."); return; } else if (sCommand.Equals("ENABLECHAN")) { if (!m_pNetwork) { PutStatus("You must be connected with a network to use this command"); return; } CString sChan = sLine.Token(1, true); if (sChan.empty()) { PutStatus("Usage: EnableChan <channel>"); } else { const vector<CChan*>& vChans = m_pNetwork->GetChans(); vector<CChan*>::const_iterator it; unsigned int uMatches = 0, uEnabled = 0; for (it = vChans.begin(); it != vChans.end(); ++it) { if (!(*it)->GetName().WildCmp(sChan)) continue; uMatches++; if (!(*it)->IsDisabled()) continue; uEnabled++; (*it)->Enable(); } PutStatus("There were [" + CString(uMatches) + "] channels matching [" + sChan + "]"); PutStatus("Enabled [" + CString(uEnabled) + "] channels"); } } else if (sCommand.Equals("LISTCHANS")) { if (!m_pNetwork) { PutStatus("You must be connected with a network to use this command"); return; } CUser* pUser = m_pUser; CIRCNetwork* pNetwork = m_pNetwork; const CString sNick = sLine.Token(1); const CString sNetwork = sLine.Token(2); if (!sNick.empty()) { if (!m_pUser->IsAdmin()) { PutStatus("Usage: ListChans"); return; } pUser = CZNC::Get().FindUser(sNick); if (!pUser) { PutStatus("No such user [" + sNick + "]"); return; } pNetwork = pUser->FindNetwork(sNetwork); if (!pNetwork) { PutStatus("No such network for user [" + sNetwork + "]"); return; } } const vector<CChan*>& vChans = pNetwork->GetChans(); CIRCSock* pIRCSock = pNetwork->GetIRCSock(); const CString& sPerms = (pIRCSock) ? pIRCSock->GetPerms() : ""; if (!vChans.size()) { PutStatus("There are no channels defined."); return; } CTable Table; Table.AddColumn("Name"); Table.AddColumn("Status"); Table.AddColumn("Conf"); Table.AddColumn("Buf"); Table.AddColumn("Modes"); Table.AddColumn("Users"); for (unsigned int p = 0; p < sPerms.size(); p++) { CString sPerm; sPerm += sPerms[p]; Table.AddColumn(sPerm); } unsigned int uNumDetached = 0, uNumDisabled = 0, uNumJoined = 0; for (unsigned int a = 0; a < vChans.size(); a++) { const CChan* pChan = vChans[a]; Table.AddRow(); Table.SetCell("Name", pChan->GetPermStr() + pChan->GetName()); Table.SetCell("Status", ((vChans[a]->IsOn()) ? ((vChans[a]->IsDetached()) ? "Detached" : "Joined") : ((vChans[a]->IsDisabled()) ? "Disabled" : "Trying"))); Table.SetCell("Conf", CString((pChan->InConfig()) ? "yes" : "")); Table.SetCell("Buf", CString((pChan->KeepBuffer()) ? "*" : "") + CString(pChan->GetBufferCount())); Table.SetCell("Modes", pChan->GetModeString()); Table.SetCell("Users", CString(pChan->GetNickCount())); map<char, unsigned int> mPerms = pChan->GetPermCounts(); for (unsigned int b = 0; b < sPerms.size(); b++) { char cPerm = sPerms[b]; Table.SetCell(CString(cPerm), CString(mPerms[cPerm])); } if(pChan->IsDetached()) uNumDetached++; if(pChan->IsOn()) uNumJoined++; if(pChan->IsDisabled()) uNumDisabled++; } PutStatus(Table); PutStatus("Total: " + CString(vChans.size()) + " - Joined: " + CString(uNumJoined) + " - Detached: " + CString(uNumDetached) + " - Disabled: " + CString(uNumDisabled)); } else if (sCommand.Equals("ADDNETWORK")) { #ifndef ENABLE_ADD_NETWORK if (!m_pUser->IsAdmin()) { PutStatus("Permission denied"); return; } #endif CString sNetwork = sLine.Token(1); if (sNetwork.empty()) { PutStatus("Usage: AddNetwork <name>"); return; } if (m_pUser->AddNetwork(sNetwork)) { PutStatus("Network added. Use /znc JumpNetwork " + sNetwork + ", or connect to ZNC with username " + m_pUser->GetUserName() + "/" + sNetwork + " (instead of just " + m_pUser->GetUserName() + ") to connect to it."); } else { PutStatus("Unable to add that network"); PutStatus("Perhaps that network is already added"); } } else if (m_pUser->IsAdmin() && sCommand.Equals("DELNETWORK")) { CString sNetwork = sLine.Token(1); if (sNetwork.empty()) { PutStatus("Usage: DelNetwork <name>"); return; } if (m_pNetwork && m_pNetwork->GetName().Equals(sNetwork)) { SetNetwork(NULL); } if (m_pUser->DeleteNetwork(sNetwork)) { PutStatus("Network deleted"); } else { PutStatus("Failed to delete network"); PutStatus("Perhaps this network doesn't exist"); } } else if (sCommand.Equals("LISTNETWORKS")) { CUser *pUser = m_pUser; if (m_pUser->IsAdmin() && !sLine.Token(1).empty()) { pUser = CZNC::Get().FindUser(sLine.Token(1)); if (!pUser) { PutStatus("User not found " + sLine.Token(1)); return; } } const vector<CIRCNetwork*>& vNetworks = pUser->GetNetworks(); CTable Table; Table.AddColumn("Network"); Table.AddColumn("OnIRC"); Table.AddColumn("IRC Server"); Table.AddColumn("IRC User"); Table.AddColumn("Channels"); for (unsigned int a = 0; a < vNetworks.size(); a++) { CIRCNetwork* pNetwork = vNetworks[a]; Table.AddRow(); Table.SetCell("Network", pNetwork->GetName()); if (pNetwork->IsIRCConnected()) { Table.SetCell("OnIRC", "Yes"); Table.SetCell("IRC Server", pNetwork->GetIRCServer()); Table.SetCell("IRC User", pNetwork->GetIRCNick().GetNickMask()); Table.SetCell("Channels", CString(pNetwork->GetChans().size())); } else { Table.SetCell("OnIRC", "No"); } } if (PutStatus(Table) == 0) { PutStatus("No networks"); } } else if (sCommand.Equals("JUMPNETWORK")) { CString sNetwork = sLine.Token(1); if (sNetwork.empty()) { PutStatus("No network supplied."); return; } if (m_pNetwork && (m_pNetwork->GetName() == sNetwork)) { PutStatus("You are already connected with this network."); return; } CIRCNetwork *pNetwork = m_pUser->FindNetwork(sNetwork); if (pNetwork) { PutStatus("Switched to " + sNetwork); SetNetwork(pNetwork); } else { PutStatus("You don't have a network named " + sNetwork); } } else if (sCommand.Equals("MODE")) { CString sNetwork = sLine.Token(1); if (sNetwork.empty()) { PutStatus("Syntax: MODE <support/default>"); return; } if (m_pNetwork && (m_pNetwork->GetName() == sNetwork)) { PutStatus("You are already in this mode."); return; } CIRCNetwork *pNetwork = m_pUser->FindNetwork(sNetwork); if (pNetwork) { PutStatus("You are now in " + sNetwork + " mode."); SetNetwork(pNetwork); } else { PutStatus("ERROR! Contact GeekBouncer admins immediately"); } } else if (m_pUser->IsAdmin() && sCommand.Equals("ADDSERVER")) { CString sServer = sLine.Token(1); if (!m_pNetwork) { PutStatus("You must be connected with a network to use this command"); return; } if (sServer.empty()) { PutStatus("Usage: AddServer <host> [[+]port] [pass]"); return; } if (m_pNetwork->AddServer(sLine.Token(1, true))) { PutStatus("Server added"); } else { PutStatus("Unable to add that server"); PutStatus("Perhaps the server is already added or openssl is disabled?"); } } else if (m_pUser->IsAdmin() && sCommand.Equals("REMSERVER") || sCommand.Equals("DELSERVER")) { if (!m_pNetwork) { PutStatus("You must be connected with a network to use this command"); return; } CString sServer = sLine.Token(1); unsigned short uPort = sLine.Token(2).ToUShort(); CString sPass = sLine.Token(3); if (sServer.empty()) { PutStatus("Usage: RemServer <host> [port] [pass]"); return; } if (!m_pNetwork->HasServers()) { PutStatus("You don't have any servers added."); return; } if (m_pNetwork->DelServer(sServer, uPort, sPass)) { PutStatus("Server removed"); } else { PutStatus("No such server"); } } else if (sCommand.Equals("LISTSERVERS")) { if (!m_pNetwork) { PutStatus("You must be connected with a network to use this command"); return; } if (m_pNetwork->HasServers()) { const vector<CServer*>& vServers = m_pNetwork->GetServers(); CServer* pCurServ = m_pNetwork->GetCurrentServer(); CTable Table; Table.AddColumn("Host"); Table.AddColumn("Port"); Table.AddColumn("SSL"); Table.AddColumn("Pass"); for (unsigned int a = 0; a < vServers.size(); a++) { CServer* pServer = vServers[a]; Table.AddRow(); Table.SetCell("Host", pServer->GetName() + (pServer == pCurServ ? "*" : "")); Table.SetCell("Port", CString(pServer->GetPort())); Table.SetCell("SSL", (pServer->IsSSL()) ? "SSL" : ""); Table.SetCell("Pass", pServer->GetPass()); } PutStatus(Table); } else { PutStatus("You don't have any servers added."); } } else if (sCommand.Equals("TOPICS")) { if (!m_pNetwork) { PutStatus("You must be connected with a network to use this command"); return; } const vector<CChan*>& vChans = m_pNetwork->GetChans(); CTable Table; Table.AddColumn("Name"); Table.AddColumn("Set By"); Table.AddColumn("Topic"); for (unsigned int a = 0; a < vChans.size(); a++) { CChan* pChan = vChans[a]; Table.AddRow(); Table.SetCell("Name", pChan->GetName()); Table.SetCell("Set By", pChan->GetTopicOwner()); Table.SetCell("Topic", pChan->GetTopic()); } PutStatus(Table); } else if (sCommand.Equals("LISTMODS") || sCommand.Equals("LISTMODULES")) { if (m_pUser->IsAdmin()) { CModules& GModules = CZNC::Get().GetModules(); if (!GModules.size()) { PutStatus("No global modules loaded."); } else { PutStatus("Global modules:"); CTable GTable; GTable.AddColumn("Name"); GTable.AddColumn("Arguments"); for (unsigned int b = 0; b < GModules.size(); b++) { GTable.AddRow(); GTable.SetCell("Name", GModules[b]->GetModName()); GTable.SetCell("Arguments", GModules[b]->GetArgs()); } PutStatus(GTable); } } CModules& Modules = m_pUser->GetModules(); if (!Modules.size()) { PutStatus("Your user has no modules loaded."); } else { PutStatus("User modules:"); CTable Table; Table.AddColumn("Name"); Table.AddColumn("Arguments"); for (unsigned int b = 0; b < Modules.size(); b++) { Table.AddRow(); Table.SetCell("Name", Modules[b]->GetModName()); Table.SetCell("Arguments", Modules[b]->GetArgs()); } PutStatus(Table); } if (m_pNetwork) { CModules& NetworkModules = m_pNetwork->GetModules(); if (NetworkModules.empty()) { PutStatus("This network has no modules loaded."); } else { PutStatus("Network modules:"); CTable Table; Table.AddColumn("Name"); Table.AddColumn("Arguments"); for (unsigned int b = 0; b < NetworkModules.size(); b++) { Table.AddRow(); Table.SetCell("Name", NetworkModules[b]->GetModName()); Table.SetCell("Arguments", NetworkModules[b]->GetArgs()); } PutStatus(Table); } } return; } else if (sCommand.Equals("LISTAVAILMODS") || sCommand.Equals("LISTAVAILABLEMODULES")) { if (m_pUser->DenyLoadMod()) { PutStatus("Access Denied."); return; } if (m_pUser->IsAdmin()) { set<CModInfo> ssGlobalMods; CZNC::Get().GetModules().GetAvailableMods(ssGlobalMods, CModInfo::GlobalModule); if (ssGlobalMods.empty()) { PutStatus("No global modules available."); } else { PutStatus("Global modules:"); CTable GTable; GTable.AddColumn("Name"); GTable.AddColumn("Description"); set<CModInfo>::iterator it; for (it = ssGlobalMods.begin(); it != ssGlobalMods.end(); ++it) { const CModInfo& Info = *it; GTable.AddRow(); GTable.SetCell("Name", (CZNC::Get().GetModules().FindModule(Info.GetName()) ? "*" : " ") + Info.GetName()); GTable.SetCell("Description", Info.GetDescription().Ellipsize(128)); } PutStatus(GTable); } } set<CModInfo> ssUserMods; CZNC::Get().GetModules().GetAvailableMods(ssUserMods); if (!ssUserMods.size()) { PutStatus("No user modules available."); } else { PutStatus("User modules:"); CTable Table; Table.AddColumn("Name"); Table.AddColumn("Description"); set<CModInfo>::iterator it; for (it = ssUserMods.begin(); it != ssUserMods.end(); ++it) { const CModInfo& Info = *it; Table.AddRow(); Table.SetCell("Name", (m_pUser->GetModules().FindModule(Info.GetName()) ? "*" : " ") + Info.GetName()); Table.SetCell("Description", Info.GetDescription().Ellipsize(128)); } PutStatus(Table); } set<CModInfo> ssNetworkMods; CZNC::Get().GetModules().GetAvailableMods(ssNetworkMods, CModInfo::NetworkModule); if (!ssNetworkMods.size()) { PutStatus("No network modules available."); } else { PutStatus("Network modules:"); CTable Table; Table.AddColumn("Name"); Table.AddColumn("Description"); set<CModInfo>::const_iterator it; for (it = ssNetworkMods.begin(); it != ssNetworkMods.end(); ++it) { const CModInfo& Info = *it; Table.AddRow(); Table.SetCell("Name", ((m_pNetwork && m_pNetwork->GetModules().FindModule(Info.GetName())) ? "*" : " ") + Info.GetName()); Table.SetCell("Description", Info.GetDescription().Ellipsize(128)); } PutStatus(Table); } return; } else if (sCommand.Equals("LOADMOD") || sCommand.Equals("LOADMODULE")) { CModInfo::EModuleType eType; CString sType = sLine.Token(1); CString sMod = sLine.Token(2); CString sArgs = sLine.Token(3, true); if (sType.Equals("global")) { eType = CModInfo::GlobalModule; } else if (sType.Equals("user")) { eType = CModInfo::UserModule; } else if (sType.Equals("network")) { eType = CModInfo::NetworkModule; } else { sMod = sType; sArgs = sLine.Token(2, true); sType = "default"; // Will be set correctly later eType = CModInfo::UserModule; } if (m_pUser->DenyLoadMod()) { PutStatus("Unable to load [" + sMod + "]: Access Denied."); return; } if (sMod.empty()) { PutStatus("Usage: LoadMod [type] <module> [args]"); return; } CModInfo ModInfo; CString sRetMsg; if (!CZNC::Get().GetModules().GetModInfo(ModInfo, sMod, sRetMsg)) { PutStatus("Unable to find modinfo [" + sMod + "] [" + sRetMsg + "]"); return; } if (sType.Equals("default")) { eType = ModInfo.GetDefaultType(); } if (eType == CModInfo::GlobalModule && !m_pUser->IsAdmin()) { PutStatus("Unable to load global module [" + sMod + "]: Access Denied."); return; } if (eType == CModInfo::NetworkModule && !m_pNetwork) { PutStatus("Unable to load network module [" + sMod + "] Not connected with a network."); return; } CString sModRet; bool b = false; switch (eType) { case CModInfo::GlobalModule: b = CZNC::Get().GetModules().LoadModule(sMod, sArgs, eType, NULL, NULL, sModRet); break; case CModInfo::UserModule: b = m_pUser->GetModules().LoadModule(sMod, sArgs, eType, m_pUser, NULL, sModRet); break; case CModInfo::NetworkModule: b = m_pNetwork->GetModules().LoadModule(sMod, sArgs, eType, m_pUser, m_pNetwork, sModRet); break; default: sModRet = "Unable to load module [" + sMod + "]: Unknown module type"; } if (b) sModRet = "Loaded module [" + sMod + "] " + sModRet; PutStatus(sModRet); return; } else if (sCommand.Equals("UNLOADMOD") || sCommand.Equals("UNLOADMODULE")) { CModInfo::EModuleType eType = CModInfo::UserModule; CString sType = sLine.Token(1); CString sMod = sLine.Token(2); if (sType.Equals("global")) { eType = CModInfo::GlobalModule; } else if (sType.Equals("user")) { eType = CModInfo::UserModule; } else if (sType.Equals("network")) { eType = CModInfo::NetworkModule; } else { sMod = sType; sType = "default"; } if (m_pUser->DenyLoadMod()) { PutStatus("Unable to unload [" + sMod + "] Access Denied."); return; } if (sMod.empty()) { PutStatus("Usage: UnloadMod [type] <module>"); return; } if (sType.Equals("default")) { CModInfo ModInfo; CString sRetMsg; if (!CZNC::Get().GetModules().GetModInfo(ModInfo, sMod, sRetMsg)) { PutStatus("Unable to find modinfo [" + sMod + "] [" + sRetMsg + "]"); return; } eType = ModInfo.GetDefaultType(); } if (eType == CModInfo::GlobalModule && !m_pUser->IsAdmin()) { PutStatus("Unable to unload global module [" + sMod + "]: Access Denied."); return; } if (eType == CModInfo::NetworkModule && !m_pNetwork) { PutStatus("Unable to unload network module [" + sMod + "] Not connected with a network."); return; } CString sModRet; switch (eType) { case CModInfo::GlobalModule: CZNC::Get().GetModules().UnloadModule(sMod, sModRet); break; case CModInfo::UserModule: m_pUser->GetModules().UnloadModule(sMod, sModRet); break; case CModInfo::NetworkModule: m_pNetwork->GetModules().UnloadModule(sMod, sModRet); break; default: sModRet = "Unable to unload module [" + sMod + "]: Unknown module type"; } PutStatus(sModRet); return; } else if (sCommand.Equals("RELOADMOD") || sCommand.Equals("RELOADMODULE")) { CModInfo::EModuleType eType; CString sType = sLine.Token(1); CString sMod = sLine.Token(2); CString sArgs = sLine.Token(3, true); if (m_pUser->DenyLoadMod()) { PutStatus("Unable to reload modules. Access Denied."); return; } if (sType.Equals("global")) { eType = CModInfo::GlobalModule; } else if (sType.Equals("user")) { eType = CModInfo::UserModule; } else if (sType.Equals("network")) { eType = CModInfo::NetworkModule; } else { sMod = sType; sArgs = sLine.Token(2, true); sType = "default"; // Will be set correctly later eType = CModInfo::UserModule; } if (sMod.empty()) { PutStatus("Usage: ReloadMod [type] <module> [args]"); return; } if (sType.Equals("default")) { CModInfo ModInfo; CString sRetMsg; if (!CZNC::Get().GetModules().GetModInfo(ModInfo, sMod, sRetMsg)) { PutStatus("Unable to find modinfo for [" + sMod + "] [" + sRetMsg + "]"); return; } eType = ModInfo.GetDefaultType(); } if (eType == CModInfo::GlobalModule && !m_pUser->IsAdmin()) { PutStatus("Unable to reload global module [" + sMod + "]: Access Denied."); return; } if (eType == CModInfo::NetworkModule && !m_pNetwork) { PutStatus("Unable to load network module [" + sMod + "] Not connected with a network."); return; } CString sModRet; switch (eType) { case CModInfo::GlobalModule: CZNC::Get().GetModules().ReloadModule(sMod, sArgs, NULL, NULL, sModRet); break; case CModInfo::UserModule: m_pUser->GetModules().ReloadModule(sMod, sArgs, m_pUser, NULL, sModRet); break; case CModInfo::NetworkModule: m_pNetwork->GetModules().ReloadModule(sMod, sArgs, m_pUser, m_pNetwork, sModRet); break; default: sModRet = "Unable to reload module [" + sMod + "]: Unknown module type"; } PutStatus(sModRet); return; } else if ((sCommand.Equals("UPDATEMOD") || sCommand.Equals("UPDATEMODULE")) && m_pUser->IsAdmin() ) { CString sMod = sLine.Token(1); if (sMod.empty()) { PutStatus("Usage: UpdateMod <module>"); return; } PutStatus("Reloading [" + sMod + "] everywhere"); if (CZNC::Get().UpdateModule(sMod)) { PutStatus("Done"); } else { PutStatus("Done, but there were errors, [" + sMod + "] could not be loaded everywhere."); } } else if ((sCommand.Equals("ADDBINDHOST") || sCommand.Equals("ADDVHOST")) && m_pUser->IsAdmin()) { CString sHost = sLine.Token(1); if (sHost.empty()) { PutStatus("Usage: AddBindHost <host>"); return; } if (CZNC::Get().AddBindHost(sHost)) { PutStatus("Done"); } else { PutStatus("The host [" + sHost + "] is already in the list"); } } else if ((sCommand.Equals("REMBINDHOST") || sCommand.Equals("REMVHOST") || sCommand.Equals("DELVHOST")) && m_pUser->IsAdmin()) { CString sHost = sLine.Token(1); if (sHost.empty()) { PutStatus("Usage: RemBindHost <host>"); return; } if (CZNC::Get().RemBindHost(sHost)) { PutStatus("Done"); } else { PutStatus("The host [" + sHost + "] is not in the list"); } } else if ((sCommand.Equals("LISTBINDHOSTS") || sCommand.Equals("LISTVHOSTS")) && (m_pUser->IsAdmin() || !m_pUser->DenySetBindHost())) { const VCString& vsHosts = CZNC::Get().GetBindHosts(); if (vsHosts.empty()) { PutStatus("No bind hosts configured"); return; } CTable Table; Table.AddColumn("Host"); VCString::const_iterator it; for (it = vsHosts.begin(); it != vsHosts.end(); ++it) { Table.AddRow(); Table.SetCell("Host", *it); } PutStatus(Table); } else if ((sCommand.Equals("SETBINDHOST") || sCommand.Equals("SETVHOST")) && (m_pUser->IsAdmin() || !m_pUser->DenySetBindHost())) { CString sHost = sLine.Token(1); if (sHost.empty()) { PutStatus("Usage: SetBindHost <host>"); return; } if (sHost.Equals(m_pUser->GetBindHost())) { PutStatus("You already have this bind host!"); return; } const VCString& vsHosts = CZNC::Get().GetBindHosts(); if (!m_pUser->IsAdmin() && !vsHosts.empty()) { VCString::const_iterator it; bool bFound = false; for (it = vsHosts.begin(); it != vsHosts.end(); ++it) { if (sHost.Equals(*it)) { bFound = true; break; } } if (!bFound) { PutStatus("You may not use this bind host. See [ListBindHosts] for a list"); return; } } m_pUser->SetBindHost(sHost); PutStatus("Set bind host to [" + m_pUser->GetBindHost() + "]"); } else if ((sCommand.Equals("CLEARBINDHOST") || sCommand.Equals("CLEARVHOST")) && (m_pUser->IsAdmin() || !m_pUser->DenySetBindHost())) { m_pUser->SetBindHost(""); PutStatus("Bind Host Cleared"); } else if (sCommand.Equals("PLAYBUFFER")) { if (!m_pNetwork) { PutStatus("You must be connected with a network to use this command"); return; } CString sChan = sLine.Token(1); if (sChan.empty()) { PutStatus("Usage: PlayBuffer <#chan>"); return; } CChan* pChan = m_pNetwork->FindChan(sChan); if (!pChan) { PutStatus("You are not on [" + sChan + "]"); return; } if (!pChan->IsOn()) { PutStatus("You are not on [" + sChan + "] [trying]"); return; } if (pChan->GetBuffer().IsEmpty()) { PutStatus("The buffer for [" + sChan + "] is empty"); return; } pChan->SendBuffer(this); } else if (sCommand.Equals("CLEARBUFFER")) { if (!m_pNetwork) { PutStatus("You must be connected with a network to use this command"); return; } CString sChan = sLine.Token(1); if (sChan.empty()) { PutStatus("Usage: ClearBuffer <#chan>"); return; } CChan* pChan = m_pNetwork->FindChan(sChan); if (!pChan) { PutStatus("You are not on [" + sChan + "]"); return; } const vector<CChan*>& vChans = m_pNetwork->GetChans(); vector<CChan*>::const_iterator it; unsigned int uMatches = 0; for (it = vChans.begin(); it != vChans.end(); ++it) { if (!(*it)->GetName().WildCmp(sChan)) continue; uMatches++; (*it)->ClearBuffer(); } PutStatus("The buffer for [" + CString(uMatches) + "] channels matching [" + sChan + "] has been cleared"); } else if (sCommand.Equals("CLEARALLCHANNELBUFFERS")) { if (!m_pNetwork) { PutStatus("You must be connected with a network to use this command"); return; } vector<CChan*>::const_iterator it; const vector<CChan*>& vChans = m_pNetwork->GetChans(); for (it = vChans.begin(); it != vChans.end(); ++it) { (*it)->ClearBuffer(); } PutStatus("All channel buffers have been cleared"); } else if (sCommand.Equals("SETBUFFER")) { if (!m_pNetwork) { PutStatus("You must be connected with a network to use this command"); return; } CString sChan = sLine.Token(1); if (sChan.empty()) { PutStatus("Usage: SetBuffer <#chan> [linecount]"); return; } unsigned int uLineCount = sLine.Token(2).ToUInt(); const vector<CChan*>& vChans = m_pNetwork->GetChans(); vector<CChan*>::const_iterator it; unsigned int uMatches = 0, uFail = 0; for (it = vChans.begin(); it != vChans.end(); ++it) { if (!(*it)->GetName().WildCmp(sChan)) continue; uMatches++; if (!(*it)->SetBufferCount(uLineCount)) uFail++; } PutStatus("BufferCount for [" + CString(uMatches - uFail) + "] channels was set to [" + CString(uLineCount) + "]"); if (uFail > 0) { PutStatus("Setting BufferCount failed for [" + CString(uFail) + "] channels, " "max buffer count is " + CString(CZNC::Get().GetMaxBufferSize())); } } else if (m_pUser->IsAdmin() && sCommand.Equals("TRAFFIC")) { CZNC::TrafficStatsPair Users, ZNC, Total; CZNC::TrafficStatsMap traffic = CZNC::Get().GetTrafficStats(Users, ZNC, Total); CZNC::TrafficStatsMap::const_iterator it; CTable Table; Table.AddColumn("Username"); Table.AddColumn("In"); Table.AddColumn("Out"); Table.AddColumn("Total"); for (it = traffic.begin(); it != traffic.end(); ++it) { Table.AddRow(); Table.SetCell("Username", it->first); Table.SetCell("In", CString::ToByteStr(it->second.first)); Table.SetCell("Out", CString::ToByteStr(it->second.second)); Table.SetCell("Total", CString::ToByteStr(it->second.first + it->second.second)); } Table.AddRow(); Table.SetCell("Username", "<Users>"); Table.SetCell("In", CString::ToByteStr(Users.first)); Table.SetCell("Out", CString::ToByteStr(Users.second)); Table.SetCell("Total", CString::ToByteStr(Users.first + Users.second)); Table.AddRow(); Table.SetCell("Username", "<ZNC>"); Table.SetCell("In", CString::ToByteStr(ZNC.first)); Table.SetCell("Out", CString::ToByteStr(ZNC.second)); Table.SetCell("Total", CString::ToByteStr(ZNC.first + ZNC.second)); Table.AddRow(); Table.SetCell("Username", "<Total>"); Table.SetCell("In", CString::ToByteStr(Total.first)); Table.SetCell("Out", CString::ToByteStr(Total.second)); Table.SetCell("Total", CString::ToByteStr(Total.first + Total.second)); PutStatus(Table); } else if (sCommand.Equals("UPTIME")) { PutStatus("Running for " + CZNC::Get().GetUptime()); } else if (m_pUser->IsAdmin() && (sCommand.Equals("LISTPORTS") || sCommand.Equals("ADDPORT") || sCommand.Equals("DELPORT"))) { UserPortCommand(sLine); } else { PutStatus("Unknown command [" + sCommand + "] try 'Help'"); } }
int zaFont::load_font(char * instr,int len) { char * pin = NULL; char * pout = NULL; char *p = NULL; char* inbuf = pin ; // m_filepos, file head char* outbuf = pout; if (len==0)// utf8, { int ll= strlen(instr); size_t inbytesleft= ll+1; size_t outbytesleft = inbytesleft*2; pin = (char *)malloc(inbytesleft); pout = (char *)malloc(outbytesleft); inbuf = pin ; // m_filepos, file head outbuf = pout; fprintf(stderr,"zaFont::load_font load begin length %d\n",ll); strcpy(pin,instr); iconv_t tt; tt = iconv_open("UTF-16LE","UTF-8"); int ret = iconv(tt,&inbuf,&inbytesleft,&outbuf,&outbytesleft); if ( ret < 0) { fprintf(stderr,"zaFont::load_font load error errno %d\n",errno); throw CException(__FILE__,__LINE__,"zaFont::load_font convert error ,filename %s","NULL"); } fprintf(stderr,"zaFont::load_font sucess.%d--%d:\n",ll*2,outbytesleft); iconv_close(tt); len = ll*2- outbytesleft; p= pout; } else p = instr; FT_Library library; FT_Face face; int c; int i, j; font_t* font = NULL; if(FT_Init_FreeType(&library)) { fprintf(stderr, "Error loading Freetype library\n"); return NULL; } if (FT_New_Face(library, m_path,0,&face)) { fprintf(stderr, "Error loading font %s\n", m_path); return NULL; } if(FT_Set_Char_Size ( face, m_size * 64, m_size * 64, m_dpi, m_dpi)) { fprintf(stderr, "Error initializing character parameters\n"); return NULL; } unsigned int charcode = 0; for (int cci =0 ; cci < len ; cci +=2) { charcode = ((unsigned char)*(p+1))*256+(unsigned char)*p ; if (charcode == 601) { charcode --; charcode ++; } if (this->m_map.find(charcode)==m_map.end()) { font = (font_t*) malloc(sizeof(font_t)); font->initialized = 0; glGenTextures(1, &(font->font_texture)); //Let each glyph reside in 32x32 section of the font texture int segment_size_x = 0, segment_size_y = 0; int num_segments_x = 1;//16 int num_segments_y = 1;//8 FT_GlyphSlot slot; FT_Bitmap bmp; int glyph_width, glyph_height; //First calculate the max width and height of a character in a passed font for(c = 0; c < 1; c++) { // if(FT_Load_Char(face,0x4E2D+charcode-0x4E2D , FT_LOAD_RENDER)) { fprintf(stderr, "FT_Load_Char failed\n"); free(font); return NULL; } slot = face->glyph; bmp = slot->bitmap; //glyph_width = nextp2(bmp.width); //glyph_height = nextp2(bmp.rows); glyph_width = bmp.width; glyph_height = bmp.rows; if (glyph_width > segment_size_x) { segment_size_x = glyph_width; } if (glyph_width > m_max_x) m_max_x = glyph_width; if (glyph_height > segment_size_y) { segment_size_y = glyph_height; } if (glyph_height > m_max_y) m_max_y = glyph_height; } int font_tex_width = nextp2(num_segments_x * segment_size_x); int font_tex_height = nextp2(num_segments_y * segment_size_y); int bitmap_offset_x = 0, bitmap_offset_y = 0; GLubyte* font_texture_data = (GLubyte*) malloc(sizeof(GLubyte) * 2 * font_tex_width * font_tex_height); memset((void*)font_texture_data, 0, sizeof(GLubyte) * 2 * font_tex_width * font_tex_height); if (!font_texture_data) { fprintf(stderr, "Failed to allocate memory for font texture\n"); free(font); return NULL; } // Fill font texture bitmap with individual bmp data and record appropriate size, texture coordinates and offsets for every glyph for(c = 0; c < 1; c++) { if(FT_Load_Char(face,0x4E2D+charcode-0x4E2D , FT_LOAD_RENDER)) { fprintf(stderr, "FT_Load_Char failed\n"); free(font); return NULL; } slot = face->glyph; bmp = slot->bitmap; glyph_width = nextp2(bmp.width); glyph_height = nextp2(bmp.rows); div_t temp = div(c, num_segments_x); bitmap_offset_x = segment_size_x * temp.rem; bitmap_offset_y = segment_size_y * temp.quot; for (j = 0; j < glyph_height; j++) { for (i = 0; i < glyph_width; i++) { font_texture_data[2 * ((bitmap_offset_x + i) + (j + bitmap_offset_y) * font_tex_width) + 0] = font_texture_data[2 * ((bitmap_offset_x + i) + (j + bitmap_offset_y) * font_tex_width) + 1] = (i >= bmp.width || j >= bmp.rows)? 0 : bmp.buffer[i + bmp.width * j]; } } font->advance[c] = (float)(slot->advance.x >> 6); font->tex_x1[c] = (float)bitmap_offset_x / (float) font_tex_width; font->tex_x2[c] = (float)(bitmap_offset_x + bmp.width) / (float)font_tex_width; font->tex_y1[c] = (float)bitmap_offset_y / (float) font_tex_height; font->tex_y2[c] = (float)(bitmap_offset_y + bmp.rows) / (float)font_tex_height; font->width[c] = bmp.width; font->height[c] = bmp.rows; font->offset_x[c] = (float)slot->bitmap_left; font->offset_y[c] = (float)((slot->metrics.horiBearingY-face->glyph->metrics.height) >> 6); } glBindTexture(GL_TEXTURE_2D, font->font_texture); 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, GL_LUMINANCE_ALPHA, font_tex_width, font_tex_height, 0, GL_LUMINANCE_ALPHA , GL_UNSIGNED_BYTE, font_texture_data); // fprintf(stderr, "charcode %d %d\n",charcode, cci); fflush(stderr); free(font_texture_data); font->initialized = 1; m_map[charcode] = font; } p += 2; }
void CSceneRendererCommandManager::Load(const std::string &FileName) { CXMLTreeNode parser; if (!parser.LoadFile(FileName.c_str())) { std::string msg_error = "CSceneRendererCommandManager::Load->Error al intentar leer el archivo: " + FileName; LOGGER->AddNewLog(ELL_ERROR, msg_error.c_str()); throw CException(__FILE__, __LINE__, msg_error); } m_FileName = FileName; // Obtenemos el nodo "scene_renderer_commands" CXMLTreeNode l_SceneRendererCommandManagerNode = parser["scene_renderer_commands"]; if (l_SceneRendererCommandManagerNode.Exists()) { // Obtenemos los datos para todos los scene renderer commands int l_count_objects = l_SceneRendererCommandManagerNode.GetNumChildren(); for (int i = 0; i < l_count_objects; ++i) { if (!l_SceneRendererCommandManagerNode(i).IsComment()) { CSceneRendererCommand* l_RendererSceneCommand = NULL; std::string l_CommandName = l_SceneRendererCommandManagerNode(i).GetName(); if (l_CommandName=="begin_scene") { l_RendererSceneCommand = new CBeginRenderSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="clear_scene") { l_RendererSceneCommand = new CClearSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="enable_z_write") { l_RendererSceneCommand = new CEnableZWriteSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="enable_z_test") { l_RendererSceneCommand = new CEnableZTestSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="disable_z_test") { l_RendererSceneCommand = new CDisableZTestSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="render_scene") { l_RendererSceneCommand = new CRenderSceneSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="disable_z_write") { l_RendererSceneCommand = new CDisableZWriteSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="end_scene") { l_RendererSceneCommand = new CEndRenderSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="present") { l_RendererSceneCommand = new CPresentSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="set_pool_renderable_objects_technique") { l_RendererSceneCommand = new CRenderableObjectTechniquesSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="setup_matrices") { l_RendererSceneCommand = new CSetupMatricesSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="set_render_target") { l_RendererSceneCommand = new CSetRenderTargetSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="unset_render_target") { std::string l_RenderTarget = l_SceneRendererCommandManagerNode(i).GetPszProperty("render_target",""); CSetRenderTargetSceneRendererCommand * l_SetRenderer=NULL; l_SetRenderer = (CSetRenderTargetSceneRendererCommand *)m_SceneRendererCommands.GetResource(l_RenderTarget); if (l_SetRenderer!=NULL) { l_RendererSceneCommand = new CUnsetRenderTargetSceneRendererCommand(l_SetRenderer, l_SceneRendererCommandManagerNode(i)); } } else if (l_CommandName=="generate_shadow_maps") { l_RendererSceneCommand = new CGenerateShadowMapsSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="blurH_shadow_maps") { l_RendererSceneCommand = new CBlurHShadowMapsSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="blurV_shadow_maps") { l_RendererSceneCommand = new CBlurVShadowMapsSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="capture_frame_buffer") { l_RendererSceneCommand = new CCaptureFrameBufferSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="render_draw_quad") { l_RendererSceneCommand = new CDrawQuadRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="render_deferred_shading") { l_RendererSceneCommand = new CDeferredShadingSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="set_scissor_rect") { l_RendererSceneCommand = new CScissorRectSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="unset_scissor_rect") { l_RendererSceneCommand = new CUnsetScissorRectSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="render_gui") { l_RendererSceneCommand = new CRenderGUISceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="render_particles") { l_RendererSceneCommand = new CRenderParticlesSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="render_mirrors") { l_RendererSceneCommand = new CRenderMirrorsSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } // DEBUG: else if (l_CommandName=="render_debug_scene") { l_RendererSceneCommand = new CRenderDebugSceneSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="render_debug_lights") { l_RendererSceneCommand = new CRenderDebugLightsSceneSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="render_debug_info") { l_RendererSceneCommand = new CRenderDebugInfoSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="render_debug_camera") { l_RendererSceneCommand = new CRenderDebugCameraSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } else if (l_CommandName=="render_debug_physX") { l_RendererSceneCommand = new CRenderDebugPhysXSceneRendererCommand(l_SceneRendererCommandManagerNode(i)); } if (l_RendererSceneCommand!=NULL) { std::string l_Name = l_SceneRendererCommandManagerNode(i).GetPszProperty("name",""); if (l_Name=="") l_Name = l_CommandName + "_" + GetNextName(); l_RendererSceneCommand->SetName(l_Name); m_SceneRendererCommands.AddResource(l_Name, l_RendererSceneCommand); } } } } }
void AssimpLoader::BuildGroup(IMeshSceneNode* meshSceneNode, const aiScene* scene, aiNode* nd, const Math::CMatrix4& matrixUpp) { // Load transformation struct aiMatrix4x4 m = nd->mTransformation; //aiTransposeMatrix4(&m); Math::CMatrix4 matrixLocalTrans = Math::CMatrix4(m.a1, m.a2, m.a3, m.a4, m.b1, m.b2, m.b3, m.b4, m.c1, m.c2, m.c3, m.c4, m.d1, m.d2, m.d3, m.d4); Math::CMatrix4 globalTransformation = matrixLocalTrans * matrixUpp; // draw all meshes assigned to this node for (unsigned int n = 0; n < nd->mNumMeshes; ++n) { /* * Construct the Object */ const struct aiMesh* mesh = scene->mMeshes[nd->mMeshes[n]]; if (mesh->mNumFaces == 0) { Logger::Log() << "[INFO] Skip assimp mesh. No faces. \n"; continue; } RenderableObject* assimpMesh = new RenderableObject; // Build the indice faces std::vector<unsigned int> indicesVector; std::vector<float> vertexVector; unsigned int maxIndice = 0; for (unsigned int t = 0; t < mesh->mNumFaces; ++t) { // Get a face elements const struct aiFace* face = &mesh->mFaces[t]; if (face->mNumIndices != 3) { Logger::Log() << "[Warning] More or less indices faces (" << face->mNumIndices << "). \n"; continue; } // Get all informations for (int i = 0; i < face->mNumIndices; i++) { int index = face->mIndices[i]; indicesVector.push_back(index); maxIndice = std::max(maxIndice, face->mIndices[i]); } } // Create the indice array unsigned int * indiceArray = new unsigned int[indicesVector.size()];for ( unsigned int i = 0; i < indicesVector.size(); i++) { indiceArray[i] = indicesVector[i]; } // Set all buffers // * Indice Buffer Logger::Log() << "[INFO] Add indice buffer : " << indicesVector.size() << "\n"; assimpMesh->SetIndiceBuffer(indiceArray, indicesVector.size()); // * Vertex buffer Logger::Log() << "[INFO] Add Vertex buffer ... \n"; RenderableObject::RenderableBuffer buffer; buffer.buffer = &mesh->mVertices[0].x; buffer.dimension = 3; buffer.size = maxIndice * 3 + 3; buffer.owner = false; Logger::Log() << " * size : " << buffer.size << "\n"; assimpMesh->AddBuffer(buffer, VERTEX_ATTRIBUT); // * Normal buffer if (mesh->HasNormals()) { buffer.buffer = &mesh->mNormals[0].x; assimpMesh->AddBuffer(buffer, NORMAL_ATTRIBUT); } // * Tangentes and bitangantes if (mesh->HasTangentsAndBitangents()) { buffer.buffer = &mesh->mTangents[0].x; assimpMesh->AddBuffer(buffer, TANGENT_ATTRIBUT); buffer.buffer = &mesh->mBitangents[0].x; assimpMesh->AddBuffer(buffer, BITANGENT_ATTRIBUT); } // * Couleurs if (mesh->GetNumColorChannels() > 0) //FIXME : Verfier le Loader ... { // TODO: Gestion des couleurs multiples if (mesh->GetNumColorChannels() > 1) { throw CException("Too Color Channels"); } else { buffer.size = maxIndice * 3 + 3; buffer.owner = true; buffer.dimension = 3; float * ColorArray = new float[maxIndice * 3 + 3];for ( int i = 0; i < maxIndice+1; i++) { ColorArray[i*3] = mesh->mColors[0][i].r; ColorArray[i*3+1] = mesh->mColors[0][i].g; ColorArray[i*3+2] = mesh->mColors[0][i].b; } buffer.buffer = ColorArray; assimpMesh->AddBuffer(buffer, COLOR_ATTRIBUT); } } // * UV Coords if (mesh->GetNumUVChannels() > 0) { // TODO: Gestion des materiaux multiples if (mesh->GetNumUVChannels() > 1) { throw CException("Too UV Channels"); } else { buffer.size = maxIndice * 2 + 2; buffer.owner = true; buffer.dimension = 2; float * UVArray = new float[maxIndice * 2 + 2];for ( int i = 0; i < maxIndice+1; i++) { UVArray[i*2] = mesh->mTextureCoords[0][i].x; UVArray[i*2+1] = mesh->mTextureCoords[0][i].y; } buffer.buffer = UVArray; assimpMesh->AddBuffer(buffer, TEXCOORD_ATTRIBUT); // Load diffuse image const struct aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex]; if (material->GetTextureCount(aiTextureType_DIFFUSE) > 0) { aiString AiPath; material->GetTexture(aiTextureType_DIFFUSE, 0, &AiPath); CFile texturePath = std::string(AiPath.data); Logger::Log() << "[INFO] Diffuse texture : " << texturePath.Filename() << "\n"; assimpMesh->AddTextureMap(DIFFUSE_TEXTURE, LoadTexture(texturePath)); } if (material->GetTextureCount(aiTextureType_SPECULAR) > 0) { aiString AiPath; material->GetTexture(aiTextureType_SPECULAR, 0, &AiPath); CFile texturePath = std::string(AiPath.data); Logger::Log() << "[INFO] Specular Texture : " << texturePath.Filename() << "\n"; assimpMesh->AddTextureMap(SPECULAR_TEXTURE, LoadTexture(texturePath)); } //TODO: Desactivation du bump mapping // if(material->GetTextureCount(aiTextureType_HEIGHT)>0) // { // aiString AiPath; // material->GetTexture(aiTextureType_HEIGHT, 0, &AiPath); // CFile texturePath = std::string(AiPath.data); // Logger::Log() << "[INFO] Normal texture : " << texturePath.Filename() << "\n"; // assimpMesh->AddTextureMap(NORMAL_TEXTURE, LoadTexture(texturePath)); // } } } // Chargement des materiaux GetMaterialPropreties(assimpMesh, scene->mMaterials[mesh->mMaterialIndex]); // Check if is an Instance bool foundInstance = false; //TODO: Reactivativate instance system // for(CachedAssimpMeshMap::iterator it = m_cached_geom.begin(); it != m_cached_geom.end(); it++) // { // if((*it)->IsInstance(*assimpMesh)) // { // (*it)->SetInstance(*assimpMesh); // foundInstance = true; // break; // } // } if (foundInstance) { Logger::Log() << "[INFO] Found an Instance ... \n"; Assert(false); } else { // Compile all buffers Logger::Log() << "[INFO] Compile all buffers ... \n"; assimpMesh->CompileBuffers(); Logger::Log() << "[INFO] Add cached resources : " << nd->mMeshes[n] << "\n"; m_cached_geom.push_back(assimpMesh); } // Attach to group Logger::Log() << "[INFO] Add to father node... \n"; meshSceneNode->AddRenderableObject(assimpMesh, globalTransformation); } // Add all childrens for (int n = 0; n < nd->mNumChildren; ++n) { BuildGroup(meshSceneNode, scene, nd->mChildren[n], globalTransformation); } }
//---------------------------------------------------------------------------- // Init data //---------------------------------------------------------------------------- bool CPhysicsManager::Init () { m_bIsOk = true; m_pMyAllocator = new CPhysicUserAllocator; assert(m_pMyAllocator); m_bIsOk = (m_pMyAllocator != NULL); if (m_bIsOk) { LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Inicializando la libreria PhysX"); // Initialize PhysicsSDK NxPhysicsSDKDesc desc; NxSDKCreateError errorCode = NXCE_NO_ERROR; m_pPhysicsSDK = NxCreatePhysicsSDK(NX_PHYSICS_SDK_VERSION, m_pMyAllocator, NULL, desc, &errorCode); /*Precompilation Directives*/ #if defined( _DEBUG ) #define USE_DEBUGGER #ifdef USE_DEBUGGER m_pPhysicsSDK->getFoundationSDK().getRemoteDebugger()->connect("127.0.0.1"); #endif #endif m_bIsOk = (m_pPhysicsSDK != NULL); if (m_bIsOk) { LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Creado el PhysXSDK"); LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: -------PhsX Settings---"); LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: El valor del SkinWidth es: %f", m_InitParams.m_fSkinWidth); //TODO por XML m_pPhysicsSDK->setParameter(NX_SKIN_WIDTH, m_InitParams.m_fSkinWidth); m_pPhysicsSDK->setParameter(NX_SKIN_WIDTH, 0.1f); //CODI PER PRINTAR INFO DELS JOINTS m_pPhysicsSDK->setParameter(NX_VISUALIZE_ACTOR_AXES, 1); m_pPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LIMITS, 1); m_pPhysicsSDK->setParameter(NX_VISUALIZE_JOINT_LOCAL_AXES, 1); m_pPhysicsSDK->setParameter(NX_CONTINUOUS_CD, 1); // Create a scene LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: El valor de la gravedad es: %f", m_InitParams.m_fGravity); NxSceneDesc sceneDesc; //TODO por XML sceneDesc.gravity = NxVec3(0.0f, m_InitParams.m_fGravity, 0.0f); sceneDesc.gravity = NxVec3(0.0f, -9.8f, 0.0f); m_pScene = m_pPhysicsSDK->createScene(sceneDesc); m_bIsOk = (m_pScene != NULL); if (m_bIsOk) { LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Solo hay un material, con los siguientes params"); LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: DefaultMaterial->Restitution %f:", m_InitParams.m_Restitution_DefMat); LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: DefaultMaterial->StaticFriction %f:", m_InitParams.m_StaticFriction_DefMat); LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: DefaultMaterial->DynamicFriction %f:", m_InitParams.m_DynamicFriction_DefMat); LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: ----END PhsX Settings---"); // Set default material NxMaterial* defaultMaterial = m_pScene->getMaterialFromIndex(0); defaultMaterial->setRestitution(m_InitParams.m_Restitution_DefMat); defaultMaterial->setStaticFriction(m_InitParams.m_StaticFriction_DefMat); defaultMaterial->setDynamicFriction(m_InitParams.m_DynamicFriction_DefMat); //Collision Flags //m_pScene->setGroupCollisionFlag(ECG_ARMA,ECG_ESCENARI,true); //Create a controllerManager m_pControllerManager = NxCreateControllerManager(m_pMyAllocator); m_bIsOk = (m_pControllerManager != NULL); if (m_bIsOk) { LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Creado el controlador de caracteres"); m_pCookingMesh = new CPhysicCookingMesh(); assert(m_pCookingMesh); m_bIsOk = m_pCookingMesh->Init(m_pPhysicsSDK, m_pMyAllocator); if (m_bIsOk) { LOGGER->AddNewLog(ELL_INFORMATION, "PhysicsManager:: Creado el CookingMesh"); } } //m_bIsOk m_pControllerManager?*/ }//isOk m_pScene? }//isOk m_pPhysicsSDK ? }//isOk m_pMyAllocator ? if (!m_bIsOk) { std::string msg_error = "PhysicsManager::Init-> Error en la inicializacion de PhysX"; LOGGER->AddNewLog(ELL_ERROR, msg_error.c_str()); Release(); throw CException(__FILE__, __LINE__, msg_error); } return m_bIsOk; }
bool ParseElement (ParserCtx *pCtx, CXMLElement **retpElement) // ParseElement // // Parses an element and returns it. We assume that we've already // parsed an open tag { CXMLElement *pElement; ASSERT(pCtx->iToken == tkTagOpen); // Parse the tag name if (ParseToken(pCtx) != tkText) { pCtx->sError = ERR_ELEMENT_TAG_EXPECTED; return false; } // Create a new element with the tag pElement = new CXMLElement(pCtx->sToken, pCtx->pElement); if (pElement == NULL) throw CException(errOutOfMemory); // Keep parsing until the tag is done ParseToken(pCtx); while (pCtx->iToken != tkTagClose && pCtx->iToken != tkSimpleTagClose) { // If we've got an identifier then this must be an attribute if (pCtx->iToken == tkText) { CString sAttribute = pCtx->sToken; CString sValue; // Expect an equals sign if (ParseToken(pCtx) != tkEquals) { pCtx->sError = ERR_EQUAL_EXPECTED; delete pElement; return false; } // Expect a quote ParseToken(pCtx); if (pCtx->iToken != tkQuote && pCtx->iToken != tkSingleQuote) { pCtx->sError = ERR_ATTRIB_NEEDS_QUOTES; delete pElement; return false; } // Remember what kind of qoute we used so that we can match it // (and so we ignore the other kind inside it). pCtx->iAttribQuote = pCtx->iToken; // Expect the value ParseToken(pCtx, AttributeState); if (pCtx->iToken == tkText) { sValue = pCtx->sToken; ParseToken(pCtx); } else sValue = NULL_STR; // Now expect an end-quote if (pCtx->iToken != pCtx->iAttribQuote) { if (pCtx->iToken != tkError || pCtx->sError.IsEmpty()) pCtx->sError = ERR_MISMATCHED_ATTRIB_QUOTE; delete pElement; return false; } // Add the attribute to the element pElement->AddAttribute(sAttribute, sValue); // Parse the next token ParseToken(pCtx); } // Otherwise this is an error else { if (pCtx->iToken != tkError || pCtx->sError.IsEmpty()) pCtx->sError = ERR_ATTRIB_EXPECTED; delete pElement; return false; } } // Give our controller a chance to deal with an element // (We use this in Transcendence to parse the <Library> element, which // contains external entities). // // NOTE: We only worry about top-level elements (i.e., elements immediately // under the root). if (pCtx->m_pController && pCtx->pElement && pCtx->pElement->GetParentElement() == NULL) { if (!pCtx->m_pController->OnOpenTag(pElement, &pCtx->sError)) { delete pElement; return false; } } // If we don't have an empty element then keep parsing until // we find a close tag if (!pCtx->m_bParseRootElement && pCtx->iToken == tkTagClose) { CXMLElement *pParentElement; // We are recursing pParentElement = pCtx->pElement; pCtx->pElement = pElement; // Parse until we've got the begin close tag while (ParseToken(pCtx, ContentState) != tkEndTagOpen) { // If this is text then append it as content if (pCtx->iToken == tkText) pElement->AppendContent(pCtx->sToken); // Otherwise, append an element else if (pCtx->iToken == tkTagOpen) { CXMLElement *pSubElement; if (!ParseElement(pCtx, &pSubElement)) { pCtx->pElement = pParentElement; delete pElement; return false; } pElement->AppendSubElement(pSubElement); } // Otherwise we're in trouble else { pCtx->pElement = pParentElement; if (pCtx->iToken != tkError || pCtx->sError.IsEmpty()) pCtx->sError = ERR_CONTENT_EXPECTED; delete pElement; return false; } } // Done pCtx->pElement = pParentElement; // The element tag should match ours if (ParseToken(pCtx) != tkText || strEqualsNoCase(pCtx->sToken, pElement->GetTag())) { pCtx->sError = ERR_UNMATCHED_CLOSE_TAG; delete pElement; return false; } // Parse the end tag if (ParseToken(pCtx) != tkTagClose) { pCtx->sError = ERR_CLOSE_TAG_EXPECTED; delete pElement; return false; } } // Done *retpElement = pElement; return true; }
void ShadersLoader::LoadShaderAttributs(Shader* shader, TiXmlElement *root) { TiXmlElement *rootAttributs = root->FirstChildElement("Attributs"); if (!rootAttributs) { Logger::Log() << "[INFO] No Attribut is available ... \n"; return; } TiXmlElement *attributNode = rootAttributs->FirstChildElement("Attribut"); Logger::Log() << "[INFO] Attribut : \n"; while (attributNode) { std::string nameAttrib; std::string typeAttrib; TinyXMLGetAttributeValue<std::string>(attributNode, "name", &nameAttrib); TinyXMLGetAttributeValue<std::string>(attributNode, "type", &typeAttrib); int typeID; //TODO: Faire une factory ??? if (typeAttrib == "Vertex") { Logger::Log() << " * Attribut : " << nameAttrib << " (Vertex) \n"; typeID = VERTEX_ATTRIBUT; } else if (typeAttrib == "Color") { Logger::Log() << " * Attribut : " << nameAttrib << " (Color) \n"; typeID = COLOR_ATTRIBUT; } else if (typeAttrib == "TexCoord") { Logger::Log() << " * Attribut : " << nameAttrib << " (TexCoord) \n"; typeID = TEXCOORD_ATTRIBUT; } else if (typeAttrib == "Tangent") { Logger::Log() << " * Attribut : " << nameAttrib << " (Tangent) \n"; typeID = TANGENT_ATTRIBUT; } else if (typeAttrib == "BiTangent") { Logger::Log() << " * Attribut : " << nameAttrib << " (BiTangent) \n"; typeID = BITANGENT_ATTRIBUT; } else if (typeAttrib == "Normal") { Logger::Log() << " * Attribut : " << nameAttrib << " (Normal) \n"; typeID = NORMAL_ATTRIBUT; } else if(typeAttrib == "Custom") { // TODO: Add Limit number & do verifications int idNum; TinyXMLGetAttributeValue<int>(attributNode, "id",&idNum); Logger::Log() << " * Attribut : " << nameAttrib << " (Custom " << idNum << ") \n"; typeID = CUSTOM_ATTRIBUT + idNum; } else { throw CException("Unknow attribut : " + typeAttrib); } shader->AddAttributBinding(typeID, nameAttrib); attributNode = attributNode->NextSiblingElement("Attribut"); } }
void CTranscendenceWnd::ReportCrash (void) // ReportCrash // // Report a crash { #ifdef DEBUG_PROGRAMSTATE m_sCrashInfo = NULL_STR; // Program state switch (g_iProgramState) { case psAnimating: m_sCrashInfo.Append(CONSTLIT("program state: miscellaneous animation\r\n")); break; case psPaintingSRS: m_sCrashInfo.Append(CONSTLIT("program state: painting SRS\r\n")); ReportCrashObj(&m_sCrashInfo); break; case psUpdating: m_sCrashInfo.Append(CONSTLIT("program state: updating universe\r\n")); break; case psUpdatingEvents: m_sCrashInfo.Append(CONSTLIT("program state: updating events\r\n")); ReportCrashEvent(&m_sCrashInfo); break; case psUpdatingBehavior: m_sCrashInfo.Append(CONSTLIT("program state: updating object behavior\r\n")); ReportCrashObj(&m_sCrashInfo); break; case psUpdatingObj: m_sCrashInfo.Append(CONSTLIT("program state: updating object\r\n")); ReportCrashObj(&m_sCrashInfo); break; case psUpdatingHitTest: m_sCrashInfo.Append(CONSTLIT("program state: updating object hit test\r\n")); ReportCrashObj(&m_sCrashInfo); break; case psUpdatingMove: m_sCrashInfo.Append(CONSTLIT("program state: updating object motion\r\n")); ReportCrashObj(&m_sCrashInfo); break; case psUpdatingEncounters: m_sCrashInfo.Append(CONSTLIT("program state: updating random encounters\r\n")); break; case psDestroyNotify: m_sCrashInfo.Append(CONSTLIT("program state: handling OnObjDestroy\r\n")); ReportCrashObj(&m_sCrashInfo); break; case psUpdatingReactorDisplay: m_sCrashInfo.Append(CONSTLIT("program state: updating reactor display\r\n")); break; case psPaintingMap: m_sCrashInfo.Append(CONSTLIT("program state: painting map\r\n")); break; case psPaintingLRS: m_sCrashInfo.Append(CONSTLIT("program state: painting LRS\r\n")); break; case psPaintingArmorDisplay: m_sCrashInfo.Append(CONSTLIT("program state: painting armor display\r\n")); break; case psPaintingMessageDisplay: m_sCrashInfo.Append(CONSTLIT("program state: painting message display\r\n")); break; case psPaintingReactorDisplay: m_sCrashInfo.Append(CONSTLIT("program state: painting reactor display\r\n")); break; case psPaintingTargetDisplay: m_sCrashInfo.Append(CONSTLIT("program state: painting target display\r\n")); ReportCrashObj(&m_sCrashInfo, (GetPlayer() ? GetPlayer()->GetShip() : NULL)); break; case psPaintingDeviceDisplay: m_sCrashInfo.Append(CONSTLIT("program state: painting device display\r\n")); break; case psStargateEnter: m_sCrashInfo.Append(CONSTLIT("program state: entering stargate\r\n")); break; case psStargateEndGame: m_sCrashInfo.Append(CONSTLIT("program state: entering end-game stargate\r\n")); break; case psStargateLoadingSystem: m_sCrashInfo.Append(CONSTLIT("program state: enter stargate, loading destination system\r\n")); break; case psStargateCreatingSystem: m_sCrashInfo.Append(CONSTLIT("program state: enter stargate, creating destination system\r\n")); break; case psStargateUpdateExtended: m_sCrashInfo.Append(CONSTLIT("program state: enter stargate, updating extended\r\n")); break; case psStargateTransferringGateFollowers: m_sCrashInfo.Append(CONSTLIT("program state: enter stargate, transferring gate followers\r\n")); break; case psStargateSavingSystem: m_sCrashInfo.Append(CONSTLIT("program state: enter stargate, saving current system\r\n")); break; case psStargateFlushingSystem: m_sCrashInfo.Append(CONSTLIT("program state: enter stargate, flushing current system\r\n")); break; case psStargateGarbageCollecting: m_sCrashInfo.Append(CONSTLIT("program state: enter stargate, garbage-collecting images\r\n")); break; case psStargateLoadingBitmaps: m_sCrashInfo.Append(CONSTLIT("program state: enter stargate, loading new images\r\n")); break; case psLoadingImages: m_sCrashInfo.Append(CONSTLIT("program state: in LoadImages\r\n")); ReportCrashObj(&m_sCrashInfo); break; case psStargateEnterDone: m_sCrashInfo.Append(CONSTLIT("program state: enter stargate done\r\n")); break; case psOnObjDestroyed: m_sCrashInfo.Append(CONSTLIT("program state: in OnObjDestroyed\r\n")); ReportCrashObj(&m_sCrashInfo); break; case psCustomError: if (g_sProgramError) m_sCrashInfo.Append(*g_sProgramError); m_sCrashInfo.Append(CONSTLIT("\r\n")); break; default: m_sCrashInfo.Append(CONSTLIT("program state: unknown\r\n")); } // Game state switch (m_State) { case gsInGame: m_sCrashInfo.Append(CONSTLIT("game state: in game\r\n")); break; case gsDocked: m_sCrashInfo.Append(CONSTLIT("game state: docked\r\n")); break; case gsDestroyed: m_sCrashInfo.Append(CONSTLIT("game state: destroyed\r\n")); break; case gsEnteringStargate: m_sCrashInfo.Append(CONSTLIT("game state: entering stargate\r\n")); break; case gsLeavingStargate: m_sCrashInfo.Append(CONSTLIT("game state: leaving stargate\r\n")); break; case gsIntro: m_sCrashInfo.Append(CONSTLIT("game state: intro\r\n")); break; default: m_sCrashInfo.Append(CONSTLIT("game state: unknown\r\n")); } #endif throw CException(ERR_FAIL); }
bool CBratSettings::LoadConfigSelectionCriteria() { QStringList keys = mSettings.childGroups(); if ( keys.empty() ) return true; qDebug() << keys; try { CMapProduct& mapProductInstance = CMapProduct::GetInstance(); mapProductInstance.AddCriteriaToProducts(); for ( CObMap::iterator it = mapProductInstance.begin(); it != mapProductInstance.end(); it++ ) { CProduct* product = dynamic_cast<CProduct*>( it->second ); if ( product == nullptr || !product->HasCriteriaInfo() ) continue; std::string config_path = BuildComposedKey( { GROUP_SEL_CRITERIA, product->GetLabel() } ); { CSection section( mSettings, config_path ); QStringList keys = mSettings.childKeys(); if ( keys.empty() ) continue; std::string val; if ( product->HasLatLonCriteria() ) { val = ReadValue( section, ENTRY_LAT_LON ); if ( !val.empty() ) product->GetLatLonCriteria()->Set( val ); } if ( product->HasDatetimeCriteria() ) { val = ReadValue( section, ENTRY_DATETIME ); if ( !val.empty() ) product->GetDatetimeCriteria()->SetFromText( val ); } if ( product->HasCycleCriteria() ) { val = ReadValue( section, ENTRY_CYCLE ); if ( !val.empty() ) product->GetCycleCriteria()->SetFromText( val ); } if ( product->HasPassIntCriteria() ) { val = ReadValue( section, ENTRY_PASS_NUMBER ); if ( !val.empty() ) product->GetPassIntCriteria()->SetFromText( val ); } if ( product->HasPassStringCriteria() ) { val = ReadValue( section, ENTRY_PASS_STRING ); if ( !val.empty() ) product->GetPassStringCriteria()->Set( val ); } } } } catch ( const CException &e ) { std::string msg( "An error occurred while loading criteria selection configuration (CBratGuiApp::LoadConfigSelectionCriteria)\nNative exception: " ); msg += e.what(); throw CException( msg, e.error() ); } return mSettings.status() == QSettings::NoError; }