text
stringlengths
54
60.6k
<commit_before>/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** rtspconnectionclient.cpp ** ** Interface to an RTSP client connection ** ** -------------------------------------------------------------------------*/ #include "logger.h" #include "rtspconnectionclient.h" RTSPConnection::SessionSink::SessionSink(UsageEnvironment& env, Callback* callback) : MediaSink(env) , m_buffer(NULL) , m_bufferSize(0) , m_callback(callback) , m_markerSize(0) { allocate(1024*1024); } RTSPConnection::SessionSink::~SessionSink() { delete [] m_buffer; } void RTSPConnection::SessionSink::allocate(ssize_t bufferSize) { m_bufferSize = bufferSize; m_buffer = new u_int8_t[m_bufferSize]; if (m_callback) { m_markerSize = m_callback->onNewBuffer(m_buffer, m_bufferSize); LOG(NOTICE) << "markerSize:" << m_markerSize; } } void RTSPConnection::SessionSink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds) { LOG(DEBUG) << "NOTIFY size:" << frameSize; if (numTruncatedBytes != 0) { delete [] m_buffer; LOG(NOTICE) << "buffer too small " << m_bufferSize << " allocate bigger one\n"; allocate(m_bufferSize*2); } else if (m_callback) { if (!m_callback->onData(this->name(), m_buffer, frameSize+m_markerSize)) { LOG(WARN) << "NOTIFY failed"; } } this->continuePlaying(); } Boolean RTSPConnection::SessionSink::continuePlaying() { Boolean ret = False; if (source() != NULL) { source()->getNextFrame(m_buffer+m_markerSize, m_bufferSize-m_markerSize, afterGettingFrame, this, onSourceClosure, this); ret = True; } return ret; } RTSPConnection::RTSPConnection(Environment& env, Callback* callback, const char* rtspURL, int timeout, int verbosityLevel) : RTSPClient(env, rtspURL, verbosityLevel, NULL, 0 #if LIVEMEDIA_LIBRARY_VERSION_INT > 1371168000 ,-1 #endif ) , m_timeout(timeout) , m_session(NULL) , m_subSessionIter(NULL) , m_callback(callback) , m_env(env) { // start tasks m_connectionTask = env.taskScheduler().scheduleDelayedTask(timeout*1000000, TaskConnectionTimeout, this); m_dataTask = env.taskScheduler().scheduleDelayedTask(timeout*1000000, TaskDataArrivalTimeout, this); // initiate connection process this->sendNextCommand(); } RTSPConnection::~RTSPConnection() { delete m_subSessionIter; Medium::close(m_session); } void RTSPConnection::sendNextCommand() { if (m_subSessionIter == NULL) { // no SDP, send DESCRIBE this->sendDescribeCommand(continueAfterDESCRIBE); } else { m_subSession = m_subSessionIter->next(); if (m_subSession != NULL) { // still subsession to SETUP if (!m_subSession->initiate()) { LOG(WARN) << "Failed to initiate " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession: " << envir().getResultMsg(); this->sendNextCommand(); } else { LOG(NOTICE) << "Initiated " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession"; } this->sendSetupCommand(*m_subSession, continueAfterSETUP); } else { // no more subsession to SETUP, send PLAY this->sendPlayCommand(*m_session, continueAfterPLAY); } } } void RTSPConnection::continueAfterDESCRIBE(int resultCode, char* resultString) { if (resultCode != 0) { LOG(WARN) << "Failed to DESCRIBE: " << resultString; m_env.stop(); } else { LOG(NOTICE) << "Got SDP:\n" << resultString; m_session = MediaSession::createNew(envir(), resultString); m_subSessionIter = new MediaSubsessionIterator(*m_session); this->sendNextCommand(); } delete[] resultString; } void RTSPConnection::continueAfterSETUP(int resultCode, char* resultString) { if (resultCode != 0) { LOG(WARN) << "Failed to SETUP: " << resultString; m_env.stop(); } else { m_subSession->sink = SessionSink::createNew(envir(), m_callback); if (m_subSession->sink == NULL) { LOG(WARN) << "Failed to create a data sink for " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession: " << envir().getResultMsg() << "\n"; } else if (m_callback->onNewSession(m_subSession->sink->name(), m_subSession->mediumName(), m_subSession->codecName(), m_subSession->savedSDPLines())) { LOG(WARN) << "Created a data sink for the \"" << m_subSession->mediumName() << "/" << m_subSession->codecName() << "\" subsession"; m_subSession->sink->startPlaying(*(m_subSession->readSource()), NULL, NULL); } } delete[] resultString; this->sendNextCommand(); } void RTSPConnection::continueAfterPLAY(int resultCode, char* resultString) { if (resultCode != 0) { LOG(WARN) << "Failed to PLAY: " << resultString; m_env.stop(); } else { LOG(NOTICE) << "PLAY OK"; envir().taskScheduler().unscheduleDelayedTask(m_connectionTask); } delete[] resultString; } void RTSPConnection::TaskConnectionTimeout() { std::cout << "timeout" << std::endl; m_env.stop(); } void RTSPConnection::TaskDataArrivalTimeout() { unsigned int newTotNumPacketsReceived = 0; MediaSubsessionIterator iter(*m_session); MediaSubsession* subsession; while ((subsession = iter.next()) != NULL) { RTPSource* src = subsession->rtpSource(); if (src != NULL) { newTotNumPacketsReceived += src->receptionStatsDB().totNumPacketsReceived(); } } if (newTotNumPacketsReceived == m_nbPacket) { std::cout << "no more data" << std::endl; m_env.stop(); } else { m_nbPacket = newTotNumPacketsReceived; m_dataTask = envir().taskScheduler().scheduleDelayedTask(m_timeout*1000000, TaskDataArrivalTimeout, this); } } <commit_msg>initialize m_packet<commit_after>/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** rtspconnectionclient.cpp ** ** Interface to an RTSP client connection ** ** -------------------------------------------------------------------------*/ #include "logger.h" #include "rtspconnectionclient.h" RTSPConnection::SessionSink::SessionSink(UsageEnvironment& env, Callback* callback) : MediaSink(env) , m_buffer(NULL) , m_bufferSize(0) , m_callback(callback) , m_markerSize(0) { allocate(1024*1024); } RTSPConnection::SessionSink::~SessionSink() { delete [] m_buffer; } void RTSPConnection::SessionSink::allocate(ssize_t bufferSize) { m_bufferSize = bufferSize; m_buffer = new u_int8_t[m_bufferSize]; if (m_callback) { m_markerSize = m_callback->onNewBuffer(m_buffer, m_bufferSize); LOG(NOTICE) << "markerSize:" << m_markerSize; } } void RTSPConnection::SessionSink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds) { LOG(DEBUG) << "NOTIFY size:" << frameSize; if (numTruncatedBytes != 0) { delete [] m_buffer; LOG(NOTICE) << "buffer too small " << m_bufferSize << " allocate bigger one\n"; allocate(m_bufferSize*2); } else if (m_callback) { if (!m_callback->onData(this->name(), m_buffer, frameSize+m_markerSize)) { LOG(WARN) << "NOTIFY failed"; } } this->continuePlaying(); } Boolean RTSPConnection::SessionSink::continuePlaying() { Boolean ret = False; if (source() != NULL) { source()->getNextFrame(m_buffer+m_markerSize, m_bufferSize-m_markerSize, afterGettingFrame, this, onSourceClosure, this); ret = True; } return ret; } RTSPConnection::RTSPConnection(Environment& env, Callback* callback, const char* rtspURL, int timeout, int verbosityLevel) : RTSPClient(env, rtspURL, verbosityLevel, NULL, 0 #if LIVEMEDIA_LIBRARY_VERSION_INT > 1371168000 ,-1 #endif ) , m_timeout(timeout) , m_session(NULL) , m_subSessionIter(NULL) , m_callback(callback) , m_env(env) , m_nbPacket(0) { // start tasks m_connectionTask = env.taskScheduler().scheduleDelayedTask(timeout*1000000, TaskConnectionTimeout, this); m_dataTask = env.taskScheduler().scheduleDelayedTask(timeout*1000000, TaskDataArrivalTimeout, this); // initiate connection process this->sendNextCommand(); } RTSPConnection::~RTSPConnection() { delete m_subSessionIter; Medium::close(m_session); } void RTSPConnection::sendNextCommand() { if (m_subSessionIter == NULL) { // no SDP, send DESCRIBE this->sendDescribeCommand(continueAfterDESCRIBE); } else { m_subSession = m_subSessionIter->next(); if (m_subSession != NULL) { // still subsession to SETUP if (!m_subSession->initiate()) { LOG(WARN) << "Failed to initiate " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession: " << envir().getResultMsg(); this->sendNextCommand(); } else { LOG(NOTICE) << "Initiated " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession"; } this->sendSetupCommand(*m_subSession, continueAfterSETUP); } else { // no more subsession to SETUP, send PLAY this->sendPlayCommand(*m_session, continueAfterPLAY); } } } void RTSPConnection::continueAfterDESCRIBE(int resultCode, char* resultString) { if (resultCode != 0) { LOG(WARN) << "Failed to DESCRIBE: " << resultString; m_env.stop(); } else { LOG(NOTICE) << "Got SDP:\n" << resultString; m_session = MediaSession::createNew(envir(), resultString); m_subSessionIter = new MediaSubsessionIterator(*m_session); this->sendNextCommand(); } delete[] resultString; } void RTSPConnection::continueAfterSETUP(int resultCode, char* resultString) { if (resultCode != 0) { LOG(WARN) << "Failed to SETUP: " << resultString; m_env.stop(); } else { m_subSession->sink = SessionSink::createNew(envir(), m_callback); if (m_subSession->sink == NULL) { LOG(WARN) << "Failed to create a data sink for " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession: " << envir().getResultMsg() << "\n"; } else if (m_callback->onNewSession(m_subSession->sink->name(), m_subSession->mediumName(), m_subSession->codecName(), m_subSession->savedSDPLines())) { LOG(WARN) << "Created a data sink for the \"" << m_subSession->mediumName() << "/" << m_subSession->codecName() << "\" subsession"; m_subSession->sink->startPlaying(*(m_subSession->readSource()), NULL, NULL); } } delete[] resultString; this->sendNextCommand(); } void RTSPConnection::continueAfterPLAY(int resultCode, char* resultString) { if (resultCode != 0) { LOG(WARN) << "Failed to PLAY: " << resultString; m_env.stop(); } else { LOG(NOTICE) << "PLAY OK"; envir().taskScheduler().unscheduleDelayedTask(m_connectionTask); } delete[] resultString; } void RTSPConnection::TaskConnectionTimeout() { std::cout << "timeout" << std::endl; m_env.stop(); } void RTSPConnection::TaskDataArrivalTimeout() { unsigned int newTotNumPacketsReceived = 0; MediaSubsessionIterator iter(*m_session); MediaSubsession* subsession; while ((subsession = iter.next()) != NULL) { RTPSource* src = subsession->rtpSource(); if (src != NULL) { newTotNumPacketsReceived += src->receptionStatsDB().totNumPacketsReceived(); } } if (newTotNumPacketsReceived == m_nbPacket) { std::cout << "no more data" << std::endl; m_env.stop(); } else { m_nbPacket = newTotNumPacketsReceived; m_dataTask = envir().taskScheduler().scheduleDelayedTask(m_timeout*1000000, TaskDataArrivalTimeout, this); } } <|endoftext|>
<commit_before>/* * FUNCTION: * Postgres driver -- * * Threading: * ---------- * This class is thread-enabled but not thread-safe. Two threads should * not try to use one instance of this class at the same time. Each * thread should construct it's own instance of this class. This class * uses no globals. * * HISTORY: * Copyright (c) 2017 Linas Vepstas * * LICENSE: * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_PGSQL_STORAGE #include <libpq-fe.h> #include <opencog/util/exceptions.h> #include <opencog/util/Logger.h> #include <opencog/util/platform.h> #include "ll-pg-cxx.h" #define PERR(...) \ throw opencog::RuntimeException(TRACE_INFO, __VA_ARGS__); /* =========================================================== */ LLPGConnection::LLPGConnection(const char * uri) { is_connected = false; _pgconn = PQconnectdb(uri); if (PQstatus(_pgconn) != CONNECTION_OK) { std::string msg = PQerrorMessage(_pgconn); PQfinish(_pgconn); PERR("Cannot connect to database: %s", msg.c_str()); } is_connected = true; } /* =========================================================== */ LLPGConnection::~LLPGConnection() { PQfinish(_pgconn); } /* =========================================================== */ #define DEFAULT_NUM_COLS 20 LLPGRecordSet * LLPGConnection::get_record_set(void) { LLPGRecordSet *rs; if (!free_pool.empty()) { LLRecordSet* llrs = free_pool.top(); rs = dynamic_cast<LLPGRecordSet*>(llrs); free_pool.pop(); rs->ncols = -1; } else { rs = new LLPGRecordSet(this); } rs->setup_cols(DEFAULT_NUM_COLS); return rs; } /* =========================================================== */ LLRecordSet * LLPGConnection::exec(const char * buff, bool trial_run) { if (!is_connected) return NULL; LLPGRecordSet* rs = get_record_set(); rs->_result = PQexec(_pgconn, buff); ExecStatusType rest = PQresultStatus(rs->_result); if (rest != PGRES_COMMAND_OK and rest != PGRES_EMPTY_QUERY and rest != PGRES_TUPLES_OK) { // Don't log trial-run failures. Just throw. if (not (trial_run and PGRES_FATAL_ERROR == rest)) { opencog::logger().warn("PQresult message: %s", PQresultErrorMessage(rs->_result)); opencog::logger().warn("PQ query was: %s", buff); } rs->release(); PERR("Failed to execute!"); } /* Use numbr of columns to indicate that the query hasn't * given results yet. */ rs->ncols = -1; return rs; } /* =========================================================== */ void LLPGRecordSet::setup_cols(int new_ncols) { if (new_ncols <= arrsize) return; if (column_labels) delete[] column_labels; column_labels = new char*[new_ncols]; memset(column_labels, 0, new_ncols * sizeof(char*)); if (values) delete[] values; values = new char*[new_ncols]; memset(values, 0, new_ncols * sizeof(char*)); arrsize = new_ncols; } /* =========================================================== */ /* pseudo-private routine */ LLPGRecordSet::LLPGRecordSet(LLPGConnection* _conn) : LLRecordSet(_conn) { _result = nullptr; _nrows = -1; _curr_row = -1; } /* =========================================================== */ void LLPGRecordSet::release(void) { PQclear(_result); _result = nullptr; _nrows = -1; _curr_row = -1; ncols = -1; memset(column_labels, 0, arrsize * sizeof(char*)); memset(values, 0, arrsize * sizeof(char*)); LLRecordSet::release(); } /* =========================================================== */ LLPGRecordSet::~LLPGRecordSet() { } /* =========================================================== */ #define DEFAULT_COLUMN_NAME_SIZE 121 void LLPGRecordSet::get_column_labels(void) { if (0 <= ncols) return; /* If number of columns is negative, then we haven't * gotten any results back yet. Start by getting the * column labels. */ ncols = PQnfields(_result); for (int i=0; i<ncols; i++) { column_labels[i] = PQfname(_result, i); } } /* =========================================================== */ #define DEFAULT_VARCHAR_SIZE 4040 bool LLPGRecordSet::fetch_row(void) { if (_nrows < 0) { _curr_row = 0; _nrows = PQntuples(_result); } if (_nrows <= _curr_row or _curr_row < 0) return false; if (ncols < 0) get_column_labels(); for (int i=0; i< ncols; i++) { values[i] = PQgetvalue(_result, _curr_row, i); } _curr_row++; return true; } #endif /* HAVE_PGSQL_STORAGE */ /* ============================= END OF FILE ================= */ <commit_msg>Fix previous commit<commit_after>/* * FUNCTION: * Postgres driver -- * * Threading: * ---------- * This class is thread-enabled but not thread-safe. Two threads should * not try to use one instance of this class at the same time. Each * thread should construct it's own instance of this class. This class * uses no globals. * * HISTORY: * Copyright (c) 2017 Linas Vepstas * * LICENSE: * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_PGSQL_STORAGE #include <libpq-fe.h> #include <opencog/util/exceptions.h> #include <opencog/util/Logger.h> #include <opencog/util/platform.h> #include "ll-pg-cxx.h" #define PERR(...) \ throw opencog::RuntimeException(TRACE_INFO, __VA_ARGS__); /* =========================================================== */ LLPGConnection::LLPGConnection(const char * uri) { is_connected = false; _pgconn = PQconnectdb(uri); if (PQstatus(_pgconn) != CONNECTION_OK) { std::string msg = PQerrorMessage(_pgconn); PQfinish(_pgconn); PERR("Cannot connect to database: %s", msg.c_str()); } is_connected = true; } /* =========================================================== */ LLPGConnection::~LLPGConnection() { PQfinish(_pgconn); } /* =========================================================== */ #define DEFAULT_NUM_COLS 20 LLPGRecordSet * LLPGConnection::get_record_set(void) { LLPGRecordSet *rs; if (!free_pool.empty()) { LLRecordSet* llrs = free_pool.top(); rs = dynamic_cast<LLPGRecordSet*>(llrs); free_pool.pop(); rs->ncols = -1; } else { rs = new LLPGRecordSet(this); } rs->setup_cols(DEFAULT_NUM_COLS); return rs; } /* =========================================================== */ LLRecordSet * LLPGConnection::exec(const char * buff, bool trial_run) { if (!is_connected) return NULL; LLPGRecordSet* rs = get_record_set(); rs->_result = PQexec(_pgconn, buff); ExecStatusType rest = PQresultStatus(rs->_result); if (rest != PGRES_COMMAND_OK and rest != PGRES_EMPTY_QUERY and rest != PGRES_TUPLES_OK) { // Don't log trial-run failures. Just throw. if (trial_run and PGRES_FATAL_ERROR == rest) { rs->release(); throw opencog::SilentException(); } opencog::logger().warn("PQresult message: %s", PQresultErrorMessage(rs->_result)); opencog::logger().warn("PQ query was: %s", buff); rs->release(); PERR("Failed to execute!"); } /* Use numbr of columns to indicate that the query hasn't * given results yet. */ rs->ncols = -1; return rs; } /* =========================================================== */ void LLPGRecordSet::setup_cols(int new_ncols) { if (new_ncols <= arrsize) return; if (column_labels) delete[] column_labels; column_labels = new char*[new_ncols]; memset(column_labels, 0, new_ncols * sizeof(char*)); if (values) delete[] values; values = new char*[new_ncols]; memset(values, 0, new_ncols * sizeof(char*)); arrsize = new_ncols; } /* =========================================================== */ /* pseudo-private routine */ LLPGRecordSet::LLPGRecordSet(LLPGConnection* _conn) : LLRecordSet(_conn) { _result = nullptr; _nrows = -1; _curr_row = -1; } /* =========================================================== */ void LLPGRecordSet::release(void) { PQclear(_result); _result = nullptr; _nrows = -1; _curr_row = -1; ncols = -1; memset(column_labels, 0, arrsize * sizeof(char*)); memset(values, 0, arrsize * sizeof(char*)); LLRecordSet::release(); } /* =========================================================== */ LLPGRecordSet::~LLPGRecordSet() { } /* =========================================================== */ #define DEFAULT_COLUMN_NAME_SIZE 121 void LLPGRecordSet::get_column_labels(void) { if (0 <= ncols) return; /* If number of columns is negative, then we haven't * gotten any results back yet. Start by getting the * column labels. */ ncols = PQnfields(_result); for (int i=0; i<ncols; i++) { column_labels[i] = PQfname(_result, i); } } /* =========================================================== */ #define DEFAULT_VARCHAR_SIZE 4040 bool LLPGRecordSet::fetch_row(void) { if (_nrows < 0) { _curr_row = 0; _nrows = PQntuples(_result); } if (_nrows <= _curr_row or _curr_row < 0) return false; if (ncols < 0) get_column_labels(); for (int i=0; i< ncols; i++) { values[i] = PQgetvalue(_result, _curr_row, i); } _curr_row++; return true; } #endif /* HAVE_PGSQL_STORAGE */ /* ============================= END OF FILE ================= */ <|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "../general/forall.hpp" #include "bilininteg.hpp" #include "../linalg/elementmatrix.hpp" namespace mfem { void TransposeIntegrator::AssembleEA(const FiniteElementSpace &fes, Vector &ea_data) { Vector ea_data_tmp(ea_data.Size()); ea_data_tmp = 0.0; bfi->AssembleEA(fes, ea_data_tmp); const int ne = fes.GetNE(); if (ne==0) { return; } const int dofs = fes.GetFE(0)->GetDof(); auto A = Reshape(ea_data_tmp.Write(), dofs, dofs, ne); auto AT = Reshape(ea_data.Write(), dofs, dofs, ne); MFEM_FORALL(e, ne, { for (int i = 0; i < dofs; i++) { for (int j = 0; j < dofs; j++) { const double a = A(i, j, e); AT(j, i, e) += a; } } }); } void TransposeIntegrator::AssembleEAInteriorFaces(const FiniteElementSpace& fes, Vector &ea_data_int, Vector &ea_data_ext) { const int nf = fes.GetNFbyType(FaceType::Interior); if (nf==0) { return; } Vector ea_data_int_tmp(ea_data_int.Size()); Vector ea_data_ext_tmp(ea_data_ext.Size()); ea_data_int_tmp = 0.0; ea_data_ext_tmp = 0.0; bfi->AssembleEAInteriorFaces(fes, ea_data_int_tmp, ea_data_ext_tmp); const int faceDofs = fes.GetTraceElement(0, fes.GetMesh()->GetFaceBaseGeometry(0))->GetDof(); auto A_int = Reshape(ea_data_int_tmp.Read(), faceDofs, faceDofs, 2, nf); auto A_ext = Reshape(ea_data_ext_tmp.Read(), faceDofs, faceDofs, 2, nf); auto AT_int = Reshape(ea_data_int.ReadWrite(), faceDofs, faceDofs, 2, nf); auto AT_ext = Reshape(ea_data_ext.ReadWrite(), faceDofs, faceDofs, 2, nf); MFEM_FORALL(f, nf, { for (int i = 0; i < faceDofs; i++) { for (int j = 0; j < faceDofs; j++) { const double a_int0 = A_int(i, j, 0, f); const double a_int1 = A_int(i, j, 1, f); const double a_ext0 = A_ext(i, j, 0, f); const double a_ext1 = A_ext(i, j, 1, f); AT_int(j, i, 0, f) += a_int0; AT_int(j, i, 1, f) += a_int1; AT_ext(j, i, 0, f) += a_ext1; AT_ext(j, i, 1, f) += a_ext0; } } }); } void TransposeIntegrator::AssembleEABoundaryFaces(const FiniteElementSpace& fes, Vector &ea_data_bdr) { const int nf = fes.GetNFbyType(FaceType::Boundary); if (nf==0) { return; } Vector ea_data_bdr_tmp(ea_data_bdr.Size()); ea_data_bdr_tmp = 0.0; bfi->AssembleEABoundaryFaces(fes, ea_data_bdr_tmp); const int faceDofs = fes.GetTraceElement(0, fes.GetMesh()->GetFaceBaseGeometry(0))->GetDof(); auto A_bdr = Reshape(ea_data_bdr_tmp.Read(), faceDofs, faceDofs, nf); auto AT_bdr = Reshape(ea_data_bdr.ReadWrite(), faceDofs, faceDofs, nf); MFEM_FORALL(f, nf, { for (int i = 0; i < faceDofs; i++) { for (int j = 0; j < faceDofs; j++) { const double a_bdr = A_bdr(i, j, f); AT_bdr(j, i, f) += a_bdr; } } }); FaceMatrixBdr fmat_bdr(ea_data_bdr, nf, faceDofs); FaceMatrixBdr fmat_bdr_tmp(ea_data_bdr_tmp, nf, faceDofs); fmat_bdr.Print(); fmat_bdr_tmp.Print(); } }<commit_msg>Remove prints<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "../general/forall.hpp" #include "bilininteg.hpp" #include "../linalg/elementmatrix.hpp" namespace mfem { void TransposeIntegrator::AssembleEA(const FiniteElementSpace &fes, Vector &ea_data) { Vector ea_data_tmp(ea_data.Size()); ea_data_tmp = 0.0; bfi->AssembleEA(fes, ea_data_tmp); const int ne = fes.GetNE(); if (ne==0) { return; } const int dofs = fes.GetFE(0)->GetDof(); auto A = Reshape(ea_data_tmp.Write(), dofs, dofs, ne); auto AT = Reshape(ea_data.Write(), dofs, dofs, ne); MFEM_FORALL(e, ne, { for (int i = 0; i < dofs; i++) { for (int j = 0; j < dofs; j++) { const double a = A(i, j, e); AT(j, i, e) += a; } } }); } void TransposeIntegrator::AssembleEAInteriorFaces(const FiniteElementSpace& fes, Vector &ea_data_int, Vector &ea_data_ext) { const int nf = fes.GetNFbyType(FaceType::Interior); if (nf==0) { return; } Vector ea_data_int_tmp(ea_data_int.Size()); Vector ea_data_ext_tmp(ea_data_ext.Size()); ea_data_int_tmp = 0.0; ea_data_ext_tmp = 0.0; bfi->AssembleEAInteriorFaces(fes, ea_data_int_tmp, ea_data_ext_tmp); const int faceDofs = fes.GetTraceElement(0, fes.GetMesh()->GetFaceBaseGeometry(0))->GetDof(); auto A_int = Reshape(ea_data_int_tmp.Read(), faceDofs, faceDofs, 2, nf); auto A_ext = Reshape(ea_data_ext_tmp.Read(), faceDofs, faceDofs, 2, nf); auto AT_int = Reshape(ea_data_int.ReadWrite(), faceDofs, faceDofs, 2, nf); auto AT_ext = Reshape(ea_data_ext.ReadWrite(), faceDofs, faceDofs, 2, nf); MFEM_FORALL(f, nf, { for (int i = 0; i < faceDofs; i++) { for (int j = 0; j < faceDofs; j++) { const double a_int0 = A_int(i, j, 0, f); const double a_int1 = A_int(i, j, 1, f); const double a_ext0 = A_ext(i, j, 0, f); const double a_ext1 = A_ext(i, j, 1, f); AT_int(j, i, 0, f) += a_int0; AT_int(j, i, 1, f) += a_int1; AT_ext(j, i, 0, f) += a_ext1; AT_ext(j, i, 1, f) += a_ext0; } } }); } void TransposeIntegrator::AssembleEABoundaryFaces(const FiniteElementSpace& fes, Vector &ea_data_bdr) { const int nf = fes.GetNFbyType(FaceType::Boundary); if (nf==0) { return; } Vector ea_data_bdr_tmp(ea_data_bdr.Size()); ea_data_bdr_tmp = 0.0; bfi->AssembleEABoundaryFaces(fes, ea_data_bdr_tmp); const int faceDofs = fes.GetTraceElement(0, fes.GetMesh()->GetFaceBaseGeometry(0))->GetDof(); auto A_bdr = Reshape(ea_data_bdr_tmp.Read(), faceDofs, faceDofs, nf); auto AT_bdr = Reshape(ea_data_bdr.ReadWrite(), faceDofs, faceDofs, nf); MFEM_FORALL(f, nf, { for (int i = 0; i < faceDofs; i++) { for (int j = 0; j < faceDofs; j++) { const double a_bdr = A_bdr(i, j, f); AT_bdr(j, i, f) += a_bdr; } } }); } }<|endoftext|>
<commit_before>/* * Rational ratio resampler * * Copyright 2012 Thomas Tsou <ttsou@vt.edu> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * See the COPYING file in the main directory for details. */ #include <stdlib.h> #include <math.h> #include <assert.h> #include <string.h> #include <cstdio> #include "Logger.h" #include "Resampler.h" #define MAX_OUTPUT_LEN 4096 bool Resampler::initFilters() { int i, n; int protoLen = mP * mFiltLen; float *proto; float sum = 0.0f; float scale = 0.0f; float midpt = protoLen / 2; /* * Allocate partition filters and the temporary prototype filter * according to numerator of the rational rate. Coefficients are * real only and must be 16-byte memory aligned for SSE usage. */ int flags = CXVEC_FLG_REAL_ONLY | CXVEC_FLG_MEM_ALIGN; proto = (float *) malloc(protoLen * sizeof(float)); if (!proto) return false; partitions = (struct cxvec **) malloc(sizeof(struct cxvec *) * mP); if (!partitions) return false; for (i = 0; i < mP; i++) partitions[i] = cxvec_alloc(mFiltLen, 0, NULL, flags); /* * Generate the prototype filter with a Blackman-harris window. * Scale coefficients with DC filter gain set to unity divided * by the number of filter partitions. */ float a0 = 0.35875; float a1 = 0.48829; float a2 = 0.14128; float a3 = 0.01168; for (i = 0; i < protoLen; i++) { proto[i] = cxvec_sinc(((float) i - midpt) / mP); proto[i] *= a0 - a1 * cos(2 * M_PI * i / (protoLen - 1)) + a2 * cos(4 * M_PI * i / (protoLen - 1)) - a3 * cos(6 * M_PI * i / (protoLen - 1)); sum += proto[i]; } scale = mP / sum; /* * Populate partition filters and reverse the coefficients per * convolution requirements. */ for (i = 0; i < mFiltLen; i++) { for (n = 0; n < mP; n++) { partitions[n]->data[i].real = proto[i * mP + n] * scale; partitions[n]->data[i].imag = 0.0f; } } for (i = 0; i < mP; i++) { cxvec_rvrs(partitions[i], partitions[i]); } free(proto); return true; } void Resampler::releaseFilters() { int i; for (i = 0; i < mP; i++) { cxvec_free(partitions[i]); } free(partitions); } static bool check_vec_len(struct cxvec *in, struct cxvec *out, int p, int q) { if (in->len % q) { LOG(ERR) << "Invalid input length " << in->len << " is not multiple of " << q; return false; } if (out->len % p) { LOG(ERR) << "Invalid output length " << out->len << " is not multiple of " << p; return false; } if ((in->len / q) != (out->len / p)) { LOG(ERR) << "Input/output block length mismatch"; return false; } if (out->len > MAX_OUTPUT_LEN) { LOG(ERR) << "Block length of " << out->len << " exceeds max"; return false; } return true; } void Resampler::computePath() { int i; for (i = 0; i < MAX_OUTPUT_LEN; i++) { inputIndex[i] = (mQ * i) / mP; outputPath[i] = (mQ * i) % mP; } } int Resampler::rotateSingle(struct cxvec *in, struct cxvec *out, struct cxvec *hist) { int i, n, path; if (!check_vec_len(in, out, mP, mQ)) return -1; /* Insert history */ memcpy(in->buf, hist->data, hist->len * sizeof(cmplx)); /* Generate output from precomputed input/output paths */ for (i = 0; i < out->len; i++) { n = inputIndex[i]; path = outputPath[i]; single_convolve(&in->data[n], partitions[path], &out->data[i]); } /* Save history */ memcpy(hist->data, &in->data[in->len - hist->len], hist->len * sizeof(cmplx)); return out->len; } int Resampler::rotate(struct cxvec **in, struct cxvec **out) { int len = 0; for (int i = 0; i < mChanM; i++) { if (chanActive[i]) len = rotateSingle(in[i], out[i], history[i]); else cxvec_reset(out[i]); } return len; } bool Resampler::activateChan(int num) { if ((num >= mChanM) || (num < 0)) { LOG(ERR) << "Invalid channel selection"; return false; } if (chanActive[num]) { LOG(ERR) << "Channel already activated"; return false; } chanActive[num] = true; return true; } bool Resampler::deactivateChan(int num) { if ((num >= mChanM) || (num < 0)) { LOG(ERR) << "Invalid channel selection"; return false; } if (chanActive[num]) { LOG(ERR) << "Channel already activated"; return false; } chanActive[num] = true; return true; } bool Resampler::init() { int i, rc; /* Filterbank internals */ rc = initFilters(); if (rc < 0) { LOG(ERR) << "Failed to create resampler filterbank"; return false; } /* History buffer */ history = (struct cxvec **) malloc(sizeof(struct cxvec *) * mChanM); if (!history) { LOG(ERR) << "Memory allocation failed"; return false; } for (i = 0; i < mChanM; i++) { history[i] = cxvec_alloc(mFiltLen, 0, NULL, 0); cxvec_reset(history[i]); } /* Channel activation status */ chanActive = (bool *) malloc(sizeof(bool) * mChanM); if (!chanActive) { LOG(ERR) << "Memory allocation failed"; return false; } for (i = 0; i < mChanM; i++) { chanActive[i] = false; } /* Precompute filterbank path */ inputIndex = (int *) malloc(sizeof(int) * MAX_OUTPUT_LEN); outputPath = (int *) malloc(sizeof(int) * MAX_OUTPUT_LEN); computePath(); return true; } Resampler::Resampler(int wP, int wQ, int wFiltLen, int wChanM) : mP(wP), mQ(wQ), mFiltLen(wFiltLen), mChanM(wChanM), inputIndex(NULL), outputPath(NULL) { } Resampler::~Resampler() { int i; releaseFilters(); for (i = 0; i < mChanM; i++) { cxvec_free(history[i]); } free(inputIndex); free(outputPath); free(history); free(chanActive); } <commit_msg>transceiver: mcbts: increase precomputed resampler path length<commit_after>/* * Rational ratio resampler * * Copyright 2012 Thomas Tsou <ttsou@vt.edu> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * See the COPYING file in the main directory for details. */ #include <stdlib.h> #include <math.h> #include <assert.h> #include <string.h> #include <cstdio> #include "Logger.h" #include "Resampler.h" #define MAX_OUTPUT_LEN (4096 * 4) bool Resampler::initFilters() { int i, n; int protoLen = mP * mFiltLen; float *proto; float sum = 0.0f; float scale = 0.0f; float midpt = protoLen / 2; /* * Allocate partition filters and the temporary prototype filter * according to numerator of the rational rate. Coefficients are * real only and must be 16-byte memory aligned for SSE usage. */ int flags = CXVEC_FLG_REAL_ONLY | CXVEC_FLG_MEM_ALIGN; proto = (float *) malloc(protoLen * sizeof(float)); if (!proto) return false; partitions = (struct cxvec **) malloc(sizeof(struct cxvec *) * mP); if (!partitions) return false; for (i = 0; i < mP; i++) partitions[i] = cxvec_alloc(mFiltLen, 0, NULL, flags); /* * Generate the prototype filter with a Blackman-harris window. * Scale coefficients with DC filter gain set to unity divided * by the number of filter partitions. */ float a0 = 0.35875; float a1 = 0.48829; float a2 = 0.14128; float a3 = 0.01168; for (i = 0; i < protoLen; i++) { proto[i] = cxvec_sinc(((float) i - midpt) / mP); proto[i] *= a0 - a1 * cos(2 * M_PI * i / (protoLen - 1)) + a2 * cos(4 * M_PI * i / (protoLen - 1)) - a3 * cos(6 * M_PI * i / (protoLen - 1)); sum += proto[i]; } scale = mP / sum; /* * Populate partition filters and reverse the coefficients per * convolution requirements. */ for (i = 0; i < mFiltLen; i++) { for (n = 0; n < mP; n++) { partitions[n]->data[i].real = proto[i * mP + n] * scale; partitions[n]->data[i].imag = 0.0f; } } for (i = 0; i < mP; i++) { cxvec_rvrs(partitions[i], partitions[i]); } free(proto); return true; } void Resampler::releaseFilters() { int i; for (i = 0; i < mP; i++) { cxvec_free(partitions[i]); } free(partitions); } static bool check_vec_len(struct cxvec *in, struct cxvec *out, int p, int q) { if (in->len % q) { LOG(ERR) << "Invalid input length " << in->len << " is not multiple of " << q; return false; } if (out->len % p) { LOG(ERR) << "Invalid output length " << out->len << " is not multiple of " << p; return false; } if ((in->len / q) != (out->len / p)) { LOG(ERR) << "Input/output block length mismatch"; return false; } if (out->len > MAX_OUTPUT_LEN) { LOG(ERR) << "Block length of " << out->len << " exceeds max"; return false; } return true; } void Resampler::computePath() { int i; for (i = 0; i < MAX_OUTPUT_LEN; i++) { inputIndex[i] = (mQ * i) / mP; outputPath[i] = (mQ * i) % mP; } } int Resampler::rotateSingle(struct cxvec *in, struct cxvec *out, struct cxvec *hist) { int i, n, path; if (!check_vec_len(in, out, mP, mQ)) return -1; /* Insert history */ memcpy(in->buf, hist->data, hist->len * sizeof(cmplx)); /* Generate output from precomputed input/output paths */ for (i = 0; i < out->len; i++) { n = inputIndex[i]; path = outputPath[i]; single_convolve(&in->data[n], partitions[path], &out->data[i]); } /* Save history */ memcpy(hist->data, &in->data[in->len - hist->len], hist->len * sizeof(cmplx)); return out->len; } int Resampler::rotate(struct cxvec **in, struct cxvec **out) { int len = 0; for (int i = 0; i < mChanM; i++) { if (chanActive[i]) len = rotateSingle(in[i], out[i], history[i]); else cxvec_reset(out[i]); } return len; } bool Resampler::activateChan(int num) { if ((num >= mChanM) || (num < 0)) { LOG(ERR) << "Invalid channel selection"; return false; } if (chanActive[num]) { LOG(ERR) << "Channel already activated"; return false; } chanActive[num] = true; return true; } bool Resampler::deactivateChan(int num) { if ((num >= mChanM) || (num < 0)) { LOG(ERR) << "Invalid channel selection"; return false; } if (chanActive[num]) { LOG(ERR) << "Channel already activated"; return false; } chanActive[num] = true; return true; } bool Resampler::init() { int i, rc; /* Filterbank internals */ rc = initFilters(); if (rc < 0) { LOG(ERR) << "Failed to create resampler filterbank"; return false; } /* History buffer */ history = (struct cxvec **) malloc(sizeof(struct cxvec *) * mChanM); if (!history) { LOG(ERR) << "Memory allocation failed"; return false; } for (i = 0; i < mChanM; i++) { history[i] = cxvec_alloc(mFiltLen, 0, NULL, 0); cxvec_reset(history[i]); } /* Channel activation status */ chanActive = (bool *) malloc(sizeof(bool) * mChanM); if (!chanActive) { LOG(ERR) << "Memory allocation failed"; return false; } for (i = 0; i < mChanM; i++) { chanActive[i] = false; } /* Precompute filterbank path */ inputIndex = (int *) malloc(sizeof(int) * MAX_OUTPUT_LEN); outputPath = (int *) malloc(sizeof(int) * MAX_OUTPUT_LEN); computePath(); return true; } Resampler::Resampler(int wP, int wQ, int wFiltLen, int wChanM) : mP(wP), mQ(wQ), mFiltLen(wFiltLen), mChanM(wChanM), inputIndex(NULL), outputPath(NULL) { } Resampler::~Resampler() { int i; releaseFilters(); for (i = 0; i < mChanM; i++) { cxvec_free(history[i]); } free(inputIndex); free(outputPath); free(history); free(chanActive); } <|endoftext|>
<commit_before>#include "../include/cxx.h" #include <cstring> #include <exception> #include <iostream> #include <memory> #include <stdexcept> #include <vector> extern "C" { const char *cxxbridge05$cxx_string$data(const std::string &s) noexcept { return s.data(); } size_t cxxbridge05$cxx_string$length(const std::string &s) noexcept { return s.length(); } // rust::String void cxxbridge05$string$new(rust::String *self) noexcept; void cxxbridge05$string$clone(rust::String *self, const rust::String &other) noexcept; bool cxxbridge05$string$from(rust::String *self, const char *ptr, size_t len) noexcept; void cxxbridge05$string$drop(rust::String *self) noexcept; const char *cxxbridge05$string$ptr(const rust::String *self) noexcept; size_t cxxbridge05$string$len(const rust::String *self) noexcept; // rust::Str bool cxxbridge05$str$valid(const char *ptr, size_t len) noexcept; } // extern "C" namespace rust { inline namespace cxxbridge05 { template <typename Exception> void panic [[noreturn]] (const char *msg) { #if defined(RUST_CXX_NO_EXCEPTIONS) std::cerr << "Error: " << msg << ". Aborting." << std::endl; std::terminate(); #else throw Exception(msg); #endif } template void panic<std::out_of_range>[[noreturn]] (const char *msg); String::String() noexcept { cxxbridge05$string$new(this); } String::String(const String &other) noexcept { cxxbridge05$string$clone(this, other); } String::String(String &&other) noexcept { this->repr = other.repr; cxxbridge05$string$new(&other); } String::~String() noexcept { cxxbridge05$string$drop(this); } static void initString(String *self, const char *s, size_t len) { if (!cxxbridge05$string$from(self, s, len)) { panic<std::invalid_argument>("data for rust::String is not utf-8"); } } String::String(const std::string &s) { initString(this, s.data(), s.length()); } String::String(const char *s) { initString(this, s, std::strlen(s)); } String::String(const char *s, size_t len) { initString(this, s == nullptr && len == 0 ? reinterpret_cast<const char *>(1) : s, len); } String &String::operator=(const String &other) noexcept { if (this != &other) { cxxbridge05$string$drop(this); cxxbridge05$string$clone(this, other); } return *this; } String &String::operator=(String &&other) noexcept { if (this != &other) { cxxbridge05$string$drop(this); this->repr = other.repr; cxxbridge05$string$new(&other); } return *this; } String::operator std::string() const { return std::string(this->data(), this->size()); } const char *String::data() const noexcept { return cxxbridge05$string$ptr(this); } size_t String::size() const noexcept { return cxxbridge05$string$len(this); } size_t String::length() const noexcept { return cxxbridge05$string$len(this); } String::String(unsafe_bitcopy_t, const String &bits) noexcept : repr(bits.repr) {} std::ostream &operator<<(std::ostream &os, const String &s) { os.write(s.data(), s.size()); return os; } Str::Str() noexcept : repr(Repr{reinterpret_cast<const char *>(1), 0}) {} Str::Str(const Str &) noexcept = default; static void initStr(Str::Repr repr) { if (!cxxbridge05$str$valid(repr.ptr, repr.len)) { panic<std::invalid_argument>("data for rust::Str is not utf-8"); } } Str::Str(const std::string &s) : repr(Repr{s.data(), s.length()}) { initStr(this->repr); } Str::Str(const char *s) : repr(Repr{s, std::strlen(s)}) { initStr(this->repr); } Str::Str(const char *s, size_t len) : repr( Repr{s == nullptr && len == 0 ? reinterpret_cast<const char *>(1) : s, len}) { initStr(this->repr); } Str &Str::operator=(Str other) noexcept { this->repr = other.repr; return *this; } Str::operator std::string() const { return std::string(this->data(), this->size()); } const char *Str::data() const noexcept { return this->repr.ptr; } size_t Str::size() const noexcept { return this->repr.len; } size_t Str::length() const noexcept { return this->repr.len; } Str::Str(Repr repr_) noexcept : repr(repr_) {} Str::operator Repr() noexcept { return this->repr; } std::ostream &operator<<(std::ostream &os, const Str &s) { os.write(s.data(), s.size()); return os; } extern "C" { const char *cxxbridge05$error(const char *ptr, size_t len) { char *copy = new char[len]; strncpy(copy, ptr, len); return copy; } } // extern "C" Error::Error(Str::Repr msg) noexcept : msg(msg) {} Error::Error(const Error &other) { this->msg.ptr = cxxbridge05$error(other.msg.ptr, other.msg.len); this->msg.len = other.msg.len; } Error::Error(Error &&other) noexcept { delete[] this->msg.ptr; this->msg = other.msg; other.msg.ptr = nullptr; other.msg.len = 0; } Error::~Error() noexcept { delete[] this->msg.ptr; } const char *Error::what() const noexcept { return this->msg.ptr; } } // namespace cxxbridge05 } // namespace rust extern "C" { void cxxbridge05$unique_ptr$std$string$null( std::unique_ptr<std::string> *ptr) noexcept { new (ptr) std::unique_ptr<std::string>(); } void cxxbridge05$unique_ptr$std$string$raw(std::unique_ptr<std::string> *ptr, std::string *raw) noexcept { new (ptr) std::unique_ptr<std::string>(raw); } const std::string *cxxbridge05$unique_ptr$std$string$get( const std::unique_ptr<std::string> &ptr) noexcept { return ptr.get(); } std::string *cxxbridge05$unique_ptr$std$string$release( std::unique_ptr<std::string> &ptr) noexcept { return ptr.release(); } void cxxbridge05$unique_ptr$std$string$drop( std::unique_ptr<std::string> *ptr) noexcept { ptr->~unique_ptr(); } } // extern "C" #define STD_VECTOR_OPS(RUST_TYPE, CXX_TYPE) \ size_t cxxbridge05$std$vector$##RUST_TYPE##$size( \ const std::vector<CXX_TYPE> &s) noexcept { \ return s.size(); \ } \ const CXX_TYPE *cxxbridge05$std$vector$##RUST_TYPE##$get_unchecked( \ const std::vector<CXX_TYPE> &s, size_t pos) noexcept { \ return &s[pos]; \ } \ void cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$null( \ std::unique_ptr<std::vector<CXX_TYPE>> *ptr) noexcept { \ new (ptr) std::unique_ptr<std::vector<CXX_TYPE>>(); \ } \ void cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$raw( \ std::unique_ptr<std::vector<CXX_TYPE>> *ptr, \ std::vector<CXX_TYPE> *raw) noexcept { \ new (ptr) std::unique_ptr<std::vector<CXX_TYPE>>(raw); \ } \ const std::vector<CXX_TYPE> \ *cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$get( \ const std::unique_ptr<std::vector<CXX_TYPE>> &ptr) noexcept { \ return ptr.get(); \ } \ std::vector<CXX_TYPE> \ *cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$release( \ std::unique_ptr<std::vector<CXX_TYPE>> &ptr) noexcept { \ return ptr.release(); \ } \ void cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$drop( \ std::unique_ptr<std::vector<CXX_TYPE>> *ptr) noexcept { \ ptr->~unique_ptr(); \ } #define RUST_VEC_EXTERNS(RUST_TYPE, CXX_TYPE) \ void cxxbridge05$rust_vec$##RUST_TYPE##$new( \ rust::Vec<CXX_TYPE> *ptr) noexcept; \ void cxxbridge05$rust_vec$##RUST_TYPE##$drop( \ rust::Vec<CXX_TYPE> *ptr) noexcept; \ size_t cxxbridge05$rust_vec$##RUST_TYPE##$len( \ const rust::Vec<CXX_TYPE> *ptr) noexcept; \ const CXX_TYPE *cxxbridge05$rust_vec$##RUST_TYPE##$data( \ const rust::Vec<CXX_TYPE> *ptr) noexcept; \ size_t cxxbridge05$rust_vec$##RUST_TYPE##$stride() noexcept; #define RUST_VEC_OPS(RUST_TYPE, CXX_TYPE) \ template <> \ Vec<CXX_TYPE>::Vec() noexcept { \ cxxbridge05$rust_vec$##RUST_TYPE##$new(this); \ } \ template <> \ void Vec<CXX_TYPE>::drop() noexcept { \ return cxxbridge05$rust_vec$##RUST_TYPE##$drop(this); \ } \ template <> \ size_t Vec<CXX_TYPE>::size() const noexcept { \ return cxxbridge05$rust_vec$##RUST_TYPE##$len(this); \ } \ template <> \ const CXX_TYPE *Vec<CXX_TYPE>::data() const noexcept { \ return cxxbridge05$rust_vec$##RUST_TYPE##$data(this); \ } \ template <> \ size_t Vec<CXX_TYPE>::stride() noexcept { \ return cxxbridge05$rust_vec$##RUST_TYPE##$stride(); \ } // Usize and isize are the same type as one of the below. #define FOR_EACH_NUMERIC(MACRO) \ MACRO(u8, uint8_t) \ MACRO(u16, uint16_t) \ MACRO(u32, uint32_t) \ MACRO(u64, uint64_t) \ MACRO(i8, int8_t) \ MACRO(i16, int16_t) \ MACRO(i32, int32_t) \ MACRO(i64, int64_t) \ MACRO(f32, float) \ MACRO(f64, double) #define FOR_EACH_STD_VECTOR(MACRO) \ FOR_EACH_NUMERIC(MACRO) \ MACRO(usize, size_t) \ MACRO(isize, rust::isize) \ MACRO(string, std::string) #define FOR_EACH_RUST_VEC(MACRO) \ FOR_EACH_NUMERIC(MACRO) \ MACRO(bool, bool) \ MACRO(string, rust::String) extern "C" { FOR_EACH_STD_VECTOR(STD_VECTOR_OPS) FOR_EACH_RUST_VEC(RUST_VEC_EXTERNS) } // extern "C" namespace rust { inline namespace cxxbridge05 { FOR_EACH_RUST_VEC(RUST_VEC_OPS) } // namespace cxxbridge05 } // namespace rust <commit_msg>Add asserts to protect string construction from nullptr when building with assertions<commit_after>#include "../include/cxx.h" #include <cassert> #include <cstring> #include <exception> #include <iostream> #include <memory> #include <stdexcept> #include <vector> extern "C" { const char *cxxbridge05$cxx_string$data(const std::string &s) noexcept { return s.data(); } size_t cxxbridge05$cxx_string$length(const std::string &s) noexcept { return s.length(); } // rust::String void cxxbridge05$string$new(rust::String *self) noexcept; void cxxbridge05$string$clone(rust::String *self, const rust::String &other) noexcept; bool cxxbridge05$string$from(rust::String *self, const char *ptr, size_t len) noexcept; void cxxbridge05$string$drop(rust::String *self) noexcept; const char *cxxbridge05$string$ptr(const rust::String *self) noexcept; size_t cxxbridge05$string$len(const rust::String *self) noexcept; // rust::Str bool cxxbridge05$str$valid(const char *ptr, size_t len) noexcept; } // extern "C" namespace rust { inline namespace cxxbridge05 { template <typename Exception> void panic [[noreturn]] (const char *msg) { #if defined(RUST_CXX_NO_EXCEPTIONS) std::cerr << "Error: " << msg << ". Aborting." << std::endl; std::terminate(); #else throw Exception(msg); #endif } template void panic<std::out_of_range>[[noreturn]] (const char *msg); String::String() noexcept { cxxbridge05$string$new(this); } String::String(const String &other) noexcept { cxxbridge05$string$clone(this, other); } String::String(String &&other) noexcept { this->repr = other.repr; cxxbridge05$string$new(&other); } String::~String() noexcept { cxxbridge05$string$drop(this); } static void initString(String *self, const char *s, size_t len) { if (!cxxbridge05$string$from(self, s, len)) { panic<std::invalid_argument>("data for rust::String is not utf-8"); } } String::String(const std::string &s) { initString(this, s.data(), s.length()); } String::String(const char *s) { assert(s != nullptr); initString(this, s, std::strlen(s)); } String::String(const char *s, size_t len) { assert(s != nullptr || len == 0); initString(this, s == nullptr && len == 0 ? reinterpret_cast<const char *>(1) : s, len); } String &String::operator=(const String &other) noexcept { if (this != &other) { cxxbridge05$string$drop(this); cxxbridge05$string$clone(this, other); } return *this; } String &String::operator=(String &&other) noexcept { if (this != &other) { cxxbridge05$string$drop(this); this->repr = other.repr; cxxbridge05$string$new(&other); } return *this; } String::operator std::string() const { return std::string(this->data(), this->size()); } const char *String::data() const noexcept { return cxxbridge05$string$ptr(this); } size_t String::size() const noexcept { return cxxbridge05$string$len(this); } size_t String::length() const noexcept { return cxxbridge05$string$len(this); } String::String(unsafe_bitcopy_t, const String &bits) noexcept : repr(bits.repr) {} std::ostream &operator<<(std::ostream &os, const String &s) { os.write(s.data(), s.size()); return os; } Str::Str() noexcept : repr(Repr{reinterpret_cast<const char *>(1), 0}) {} Str::Str(const Str &) noexcept = default; static void initStr(Str::Repr repr) { if (!cxxbridge05$str$valid(repr.ptr, repr.len)) { panic<std::invalid_argument>("data for rust::Str is not utf-8"); } } Str::Str(const std::string &s) : repr(Repr{s.data(), s.length()}) { initStr(this->repr); } Str::Str(const char *s) : repr(Repr{s, std::strlen(s)}) { assert(s != nullptr); initStr(this->repr); } Str::Str(const char *s, size_t len) : repr( Repr{s == nullptr && len == 0 ? reinterpret_cast<const char *>(1) : s, len}) { assert(s != nullptr || len == 0); initStr(this->repr); } Str &Str::operator=(Str other) noexcept { this->repr = other.repr; return *this; } Str::operator std::string() const { return std::string(this->data(), this->size()); } const char *Str::data() const noexcept { return this->repr.ptr; } size_t Str::size() const noexcept { return this->repr.len; } size_t Str::length() const noexcept { return this->repr.len; } Str::Str(Repr repr_) noexcept : repr(repr_) {} Str::operator Repr() noexcept { return this->repr; } std::ostream &operator<<(std::ostream &os, const Str &s) { os.write(s.data(), s.size()); return os; } extern "C" { const char *cxxbridge05$error(const char *ptr, size_t len) { char *copy = new char[len]; strncpy(copy, ptr, len); return copy; } } // extern "C" Error::Error(Str::Repr msg) noexcept : msg(msg) {} Error::Error(const Error &other) { this->msg.ptr = cxxbridge05$error(other.msg.ptr, other.msg.len); this->msg.len = other.msg.len; } Error::Error(Error &&other) noexcept { delete[] this->msg.ptr; this->msg = other.msg; other.msg.ptr = nullptr; other.msg.len = 0; } Error::~Error() noexcept { delete[] this->msg.ptr; } const char *Error::what() const noexcept { return this->msg.ptr; } } // namespace cxxbridge05 } // namespace rust extern "C" { void cxxbridge05$unique_ptr$std$string$null( std::unique_ptr<std::string> *ptr) noexcept { new (ptr) std::unique_ptr<std::string>(); } void cxxbridge05$unique_ptr$std$string$raw(std::unique_ptr<std::string> *ptr, std::string *raw) noexcept { new (ptr) std::unique_ptr<std::string>(raw); } const std::string *cxxbridge05$unique_ptr$std$string$get( const std::unique_ptr<std::string> &ptr) noexcept { return ptr.get(); } std::string *cxxbridge05$unique_ptr$std$string$release( std::unique_ptr<std::string> &ptr) noexcept { return ptr.release(); } void cxxbridge05$unique_ptr$std$string$drop( std::unique_ptr<std::string> *ptr) noexcept { ptr->~unique_ptr(); } } // extern "C" #define STD_VECTOR_OPS(RUST_TYPE, CXX_TYPE) \ size_t cxxbridge05$std$vector$##RUST_TYPE##$size( \ const std::vector<CXX_TYPE> &s) noexcept { \ return s.size(); \ } \ const CXX_TYPE *cxxbridge05$std$vector$##RUST_TYPE##$get_unchecked( \ const std::vector<CXX_TYPE> &s, size_t pos) noexcept { \ return &s[pos]; \ } \ void cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$null( \ std::unique_ptr<std::vector<CXX_TYPE>> *ptr) noexcept { \ new (ptr) std::unique_ptr<std::vector<CXX_TYPE>>(); \ } \ void cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$raw( \ std::unique_ptr<std::vector<CXX_TYPE>> *ptr, \ std::vector<CXX_TYPE> *raw) noexcept { \ new (ptr) std::unique_ptr<std::vector<CXX_TYPE>>(raw); \ } \ const std::vector<CXX_TYPE> \ *cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$get( \ const std::unique_ptr<std::vector<CXX_TYPE>> &ptr) noexcept { \ return ptr.get(); \ } \ std::vector<CXX_TYPE> \ *cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$release( \ std::unique_ptr<std::vector<CXX_TYPE>> &ptr) noexcept { \ return ptr.release(); \ } \ void cxxbridge05$unique_ptr$std$vector$##RUST_TYPE##$drop( \ std::unique_ptr<std::vector<CXX_TYPE>> *ptr) noexcept { \ ptr->~unique_ptr(); \ } #define RUST_VEC_EXTERNS(RUST_TYPE, CXX_TYPE) \ void cxxbridge05$rust_vec$##RUST_TYPE##$new( \ rust::Vec<CXX_TYPE> *ptr) noexcept; \ void cxxbridge05$rust_vec$##RUST_TYPE##$drop( \ rust::Vec<CXX_TYPE> *ptr) noexcept; \ size_t cxxbridge05$rust_vec$##RUST_TYPE##$len( \ const rust::Vec<CXX_TYPE> *ptr) noexcept; \ const CXX_TYPE *cxxbridge05$rust_vec$##RUST_TYPE##$data( \ const rust::Vec<CXX_TYPE> *ptr) noexcept; \ size_t cxxbridge05$rust_vec$##RUST_TYPE##$stride() noexcept; #define RUST_VEC_OPS(RUST_TYPE, CXX_TYPE) \ template <> \ Vec<CXX_TYPE>::Vec() noexcept { \ cxxbridge05$rust_vec$##RUST_TYPE##$new(this); \ } \ template <> \ void Vec<CXX_TYPE>::drop() noexcept { \ return cxxbridge05$rust_vec$##RUST_TYPE##$drop(this); \ } \ template <> \ size_t Vec<CXX_TYPE>::size() const noexcept { \ return cxxbridge05$rust_vec$##RUST_TYPE##$len(this); \ } \ template <> \ const CXX_TYPE *Vec<CXX_TYPE>::data() const noexcept { \ return cxxbridge05$rust_vec$##RUST_TYPE##$data(this); \ } \ template <> \ size_t Vec<CXX_TYPE>::stride() noexcept { \ return cxxbridge05$rust_vec$##RUST_TYPE##$stride(); \ } // Usize and isize are the same type as one of the below. #define FOR_EACH_NUMERIC(MACRO) \ MACRO(u8, uint8_t) \ MACRO(u16, uint16_t) \ MACRO(u32, uint32_t) \ MACRO(u64, uint64_t) \ MACRO(i8, int8_t) \ MACRO(i16, int16_t) \ MACRO(i32, int32_t) \ MACRO(i64, int64_t) \ MACRO(f32, float) \ MACRO(f64, double) #define FOR_EACH_STD_VECTOR(MACRO) \ FOR_EACH_NUMERIC(MACRO) \ MACRO(usize, size_t) \ MACRO(isize, rust::isize) \ MACRO(string, std::string) #define FOR_EACH_RUST_VEC(MACRO) \ FOR_EACH_NUMERIC(MACRO) \ MACRO(bool, bool) \ MACRO(string, rust::String) extern "C" { FOR_EACH_STD_VECTOR(STD_VECTOR_OPS) FOR_EACH_RUST_VEC(RUST_VEC_EXTERNS) } // extern "C" namespace rust { inline namespace cxxbridge05 { FOR_EACH_RUST_VEC(RUST_VEC_OPS) } // namespace cxxbridge05 } // namespace rust <|endoftext|>
<commit_before>#include "Camera.h" #include "Object.h" #include "Director.h" #include "TransformPipelineParam.h" using namespace Math; using namespace std; using namespace Rendering::Light; using namespace Device; using namespace Core; using namespace Rendering::Camera; using namespace Rendering::Manager; Camera::Camera() : Component(), _frustum(nullptr), _renderTarget(nullptr), _depthBuffer(nullptr) { } Camera::~Camera(void) { } void Camera::Initialize() { _FOV = 60.0f; _clippingNear = 0.01f; _clippingFar = 50.0f; Size<unsigned int> windowSize = Director::GetInstance()->GetWindowSize(); _aspect = (float)windowSize.w / (float)windowSize.h; _camType = Type::Perspective; _clearColor = Color(0.5f, 0.5f, 1.0f, 1.0f); _frustum = new Frustum(0.0f); _renderTarget = new Texture::RenderTexture; _renderTarget->Create(windowSize); _depthBuffer = new Texture::RenderTexture; _depthBuffer->Create(windowSize); _constBuffer = new Buffer::ConstBuffer; if(_constBuffer->Create(sizeof(CameraConstBuffer)) == false) ASSERT("Error, cam->constbuffer->Create"); //_clearFlag = ClearFlag::FlagSolidColor; } void Camera::Destroy() { SAFE_DELETE(_frustum); SAFE_DELETE(_renderTarget); SAFE_DELETE(_depthBuffer); } void Camera::CalcAspect() { Size<unsigned int> windowSize = Device::Director::GetInstance()->GetWindowSize(); _aspect = (float)windowSize.w / (float)windowSize.h; } void Camera::ProjectionMatrix(Math::Matrix& outMatrix) { if(_camType == Type::Perspective) { float radian = _FOV * PI / 180.0f; Matrix::PerspectiveFovLH(outMatrix, _aspect, radian, _clippingNear, _clippingFar); } else if(_camType == Type::Orthographic) { Size<unsigned int> windowSize = Device::Director::GetInstance()->GetWindowSize(); Matrix::OrthoLH(outMatrix, (float)(windowSize.w), (float)(windowSize.h), _clippingNear, _clippingFar); } } void Camera::ViewMatrix(Math::Matrix& outMatrix) { Transform* ownerTransform = _owner->GetTransform(); ownerTransform->WorldMatrix(outMatrix); Vector3 worldPos; worldPos.x = outMatrix._41; worldPos.y = outMatrix._42; worldPos.z = outMatrix._43; Vector3 p; p.x = -Vector3::Dot(ownerTransform->GetRight(), worldPos); p.y = -Vector3::Dot(ownerTransform->GetUp(), worldPos); p.z = -Vector3::Dot(ownerTransform->GetForward(), worldPos); outMatrix._41 = p.x; outMatrix._42 = p.y; outMatrix._43 = p.z; outMatrix._44 = 1.0f; } void Camera::UpdateTransformCBAndCheckRender(const Structure::Vector<std::string, Core::Object>& objects) { TransformPipelineParam tfParam; ProjectionMatrix(tfParam.projMat); ViewMatrix(tfParam.viewMat); Matrix viewProj = tfParam.viewMat * tfParam.projMat; _frustum->Make(viewProj); CameraConstBuffer camCB; { const Math::Matrix& viewMat = tfParam.viewMat; camCB.viewPos = Vector4(viewMat._41, viewMat._42, viewMat._43, 1.0f); camCB.clippingNear = _clippingNear; camCB.clippingFar = _clippingFar; const auto& size = Device::Director::GetInstance()->GetWindowSize(); camCB.screenSize.w = static_cast<float>(size.w); camCB.screenSize.h = static_cast<float>(size.h); } ID3D11DeviceContext* context = Device::Director::GetInstance()->GetDirectX()->GetContext(); _constBuffer->Update(context, &camCB); auto& dataInobjects = objects.GetVector(); for(auto iter = dataInobjects.begin(); iter != dataInobjects.end(); ++iter) { GET_CONTENT_FROM_ITERATOR(iter)->Culling(_frustum); GET_CONTENT_FROM_ITERATOR(iter)->UpdateTransformCBAndCheckRender(tfParam); } } void Camera::RenderObjects(const Device::DirectX* dx, const Rendering::Manager::RenderManager* renderMgr) { enum MeshRenderOption { DepthWriteWithTest, AlphaTest, Common, }; auto MeshRender = [&](ID3D11DeviceContext* context, BasicMaterial* customMaterial, Manager::RenderManager::MeshType type, MeshRenderOption option) { BasicMaterial* currentUseMaterial = nullptr; if(customMaterial && (option == MeshRenderOption::DepthWriteWithTest || option == MeshRenderOption::AlphaTest) ) ASSERT("Invalid Arg"); auto RenderIter = [&](BasicMaterial* material, Mesh::Mesh* mesh) { if(customMaterial) material = customMaterial; else if(option == MeshRenderOption::DepthWriteWithTest) { material = mesh->GetMeshRenderer()->GetDepthWriteMaterial(); customMaterial = material; } else if(option == MeshRenderOption::AlphaTest) { material = mesh->GetMeshRenderer()->GetAlphaTestMaterial(); customMaterial = material; } if(currentUseMaterial != material) { currentUseMaterial = material; currentUseMaterial->UpdateShader(context); } mesh->Render(customMaterial, _constBuffer); }; renderMgr->Iterate(RenderIter, type); }; //graphics part { ID3D11DeviceContext* context = dx->GetContext(); //Test { ID3D11RenderTargetView* rtv = dx->GetBackBuffer(); context->OMSetRenderTargets(1, &rtv, dx->GetDepthBuffer()->GetDepthStencilView()); context->ClearRenderTargetView(dx->GetBackBuffer(), _clearColor.color); dx->GetDepthBuffer()->Clear(1.0f, 0); MeshRender(context, nullptr, Manager::RenderManager::MeshType::nonAlpha, MeshRenderOption::Common); } //clear backbuffer, depthbuffer { //context->ClearRenderTargetView(dx->GetBackBuffer(), _clearColor.color); //dx->GetDepthBuffer()->Clear(0.0f, 0); //_depthBuffer->Clear(Rendering::Color::white(), dx); } //off alpha blending { //float blendFactor[1] = { 0.0f }; //context->OMSetBlendState(dx->GetOpaqueBlendState(), blendFactor, 0xffffffff); } //Render { /* ID3D11RenderTargetView* nullRTV = nullptr; ID3D11DepthStencilView* nullDSV = nullptr; ID3D11ShaderResourceView* nullSRV = nullptr; ID3D11UnorderedAccessView* nullUAV = nullptr; ID3D11SamplerState* nullSampler = nullptr;*/ //Early-Z { //ID3D11RenderTargetView* rtv = _depthBuffer->GetRenderTargetView(); //context->OMSetRenderTargets(1, &rtv, dx->GetDepthBuffer()->GetDepthStencilView()); //context->OMSetDepthStencilState(dx->GetDepthLessEqualState(), 0); //MeshRender(context, nullptr, RenderManager::MeshType::nonAlpha, MeshRenderOption::DepthWriteWithTest); //rtv = nullptr; //context->OMSetRenderTargets(1, &rtv, dx->GetDepthBuffer()->GetDepthStencilView()); //context->RSSetState(dx->GetDisableCullingRasterizerState()); //MeshRender(context, nullptr, RenderManager::MeshType::hasAlpha, MeshRenderOption::AlphaTest); //context->RSSetState(nullptr); } //Light Culling { //context->OMSetRenderTargets(1, &nullRTV, nullDSV); //context->VSSetShader(nullptr, nullptr, 0); //context->PSSetShader(nullptr, nullptr, 0); //context->CSSetShader( } //Forward Rendering { } } IDXGISwapChain* swapChain = dx->GetSwapChain(); swapChain->Present(0, 0); } } <commit_msg>Camera - 테스트로 LightCulling 붙여봄 #37<commit_after>#include "Camera.h" #include "Object.h" #include "Director.h" #include "TransformPipelineParam.h" using namespace Math; using namespace std; using namespace Rendering::Light; using namespace Device; using namespace Core; using namespace Rendering::Camera; using namespace Rendering::Manager; Camera::Camera() : Component(), _frustum(nullptr), _renderTarget(nullptr), _depthBuffer(nullptr) { } Camera::~Camera(void) { } void Camera::Initialize() { _FOV = 60.0f; _clippingNear = 0.01f; _clippingFar = 50.0f; Size<unsigned int> windowSize = Director::GetInstance()->GetWindowSize(); _aspect = (float)windowSize.w / (float)windowSize.h; _camType = Type::Perspective; _clearColor = Color(0.5f, 0.5f, 1.0f, 1.0f); _frustum = new Frustum(0.0f); _renderTarget = new Texture::RenderTexture; _renderTarget->Create(windowSize); _depthBuffer = new Texture::RenderTexture; _depthBuffer->Create(windowSize); _constBuffer = new Buffer::ConstBuffer; if(_constBuffer->Create(sizeof(CameraConstBuffer)) == false) ASSERT("Error, cam->constbuffer->Create"); //_clearFlag = ClearFlag::FlagSolidColor; } void Camera::Destroy() { SAFE_DELETE(_frustum); SAFE_DELETE(_renderTarget); SAFE_DELETE(_depthBuffer); } void Camera::CalcAspect() { Size<unsigned int> windowSize = Device::Director::GetInstance()->GetWindowSize(); _aspect = (float)windowSize.w / (float)windowSize.h; } void Camera::ProjectionMatrix(Math::Matrix& outMatrix) { if(_camType == Type::Perspective) { float radian = _FOV * PI / 180.0f; Matrix::PerspectiveFovLH(outMatrix, _aspect, radian, _clippingNear, _clippingFar); } else if(_camType == Type::Orthographic) { Size<unsigned int> windowSize = Device::Director::GetInstance()->GetWindowSize(); Matrix::OrthoLH(outMatrix, (float)(windowSize.w), (float)(windowSize.h), _clippingNear, _clippingFar); } } void Camera::ViewMatrix(Math::Matrix& outMatrix) { Transform* ownerTransform = _owner->GetTransform(); ownerTransform->WorldMatrix(outMatrix); Vector3 worldPos; worldPos.x = outMatrix._41; worldPos.y = outMatrix._42; worldPos.z = outMatrix._43; Vector3 p; p.x = -Vector3::Dot(ownerTransform->GetRight(), worldPos); p.y = -Vector3::Dot(ownerTransform->GetUp(), worldPos); p.z = -Vector3::Dot(ownerTransform->GetForward(), worldPos); outMatrix._41 = p.x; outMatrix._42 = p.y; outMatrix._43 = p.z; outMatrix._44 = 1.0f; } void Camera::UpdateTransformCBAndCheckRender(const Structure::Vector<std::string, Core::Object>& objects) { TransformPipelineParam tfParam; ProjectionMatrix(tfParam.projMat); ViewMatrix(tfParam.viewMat); Matrix viewProj = tfParam.viewMat * tfParam.projMat; _frustum->Make(viewProj); CameraConstBuffer camCB; { const Math::Matrix& viewMat = tfParam.viewMat; camCB.viewPos = Vector4(viewMat._41, viewMat._42, viewMat._43, 1.0f); camCB.clippingNear = _clippingNear; camCB.clippingFar = _clippingFar; const auto& size = Device::Director::GetInstance()->GetWindowSize(); camCB.screenSize.w = static_cast<float>(size.w); camCB.screenSize.h = static_cast<float>(size.h); } ID3D11DeviceContext* context = Device::Director::GetInstance()->GetDirectX()->GetContext(); _constBuffer->Update(context, &camCB); auto& dataInobjects = objects.GetVector(); for(auto iter = dataInobjects.begin(); iter != dataInobjects.end(); ++iter) { GET_CONTENT_FROM_ITERATOR(iter)->Culling(_frustum); GET_CONTENT_FROM_ITERATOR(iter)->UpdateTransformCBAndCheckRender(tfParam); } } void Camera::RenderObjects(const Device::DirectX* dx, const Rendering::Manager::RenderManager* renderMgr) { enum MeshRenderOption { DepthWriteWithTest, AlphaTest, Common, }; auto MeshRender = [&](ID3D11DeviceContext* context, BasicMaterial* customMaterial, Manager::RenderManager::MeshType type, MeshRenderOption option) { BasicMaterial* currentUseMaterial = nullptr; if(customMaterial && (option == MeshRenderOption::DepthWriteWithTest || option == MeshRenderOption::AlphaTest) ) ASSERT("Invalid Arg"); auto RenderIter = [&](BasicMaterial* material, Mesh::Mesh* mesh) { if(customMaterial) material = customMaterial; else if(option == MeshRenderOption::DepthWriteWithTest) { material = mesh->GetMeshRenderer()->GetDepthWriteMaterial(); customMaterial = material; } else if(option == MeshRenderOption::AlphaTest) { material = mesh->GetMeshRenderer()->GetAlphaTestMaterial(); customMaterial = material; } if(currentUseMaterial != material) { currentUseMaterial = material; currentUseMaterial->UpdateShader(context); } mesh->Render(customMaterial, _constBuffer); }; renderMgr->Iterate(RenderIter, type); }; //graphics part { ID3D11DeviceContext* context = dx->GetContext(); //Test { ID3D11RenderTargetView* rtv = dx->GetBackBuffer(); context->OMSetRenderTargets(1, &rtv, dx->GetDepthBuffer()->GetDepthStencilView()); context->ClearRenderTargetView(dx->GetBackBuffer(), _clearColor.color); dx->GetDepthBuffer()->Clear(1.0f, 0); MeshRender(context, nullptr, Manager::RenderManager::MeshType::nonAlpha, MeshRenderOption::Common); } //clear backbuffer, depthbuffer { //context->ClearRenderTargetView(dx->GetBackBuffer(), _clearColor.color); //dx->GetDepthBuffer()->Clear(0.0f, 0); //_depthBuffer->Clear(Rendering::Color::white(), dx); } //off alpha blending { //float blendFactor[1] = { 0.0f }; //context->OMSetBlendState(dx->GetOpaqueBlendState(), blendFactor, 0xffffffff); } //Render { /* ID3D11RenderTargetView* nullRTV = nullptr; ID3D11DepthStencilView* nullDSV = nullptr; ID3D11ShaderResourceView* nullSRV = nullptr; ID3D11UnorderedAccessView* nullUAV = nullptr; ID3D11SamplerState* nullSampler = nullptr;*/ //Early-Z { //ID3D11RenderTargetView* rtv = _depthBuffer->GetRenderTargetView(); //context->OMSetRenderTargets(1, &rtv, dx->GetDepthBuffer()->GetDepthStencilView()); //context->OMSetDepthStencilState(dx->GetDepthLessEqualState(), 0); //MeshRender(context, nullptr, RenderManager::MeshType::nonAlpha, MeshRenderOption::DepthWriteWithTest); //rtv = nullptr; //context->OMSetRenderTargets(1, &rtv, dx->GetDepthBuffer()->GetDepthStencilView()); //context->RSSetState(dx->GetDisableCullingRasterizerState()); //MeshRender(context, nullptr, RenderManager::MeshType::hasAlpha, MeshRenderOption::AlphaTest); //context->RSSetState(nullptr); } //Light Culling { Director* director = Director::GetInstance(); LightCulling* lightCullingCS = director->GetCurrentScene()->GetCameraManager()->GetLightCullingCS(); LightCulling::CullingConstBuffer cb; { // worldView { _owner->GetTransform()->WorldMatrix(cb.worldViewMat); Matrix view; ViewMatrix(view); cb.worldViewMat *= view; } // proj { ProjectionMatrix(cb.invProjMat); Matrix::Inverse(cb.invProjMat, cb.invProjMat); } // screenSize { cb.screenSize.x = static_cast<float>(director->GetWindowSize().w); cb.screenSize.y = static_cast<float>(director->GetWindowSize().h); } cb.clippingFar = _clippingFar; } //lightCullingCS->UpdateInputBuffer(cb, 0, 0); lightCullingCS->Dispatch(context, _depthBuffer); } //Forward Rendering { } } IDXGISwapChain* swapChain = dx->GetSwapChain(); swapChain->Present(0, 0); } } <|endoftext|>
<commit_before>#include "data-general.hpp" #include "data-course.hpp" #include "data-student.hpp" using namespace std; vector<Course> all_courses; Student user; void loadCourses() { ifstream infile("data/2012-13-s2-csv.csv"); string str; // read in the header line getline(infile, str); while (infile.peek() != -1){ Course incourse(infile); all_courses.push_back(incourse); // cout << incourse << endl; } // for (vector<Course>::iterator c = all_courses.begin(); c != all_courses.end(); ++c) // if (c->getProfessor()[1] == ' ') // if (c->getProfessor()[2] == '0' || c->getProfessor()[2] == '1') // c->displayMany(); } void whatDidICallThisWith(int argc, const char *argv[]) { printf ("This program was called with \"%s\".\n",argv[0]); if (argc > 1) for (int count = 1; count < argc; count++) printf("argv[%d] = %s\n", count, argv[count]); else printf("The command had no other arguments.\n"); } void welcome() { string name, yearS = "", yearE = "", majors; // cout << "Welcome!" << endl; // cout << "What is your name? "; // getline(cin, name); name = "Xandra Best"; // cout << "What year do you graduate? "; // cin >> yearE; // cout << "What are your majors (ex. CSCI, ASIAN) "; // getline(cin, majors); majors = "CSCI, STAT, ASIAN"; user = Student(name, yearS, yearE, majors); } void getCourses() { string courses; // cout << "What are some courses that you have taken? (ex. CSCI125, STAT 110)" << endl; // cout << "> "; // getline(cin, courses); courses = "PHIL 251A,PHIL 251B, REL 296A, REL 296B, STAT 110"; // courses = "CSCI 251, stat 110, THEAT398, writ211"; user.addCourses(courses); } int main(int argc, const char *argv[]) { loadCourses(); // cout << getCourse("STAT 10") << endl; // Course c("BIO 126"); // cout << c << endl; welcome(); getCourses(); user.display(); cout << "Question: Has the user taken CSCI 251? " << user.hasTakenCourse("CSCI251") << endl; return 0; } <commit_msg>More testcases (majors, this time)<commit_after>#include "data-general.hpp" #include "data-course.hpp" #include "data-student.hpp" using namespace std; vector<Course> all_courses; Student user; void loadCourses() { ifstream infile("data/2012-13-s2-csv.csv"); string str; // read in the header line getline(infile, str); while (infile.peek() != -1){ Course incourse(infile); all_courses.push_back(incourse); // cout << incourse << endl; } // for (vector<Course>::iterator c = all_courses.begin(); c != all_courses.end(); ++c) // if (c->getProfessor()[1] == ' ') // if (c->getProfessor()[2] == '0' || c->getProfessor()[2] == '1') // c->displayMany(); } void whatDidICallThisWith(int argc, const char *argv[]) { printf ("This program was called with \"%s\".\n",argv[0]); if (argc > 1) for (int count = 1; count < argc; count++) printf("argv[%d] = %s\n", count, argv[count]); else printf("The command had no other arguments.\n"); } void welcome() { string name, yearS = "", yearE = "", majors; // cout << "Welcome!" << endl; // cout << "What is your name? "; // getline(cin, name); name = "Xandra Best"; // cout << "What year do you graduate? "; // cin >> yearE; // cout << "What are your majors (ex. CSCI, ASIAN) "; // getline(cin, majors); majors = "CSCI, STAT, AsIaN, math"; user = Student(name, yearS, yearE, majors); } void getCourses() { string courses; // cout << "What are some courses that you have taken? (ex. CSCI125, STAT 110)" << endl; // cout << "> "; // getline(cin, courses); courses = "PHIL 251A,REL296A,rel 296b, STAT 110,"; courses += "CSCI251, stat 110, THEAT398, writ211"; user.addCourses(courses); } int main(int argc, const char *argv[]) { loadCourses(); // cout << getCourse("STAT 10") << endl; // Course c("BIO 126"); // cout << c << endl; welcome(); getCourses(); user.display(); cout << "Question: Has the user taken CSCI 251? " << user.hasTakenCourse("CSCI251") << endl; return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Nikhil Marathe ( nsm.nikhil@gmail.com ) * This file is distributed under the MIT License. Please see * LICENSE for details */ #include "taglib.h" #include <errno.h> #include <string.h> #include <v8.h> #include <node_buffer.h> #include <tfilestream.h> #include <asffile.h> #include <mpegfile.h> #include <vorbisfile.h> #include <flacfile.h> #include <oggflacfile.h> #include <mpcfile.h> #include <mp4file.h> #include <wavpackfile.h> #include <speexfile.h> #include <trueaudiofile.h> #include <aifffile.h> #include <wavfile.h> #include <apefile.h> #include <modfile.h> #include <s3mfile.h> #include <itfile.h> #include <xmfile.h> #include "audioproperties.h" #include "tag.h" #include "bufferstream.h" using namespace v8; using namespace node; using namespace node_taglib; namespace node_taglib { int CreateFileRefPath(TagLib::FileName path, TagLib::FileRef **ref) { TagLib::FileRef *f = NULL; int error = 0; if (!TagLib::File::isReadable(path)) { error = EACCES; } else { f = new TagLib::FileRef(path); if ( f->isNull() || !f->tag() ) { error = EINVAL; delete f; } } if (error != 0) *ref = NULL; else *ref = f; return error; } int CreateFileRef(TagLib::IOStream *stream, TagLib::String format, TagLib::FileRef **ref) { TagLib::FileRef *f = NULL; int error = 0; TagLib::File *file = createFile(stream, format); if (file == NULL) { *ref = NULL; return EBADF; } f = new TagLib::FileRef(file); if (f->isNull() || !f->tag()) { error = EINVAL; delete f; } if (error != 0) *ref = NULL; else *ref = f; return error; } TagLib::File *createFile(TagLib::IOStream *stream, TagLib::String format) { TagLib::File *file = 0; format = format.upper(); if (format == "MPEG") file = new TagLib::MPEG::File(stream, TagLib::ID3v2::FrameFactory::instance()); else if (format == "OGG") file = new TagLib::Ogg::Vorbis::File(stream); else if (format == "OGG/FLAC") file = new TagLib::Ogg::FLAC::File(stream); else if (format == "FLAC") file = new TagLib::FLAC::File(stream, TagLib::ID3v2::FrameFactory::instance()); else if (format == "MPC") file = new TagLib::MPC::File(stream); else if (format == "WV") file = new TagLib::WavPack::File(stream); else if (format == "SPX") file = new TagLib::Ogg::Speex::File(stream); else if (format == "TTA") file = new TagLib::TrueAudio::File(stream); else if (format == "MP4") file = new TagLib::MP4::File(stream); else if (format == "ASF") file = new TagLib::ASF::File(stream); else if (format == "AIFF") file = new TagLib::RIFF::AIFF::File(stream); else if (format == "WAV") file = new TagLib::RIFF::WAV::File(stream); else if (format == "APE") file = new TagLib::APE::File(stream); // module, nst and wow are possible but uncommon formatensions else if (format == "MOD") file = new TagLib::Mod::File(stream); else if (format == "S3M") file = new TagLib::S3M::File(stream); else if (format == "IT") file = new TagLib::IT::File(stream); else if (format == "XM") file = new TagLib::XM::File(stream); return file; } Local< String > ErrorToString(int error) { std::string err; switch (error) { case EACCES: err = "File is not readable"; break; case EINVAL: err = "Failed to extract tags"; break; case EBADF: err = "Unknown file format (check format string)"; break; default: err = "Unknown error"; break; } return Nan::New<String>(err).ToLocalChecked(); } void AsyncReadFile(const Nan::FunctionCallbackInfo< v8::Value >& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); if (args.Length() < 1) { Nan::ThrowError("Expected string or buffer as first argument"); return; } if (args[0]->IsString()) { if (args.Length() < 2 || !args[1]->IsFunction()) { Nan::ThrowError("Expected callback function as second argument"); return; } } else if (Buffer::HasInstance(args[0])) { if (args.Length() < 2 || !args[1]->IsString()) { Nan::ThrowError("Expected string 'format' as second argument"); return; } if (args.Length() < 3 || !args[2]->IsFunction()) { Nan::ThrowError("Expected callback function as third argument"); return; } } else { Nan::ThrowError("Expected string or buffer as first argument"); return; } AsyncBaton *baton = new AsyncBaton; baton->request.data = baton; baton->path = 0; baton->format = TagLib::String::null; baton->stream = 0; baton->error = 0; if (args[0]->IsString()) { String::Utf8Value path(args[0]->ToString()); baton->path = strdup(*path); baton->callback.Reset(Local<Function>::Cast(args[1])); } else { baton->format = NodeStringToTagLibString(args[1]->ToString()); baton->stream = new BufferStream(args[0]->ToObject()); baton->callback.Reset(Local<Function>::Cast(args[2])); } uv_queue_work(uv_default_loop(), &baton->request, AsyncReadFileDo, (uv_after_work_cb)AsyncReadFileAfter); args.GetReturnValue().SetUndefined(); } void AsyncReadFileDo(uv_work_t *req) { AsyncBaton *baton = static_cast<AsyncBaton*>(req->data); TagLib::FileRef *f; if (baton->path) { baton->error = node_taglib::CreateFileRefPath(baton->path, &f); } else { assert(baton->stream); baton->error = node_taglib::CreateFileRef(baton->stream, baton->format, &f); } if (baton->error == 0) { baton->fileRef = f; } } void AsyncReadFileAfter(uv_work_t *req) { AsyncBaton *baton = static_cast<AsyncBaton*>(req->data); if (baton->error) { Local<Object> error = Nan::New<Object>(); error->Set(Nan::New("code").ToLocalChecked(), Nan::New(baton->error)); error->Set(Nan::New("message").ToLocalChecked(), ErrorToString(baton->error)); Handle<Value> argv[] = { error, Nan::Null(), Nan::Null() }; Nan::Call(Nan::New(baton->callback), Nan::GetCurrentContext()->Global(), 3, argv); } else { // read the data, put it in objects and delete the fileref TagLib::Tag *tag = baton->fileRef->tag(); Local<Object> tagObj = Nan::New<Object>(); if (!tag->isEmpty()) { tagObj->Set(Nan::New("album").ToLocalChecked(), TagLibStringToString(tag->album())); tagObj->Set(Nan::New("artist").ToLocalChecked(), TagLibStringToString(tag->artist())); tagObj->Set(Nan::New("comment").ToLocalChecked(), TagLibStringToString(tag->comment())); tagObj->Set(Nan::New("genre").ToLocalChecked(), TagLibStringToString(tag->genre())); tagObj->Set(Nan::New("title").ToLocalChecked(), TagLibStringToString(tag->title())); tagObj->Set(Nan::New("track").ToLocalChecked(), Nan::New(tag->track())); tagObj->Set(Nan::New("year").ToLocalChecked(), Nan::New(tag->year())); } TagLib::AudioProperties *props = baton->fileRef->audioProperties(); Local<Object> propsObj = Nan::New<Object>(); if (props) { propsObj->Set(Nan::New("length").ToLocalChecked(), Nan::New(props->length())); propsObj->Set(Nan::New("bitrate").ToLocalChecked(), Nan::New(props->bitrate())); propsObj->Set(Nan::New("sampleRate").ToLocalChecked(), Nan::New(props->sampleRate())); propsObj->Set(Nan::New("channels").ToLocalChecked(), Nan::New(props->channels())); } Handle<Value> argv[] = { Nan::Null(), tagObj, propsObj }; Nan::Call(Nan::New(baton->callback), Nan::GetCurrentContext()->Global(), 3, argv); delete baton->fileRef; delete baton; baton = NULL; } } Local< Value > TagLibStringToString( TagLib::String s ) { if(s.isEmpty()) { return Nan::Null(); } else { TagLib::ByteVector str = s.data(TagLib::String::UTF16); // Strip the Byte Order Mark of the input to avoid node adding a UTF-8 // Byte Order Mark return Nan::New<v8::String>((uint16_t *)str.mid(2,str.size()-2).data(), s.size()).ToLocalChecked(); } } TagLib::String NodeStringToTagLibString( Local<Value> s ) { if(s->IsNull()) { return TagLib::String::null; } else { String::Utf8Value str(s->ToString()); return TagLib::String(*str, TagLib::String::UTF8); } } void AddResolvers(const Nan::FunctionCallbackInfo<Value> &args) { for (int i = 0; i < args.Length(); i++) { Local<Value> arg = args[i]; if (arg->IsFunction()) { Local<Function> resolver = Local<Function>::Cast(arg); TagLib::FileRef::addFileTypeResolver(new CallbackResolver(resolver)); } } args.GetReturnValue().SetUndefined(); } CallbackResolver::CallbackResolver(Local< Function > func) : TagLib::FileRef::FileTypeResolver() , resolverFunc(func) // the constructor is always called in the v8 thread #ifdef _WIN32 , created_in(GetCurrentThreadId()) #else , created_in(pthread_self()) #endif { } void CallbackResolver::invokeResolverCb(uv_async_t *handle) { AsyncResolverBaton *baton = (AsyncResolverBaton *) handle->data; invokeResolver(baton); uv_async_send((uv_async_t*) &baton->idler); uv_close((uv_handle_t*)&baton->request, 0); } void CallbackResolver::stopIdling(uv_async_t *handle) { uv_close((uv_handle_t*) handle, 0); } void CallbackResolver::invokeResolver(AsyncResolverBaton *baton) { Nan::HandleScope scope; Handle<Value> argv[] = { TagLibStringToString(baton->fileName) }; Local<Value> ret = Nan::Call(Nan::New(baton->resolver->resolverFunc), Nan::GetCurrentContext()->Global(), 1, argv).ToLocalChecked(); if (!ret->IsString()) { baton->type = TagLib::String::null; } else { baton->type = NodeStringToTagLibString(ret->ToString()).upper(); } } TagLib::File *CallbackResolver::createFile(TagLib::FileName fileName, bool readAudioProperties, TagLib::AudioProperties::ReadStyle audioPropertiesStyle) const { AsyncResolverBaton baton; baton.request.data = (void *) &baton; baton.resolver = this; baton.fileName = fileName; #ifdef _WIN32 if (created_in != GetCurrentThreadId()) { #else if (created_in != pthread_self()) { #endif uv_loop_t *wait_loop = uv_loop_new(); uv_async_init(wait_loop, &baton.idler, CallbackResolver::stopIdling); uv_async_init(uv_default_loop(), &baton.request, invokeResolverCb); uv_async_send(&baton.request); uv_run(wait_loop, UV_RUN_DEFAULT); uv_loop_delete(wait_loop); } else { invokeResolver(&baton); } TagLib::FileStream *stream = new TagLib::FileStream(fileName); return node_taglib::createFile(stream, baton.type); } } extern "C" { static void init (Handle<Object> target) { Nan::HandleScope scope; #ifdef TAGLIB_WITH_ASF Nan::Set(target, Nan::New("WITH_ASF").ToLocalChecked(), Nan::True()); #else Nan::Set(target, Nan::New("WITH_ASF").ToLocalChecked(), Nan::False()); #endif #ifdef TAGLIB_WITH_MP4 Nan::Set(target, Nan::New("WITH_MP4").ToLocalChecked(), Nan::True()); #else Nan::Set(target, Nan::New("WITH_MP4").ToLocalChecked(), Nan::False()); #endif Nan::SetMethod(target, "read", AsyncReadFile); #ifdef ENABLE_RESOLVERS Nan::SetMethod(target, "addResolvers", AddResolvers); #endif Tag::Init(target); } NODE_MODULE(taglib, init) } <commit_msg>Fix "Cannot create a handle without a HandleScope" in AsyncReadFileAfter()<commit_after>/* * Copyright (C) 2009 Nikhil Marathe ( nsm.nikhil@gmail.com ) * This file is distributed under the MIT License. Please see * LICENSE for details */ #include "taglib.h" #include <errno.h> #include <string.h> #include <v8.h> #include <node_buffer.h> #include <tfilestream.h> #include <asffile.h> #include <mpegfile.h> #include <vorbisfile.h> #include <flacfile.h> #include <oggflacfile.h> #include <mpcfile.h> #include <mp4file.h> #include <wavpackfile.h> #include <speexfile.h> #include <trueaudiofile.h> #include <aifffile.h> #include <wavfile.h> #include <apefile.h> #include <modfile.h> #include <s3mfile.h> #include <itfile.h> #include <xmfile.h> #include "audioproperties.h" #include "tag.h" #include "bufferstream.h" using namespace v8; using namespace node; using namespace node_taglib; namespace node_taglib { int CreateFileRefPath(TagLib::FileName path, TagLib::FileRef **ref) { TagLib::FileRef *f = NULL; int error = 0; if (!TagLib::File::isReadable(path)) { error = EACCES; } else { f = new TagLib::FileRef(path); if ( f->isNull() || !f->tag() ) { error = EINVAL; delete f; } } if (error != 0) *ref = NULL; else *ref = f; return error; } int CreateFileRef(TagLib::IOStream *stream, TagLib::String format, TagLib::FileRef **ref) { TagLib::FileRef *f = NULL; int error = 0; TagLib::File *file = createFile(stream, format); if (file == NULL) { *ref = NULL; return EBADF; } f = new TagLib::FileRef(file); if (f->isNull() || !f->tag()) { error = EINVAL; delete f; } if (error != 0) *ref = NULL; else *ref = f; return error; } TagLib::File *createFile(TagLib::IOStream *stream, TagLib::String format) { TagLib::File *file = 0; format = format.upper(); if (format == "MPEG") file = new TagLib::MPEG::File(stream, TagLib::ID3v2::FrameFactory::instance()); else if (format == "OGG") file = new TagLib::Ogg::Vorbis::File(stream); else if (format == "OGG/FLAC") file = new TagLib::Ogg::FLAC::File(stream); else if (format == "FLAC") file = new TagLib::FLAC::File(stream, TagLib::ID3v2::FrameFactory::instance()); else if (format == "MPC") file = new TagLib::MPC::File(stream); else if (format == "WV") file = new TagLib::WavPack::File(stream); else if (format == "SPX") file = new TagLib::Ogg::Speex::File(stream); else if (format == "TTA") file = new TagLib::TrueAudio::File(stream); else if (format == "MP4") file = new TagLib::MP4::File(stream); else if (format == "ASF") file = new TagLib::ASF::File(stream); else if (format == "AIFF") file = new TagLib::RIFF::AIFF::File(stream); else if (format == "WAV") file = new TagLib::RIFF::WAV::File(stream); else if (format == "APE") file = new TagLib::APE::File(stream); // module, nst and wow are possible but uncommon formatensions else if (format == "MOD") file = new TagLib::Mod::File(stream); else if (format == "S3M") file = new TagLib::S3M::File(stream); else if (format == "IT") file = new TagLib::IT::File(stream); else if (format == "XM") file = new TagLib::XM::File(stream); return file; } Local< String > ErrorToString(int error) { std::string err; switch (error) { case EACCES: err = "File is not readable"; break; case EINVAL: err = "Failed to extract tags"; break; case EBADF: err = "Unknown file format (check format string)"; break; default: err = "Unknown error"; break; } return Nan::New<String>(err).ToLocalChecked(); } void AsyncReadFile(const Nan::FunctionCallbackInfo< v8::Value >& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); if (args.Length() < 1) { Nan::ThrowError("Expected string or buffer as first argument"); return; } if (args[0]->IsString()) { if (args.Length() < 2 || !args[1]->IsFunction()) { Nan::ThrowError("Expected callback function as second argument"); return; } } else if (Buffer::HasInstance(args[0])) { if (args.Length() < 2 || !args[1]->IsString()) { Nan::ThrowError("Expected string 'format' as second argument"); return; } if (args.Length() < 3 || !args[2]->IsFunction()) { Nan::ThrowError("Expected callback function as third argument"); return; } } else { Nan::ThrowError("Expected string or buffer as first argument"); return; } AsyncBaton *baton = new AsyncBaton; baton->request.data = baton; baton->path = 0; baton->format = TagLib::String::null; baton->stream = 0; baton->error = 0; if (args[0]->IsString()) { String::Utf8Value path(args[0]->ToString()); baton->path = strdup(*path); baton->callback.Reset(Local<Function>::Cast(args[1])); } else { baton->format = NodeStringToTagLibString(args[1]->ToString()); baton->stream = new BufferStream(args[0]->ToObject()); baton->callback.Reset(Local<Function>::Cast(args[2])); } uv_queue_work(uv_default_loop(), &baton->request, AsyncReadFileDo, (uv_after_work_cb)AsyncReadFileAfter); args.GetReturnValue().SetUndefined(); } void AsyncReadFileDo(uv_work_t *req) { AsyncBaton *baton = static_cast<AsyncBaton*>(req->data); TagLib::FileRef *f; if (baton->path) { baton->error = node_taglib::CreateFileRefPath(baton->path, &f); } else { assert(baton->stream); baton->error = node_taglib::CreateFileRef(baton->stream, baton->format, &f); } if (baton->error == 0) { baton->fileRef = f; } } void AsyncReadFileAfter(uv_work_t *req) { AsyncBaton *baton = static_cast<AsyncBaton*>(req->data); Nan::HandleScope scope; if (baton->error) { Local<Object> error = Nan::New<Object>(); error->Set(Nan::New("code").ToLocalChecked(), Nan::New(baton->error)); error->Set(Nan::New("message").ToLocalChecked(), ErrorToString(baton->error)); Handle<Value> argv[] = { error, Nan::Null(), Nan::Null() }; Nan::Call(Nan::New(baton->callback), Nan::GetCurrentContext()->Global(), 3, argv); } else { // read the data, put it in objects and delete the fileref TagLib::Tag *tag = baton->fileRef->tag(); Local<Object> tagObj = Nan::New<Object>(); if (!tag->isEmpty()) { tagObj->Set(Nan::New("album").ToLocalChecked(), TagLibStringToString(tag->album())); tagObj->Set(Nan::New("artist").ToLocalChecked(), TagLibStringToString(tag->artist())); tagObj->Set(Nan::New("comment").ToLocalChecked(), TagLibStringToString(tag->comment())); tagObj->Set(Nan::New("genre").ToLocalChecked(), TagLibStringToString(tag->genre())); tagObj->Set(Nan::New("title").ToLocalChecked(), TagLibStringToString(tag->title())); tagObj->Set(Nan::New("track").ToLocalChecked(), Nan::New(tag->track())); tagObj->Set(Nan::New("year").ToLocalChecked(), Nan::New(tag->year())); } TagLib::AudioProperties *props = baton->fileRef->audioProperties(); Local<Object> propsObj = Nan::New<Object>(); if (props) { propsObj->Set(Nan::New("length").ToLocalChecked(), Nan::New(props->length())); propsObj->Set(Nan::New("bitrate").ToLocalChecked(), Nan::New(props->bitrate())); propsObj->Set(Nan::New("sampleRate").ToLocalChecked(), Nan::New(props->sampleRate())); propsObj->Set(Nan::New("channels").ToLocalChecked(), Nan::New(props->channels())); } Handle<Value> argv[] = { Nan::Null(), tagObj, propsObj }; Nan::Call(Nan::New(baton->callback), Nan::GetCurrentContext()->Global(), 3, argv); delete baton->fileRef; delete baton; baton = NULL; } } Local< Value > TagLibStringToString( TagLib::String s ) { if(s.isEmpty()) { return Nan::Null(); } else { TagLib::ByteVector str = s.data(TagLib::String::UTF16); // Strip the Byte Order Mark of the input to avoid node adding a UTF-8 // Byte Order Mark return Nan::New<v8::String>((uint16_t *)str.mid(2,str.size()-2).data(), s.size()).ToLocalChecked(); } } TagLib::String NodeStringToTagLibString( Local<Value> s ) { if(s->IsNull()) { return TagLib::String::null; } else { String::Utf8Value str(s->ToString()); return TagLib::String(*str, TagLib::String::UTF8); } } void AddResolvers(const Nan::FunctionCallbackInfo<Value> &args) { for (int i = 0; i < args.Length(); i++) { Local<Value> arg = args[i]; if (arg->IsFunction()) { Local<Function> resolver = Local<Function>::Cast(arg); TagLib::FileRef::addFileTypeResolver(new CallbackResolver(resolver)); } } args.GetReturnValue().SetUndefined(); } CallbackResolver::CallbackResolver(Local< Function > func) : TagLib::FileRef::FileTypeResolver() , resolverFunc(func) // the constructor is always called in the v8 thread #ifdef _WIN32 , created_in(GetCurrentThreadId()) #else , created_in(pthread_self()) #endif { } void CallbackResolver::invokeResolverCb(uv_async_t *handle) { AsyncResolverBaton *baton = (AsyncResolverBaton *) handle->data; invokeResolver(baton); uv_async_send((uv_async_t*) &baton->idler); uv_close((uv_handle_t*)&baton->request, 0); } void CallbackResolver::stopIdling(uv_async_t *handle) { uv_close((uv_handle_t*) handle, 0); } void CallbackResolver::invokeResolver(AsyncResolverBaton *baton) { Nan::HandleScope scope; Handle<Value> argv[] = { TagLibStringToString(baton->fileName) }; Local<Value> ret = Nan::Call(Nan::New(baton->resolver->resolverFunc), Nan::GetCurrentContext()->Global(), 1, argv).ToLocalChecked(); if (!ret->IsString()) { baton->type = TagLib::String::null; } else { baton->type = NodeStringToTagLibString(ret->ToString()).upper(); } } TagLib::File *CallbackResolver::createFile(TagLib::FileName fileName, bool readAudioProperties, TagLib::AudioProperties::ReadStyle audioPropertiesStyle) const { AsyncResolverBaton baton; baton.request.data = (void *) &baton; baton.resolver = this; baton.fileName = fileName; #ifdef _WIN32 if (created_in != GetCurrentThreadId()) { #else if (created_in != pthread_self()) { #endif uv_loop_t *wait_loop = uv_loop_new(); uv_async_init(wait_loop, &baton.idler, CallbackResolver::stopIdling); uv_async_init(uv_default_loop(), &baton.request, invokeResolverCb); uv_async_send(&baton.request); uv_run(wait_loop, UV_RUN_DEFAULT); uv_loop_delete(wait_loop); } else { invokeResolver(&baton); } TagLib::FileStream *stream = new TagLib::FileStream(fileName); return node_taglib::createFile(stream, baton.type); } } extern "C" { static void init (Handle<Object> target) { Nan::HandleScope scope; #ifdef TAGLIB_WITH_ASF Nan::Set(target, Nan::New("WITH_ASF").ToLocalChecked(), Nan::True()); #else Nan::Set(target, Nan::New("WITH_ASF").ToLocalChecked(), Nan::False()); #endif #ifdef TAGLIB_WITH_MP4 Nan::Set(target, Nan::New("WITH_MP4").ToLocalChecked(), Nan::True()); #else Nan::Set(target, Nan::New("WITH_MP4").ToLocalChecked(), Nan::False()); #endif Nan::SetMethod(target, "read", AsyncReadFile); #ifdef ENABLE_RESOLVERS Nan::SetMethod(target, "addResolvers", AddResolvers); #endif Tag::Init(target); } NODE_MODULE(taglib, init) } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: precompiled_vcl.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2007-05-10 16:29:13 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): Generated on 2006-09-01 17:50:18.342046 #ifdef PRECOMPILED_HEADERS #include <tools/debug.hxx> #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.296); FILE MERGED 2008/03/28 15:44:08 rt 1.3.296.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: precompiled_vcl.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): Generated on 2006-09-01 17:50:18.342046 #ifdef PRECOMPILED_HEADERS #include <tools/debug.hxx> #endif <|endoftext|>
<commit_before>#include <iostream> #include <iomanip> #include <string> #include <fstream> #include <vector> #include <array> #include <cmath> #include <numeric> #include <algorithm> #include <immintrin.h> /*#include <boost/filesystem/fstream.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/gzip.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <mongo/client/dbclient.h> #include <Poco/Net/MailMessage.h> #include <Poco/Net/MailRecipient.h> #include <Poco/Net/SMTPClientSession.h>*/ using namespace std; /*using namespace std::chrono; using namespace boost::filesystem; using namespace boost::iostreams; using namespace boost::gregorian; using namespace boost::posix_time; using namespace mongo; using namespace bson; using namespace Poco::Net;*/ /*inline static string now() { return to_simple_string(second_clock::local_time()) + " "; }*/ vector<double> parse(const string& line) { vector<double> r; if (line.size()) { r.reserve(12); for (size_t b = 0, e; true; b = e + 1) { if ((e = line.find(',', b + 6)) == string::npos) { r.push_back(stof(line.substr(b))); break; } r.push_back(stof(line.substr(b, e - b))); } } return r; } int main(int argc, char* argv[]) { /* // Check the required number of command line arguments. if (argc != 5) { cout << "usr host user pwd jobs_path" << endl; return 0; } // Fetch command line arguments. const auto host = argv[1]; const auto user = argv[2]; const auto pwd = argv[3]; const path jobs_path = argv[4]; DBClientConnection conn; { // Connect to host and authenticate user. cout << now() << "Connecting to " << host << " and authenticating " << user << endl; string errmsg; if ((!conn.connect(host, errmsg)) || (!conn.auth("istar", user, pwd, errmsg))) { cerr << now() << errmsg << endl; return 1; } } const auto collection = "istar.usr";*/ const auto m256s = _mm256_set1_pd(-0. ); // -0. = 1 << 63 // Read the feature file. string line; vector<vector<double>> features; features.reserve(23129083); for (ifstream ifs(argv[1]); getline(ifs, line); features.push_back(parse(line))); const size_t n = features.size(); // Read the header file. vector<string> headers; headers.reserve(n); for (ifstream ifs(argv[2]); getline(ifs, line); headers.push_back(move(line))); // Search the features for records similar to each of the queries. vector<double> scores(n); vector<size_t> scase(n); array<double, 4> a; cout.setf(ios::fixed, ios::floatfield); cout << setprecision(4); const double qv = 1.0 / 12; while (getline(cin, line)) { const auto& q = parse(line); for (size_t k = 0; k < n; ++k) { const auto& l = features[k]; double s = 0; for (size_t i = 0; i < 12; i += 4) { _mm256_stream_pd(a.data(), _mm256_andnot_pd(m256s, _mm256_sub_pd(_mm256_load_pd(&q[i]), _mm256_load_pd(&l[i])))); s += a[0] + a[1] + a[2] + a[3]; } scores[k] = 1 / (1 + s * qv); } iota(scase.begin(), scase.end(), 0); sort(scase.begin(), scase.end(), [&scores](const size_t val1, const size_t val2) { return scores[val1] > scores[val2]; }); for (const size_t c : scase) { cout << c << '\t' << headers[c] << '\t' << scores[c] << endl; } } /* // Initialize epoch const auto epoch = date(1970, 1, 1); while (true) { // Fetch jobs. auto cursor = conn.query(collection, QUERY("done" << BSON("$exists" << false)).sort("submitted"), 100); // Each batch processes 100 jobs. while (cursor->more()) { const auto job = cursor->next(); const auto _id = job["_id"].OID(); cout << now() << "Executing job " << _id.str() << endl; // Obtain the target genome via taxid. const auto ligand = job["ligand"].Int(); // Update progress. const auto millis_since_epoch = duration_cast<std::chrono::milliseconds>(system_clock::now().time_since_epoch()).count(); conn.update(collection, BSON("_id" << _id), BSON("$set" << BSON("done" << Date_t(millis_since_epoch)))); const auto err = conn.getLastError(); if (!err.empty()) { cerr << now() << err << endl; } // Send completion notification email. const auto email = job["email"].String(); cout << now() << "Sending a completion notification email to " << email << endl; MailMessage message; message.setSender("igrep <noreply@cse.cuhk.edu.hk>"); message.setSubject("Your igrep job has completed"); message.setContent("Your igrep job submitted on " + to_simple_string(ptime(epoch, boost::posix_time::milliseconds(job["submitted"].Date().millis))) + " UTC searching the genome of " + g.name + " for " + to_string(qi) + " patterns was done on " + to_simple_string(ptime(epoch, boost::posix_time::milliseconds(millis_since_epoch))) + " UTC. View result at http://istar.cse.cuhk.edu.hk/igrep"); message.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, email)); SMTPClientSession session("137.189.91.190"); session.login(); session.sendMessage(message); session.close(); } // Sleep for a while. this_thread::sleep_for(std::chrono::seconds(10)); }*/ } <commit_msg>Implemented a prototype usr.cpp<commit_after>#include <iostream> #include <iomanip> #include <string> #include <fstream> #include <vector> #include <array> #include <cmath> #include <numeric> #include <algorithm> #include <cassert> #include <chrono> #include <thread> #include <immintrin.h> /*#include <boost/filesystem/fstream.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/gzip.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <mongo/client/dbclient.h> #include <Poco/Net/MailMessage.h> #include <Poco/Net/MailRecipient.h> #include <Poco/Net/SMTPClientSession.h>*/ using namespace std; /*using namespace std::chrono; using namespace boost::filesystem; using namespace boost::iostreams; using namespace boost::gregorian; using namespace boost::posix_time; using namespace mongo; using namespace bson; using namespace Poco::Net;*/ /*inline static string now() { return to_simple_string(second_clock::local_time()) + " "; }*/ template <typename T> void read(vector<T>& v, const string f) { ifstream ifs(f, ifstream::binary); ifs.seekg(0, ifstream::end); const size_t num_bytes = ifs.tellg(); v.resize(num_bytes / sizeof(T)); ifs.seekg(0); ifs.read(reinterpret_cast<char*>(v.data()), num_bytes); } int main(int argc, char* argv[]) { /* // Check the required number of command line arguments. if (argc != 5) { cout << "usr host user pwd jobs_path" << endl; return 0; } // Fetch command line arguments. const auto host = argv[1]; const auto user = argv[2]; const auto pwd = argv[3]; const path jobs_path = argv[4]; DBClientConnection conn; { // Connect to host and authenticate user. cout << now() << "Connecting to " << host << " and authenticating " << user << endl; string errmsg; if ((!conn.connect(host, errmsg)) || (!conn.auth("istar", user, pwd, errmsg))) { cerr << now() << errmsg << endl; return 1; } } const auto collection = "istar.usr";*/ const auto m256s = _mm256_set1_pd(-0. ); // -0. = 1 << 63 const double qv = 1.0 / 12; // const auto epoch = date(1970, 1, 1); // Read the feature bin file. vector<array<double, 12>> features; read(features, "16_usr.bin"); const size_t n = features.size(); // Read the header bin file. /* vector<size_t> headers; read(headers, "16_hdr.bin"); assert(n == headers.size());*/ // Search the features for records similar to the query. cout.setf(ios::fixed, ios::floatfield); cout << setprecision(4); vector<double> scores(n); vector<size_t> scase(n); array<double, 4> a; while (true) { /* // Fetch jobs. auto cursor = conn.query(collection, QUERY("done" << BSON("$exists" << false)).sort("submitted"), 100); // Each batch processes 100 jobs. while (cursor->more()) { const auto job = cursor->next(); const auto _id = job["_id"].OID(); cout << now() << "Executing job " << _id.str() << endl; // Obtain the target genome via taxid. const auto ligand = job["ligand"].Int(); // Update progress. const auto millis_since_epoch = duration_cast<std::chrono::milliseconds>(system_clock::now().time_since_epoch()).count(); conn.update(collection, BSON("_id" << _id), BSON("$set" << BSON("done" << Date_t(millis_since_epoch)))); const auto err = conn.getLastError(); if (!err.empty()) { cerr << now() << err << endl; } // Send completion notification email. const auto email = job["email"].String(); cout << now() << "Sending a completion notification email to " << email << endl; MailMessage message; message.setSender("igrep <noreply@cse.cuhk.edu.hk>"); message.setSubject("Your igrep job has completed"); message.setContent("Your igrep job submitted on " + to_simple_string(ptime(epoch, boost::posix_time::milliseconds(job["submitted"].Date().millis))) + " UTC searching the genome of " + g.name + " for " + to_string(qi) + " patterns was done on " + to_simple_string(ptime(epoch, boost::posix_time::milliseconds(millis_since_epoch))) + " UTC. View result at http://istar.cse.cuhk.edu.hk/igrep"); message.addRecipient(MailRecipient(MailRecipient::PRIMARY_RECIPIENT, email)); SMTPClientSession session("137.189.91.190"); session.login(); session.sendMessage(message); session.close(); }*/ const array<double, 12> q = { 2.8676,1.1022,-0.5600,2.8974,1.2106,-0.6881,5.1474,2.3391,-2.0920,4.6221,2.0675,-1.1042 }; for (size_t k = 0; k < n; ++k) { const auto& l = features[k]; double s = 0; for (size_t i = 0; i < 12; i += 4) { const auto m256a = _mm256_andnot_pd(m256s, _mm256_sub_pd(_mm256_load_pd(&q[i]), _mm256_load_pd(&l[i]))); _mm256_stream_pd(a.data(), _mm256_hadd_pd(m256a, m256a)); s += a[0] + a[2]; } scores[k] = 1 / (1 + s * qv); } iota(scase.begin(), scase.end(), 0); sort(scase.begin(), scase.end(), [&scores](const size_t val1, const size_t val2) { return scores[val1] > scores[val2]; }); for (const size_t c : scase) { cout << c << '\t' << scores[c] << endl; } break; // Sleep for a while. this_thread::sleep_for(std::chrono::seconds(10)); } } <|endoftext|>
<commit_before>#ifndef TISYS_HPP #define TISYS_HPP #include <tiobj.hpp> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> std::string path_add(std::string base, std::string add1); std::string path_add(std::string base, std::string add1, std::string add2); std::string path_add(std::string base, std::string add1, std::string add2, std::string add3); std::string path_remove (std::string url); std::string path_last (std::string url); std::string path_absolute(std::string url); std::string path_context (std::string classe, std::string _url="."); void tiurl_explode(TiObj& out, std::string tiurl); void tiurl_sysobj (TiObj& out, std::string tiurl); int csystem(std::string cmd); class Filesystem { public: TiObj cache; private: std::string root; std::string cur_path; std::string status_func; std::string status_msg; int status_code; public: Filesystem(); Filesystem(std::string cur_path, string root=""); bool listdir (TiObj& out, std::string url="."); inline bool listdir (std::string url="."){return this->listdir(this->cache, url);} bool listdirtree(TiObj& out, std::string url="."); bool info (TiObj& out, std::string url="."); //bool select(TiObj& out, string query, string url); bool newfolder(std::string url, mode_t mode=0755); bool newfile (std::string url, mode_t mode=0644); bool newlink(std::string to, std::string in=""); bool rm (std::string url); bool rmdir (std::string url); bool rmtree(std::string url); bool cp (std::string from, std::string to); bool cptree(std::string from, std::string to); bool mv (std::string from, std::string to); bool rename(std::string old, std::string novo); bool node_exist (std::string url); inline bool exists (std::string url){return this->node_exist(url);} bool node_isfolder(std::string url); bool node_isfile (std::string url); bool node_islink (std::string url); bool node_isblock (std::string url); std::string node_type (std::string url); bool mount (); bool umount(); std::string last_error(); std::string file_type (std::string url); std::string folder_type(std::string url); private: void error(std::string msg); void log (std::string function); std::string path_set (std::string url); }; class Objsystem : public Filesystem { bool list (TiObj& out, std::string tiurl); bool list (TiObj& out, std::string query, std::string tiurl); bool listtree(TiObj& out, std::string query, std::string tiurl); bool info (TiObj& out, std::string tiurl); //bool context (std::string url); bool mkobj(std::string tiurl, TiObj& data); }; class System { bool listDevice (TiObj& out); bool listDeviceBlock (TiObj& out); bool listDeviceEthernet (TiObj& out); bool listDeviceVideo (TiObj& out); bool listDeviceInputVideo (TiObj& out); bool listDeviceAudio (TiObj& out); bool listDeviceInputAudio (TiObj& out); bool listUser (TiObj& out); bool listCmd (TiObj& out); bool listWifi (TiObj& out); //bool listLib(); }; class TiProcess { std::string buf_send; std::string buf_recv; std::string lasterror; FILE *wstream; FILE *rstream; pid_t id; public: ~TiProcess(); bool start(std::string cmd); int exec (std::string& out, std::string cmd); void send (std::string data); void recv (std::string& out); int recvAll(std::string& out); void recvObj(); void flush(); int wait (); void finalize(); }; /*namespace TiSys{ // Gerenciamento de Path std::string path_add(std::string base, std::string add1); std::string path_add(std::string base, std::string add1, std::string add2); std::string path_add(std::string base, std::string add1, std::string add2, std::string add3); std::string path_remove(std::string url); std::string path_last(std::string url); std::string path_absolute (std::string url); int newFolder(std::string path, mode_t mode=0755); bool existNode(std::string url); bool isFolder(std::string url); bool isFile(std::string url); int info(TiObj& out, std::string filename, std::string base=""); string getCtx(string classe, string _url=""); void getArgs(TiObj& out, int argc, char** argv); string getUrl(string tiurl); void listUsers(TiObj& out); void listBlockDevice(TiObj& out); bool listRecursive( TiObj& out, std::string classe, std::string url, std::string base="."); }*/ #endif <commit_msg>adicionado cache na funcao info<commit_after>#ifndef TISYS_HPP #define TISYS_HPP #include <tiobj.hpp> #include <string.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> std::string path_add(std::string base, std::string add1); std::string path_add(std::string base, std::string add1, std::string add2); std::string path_add(std::string base, std::string add1, std::string add2, std::string add3); std::string path_remove (std::string url); std::string path_last (std::string url); std::string path_absolute(std::string url); std::string path_context (std::string classe, std::string _url="."); void tiurl_explode(TiObj& out, std::string tiurl); void tiurl_sysobj (TiObj& out, std::string tiurl); int csystem(std::string cmd); class Filesystem { public: TiObj cache; private: std::string root; std::string cur_path; std::string status_func; std::string status_msg; int status_code; public: Filesystem(); Filesystem(std::string cur_path, string root=""); bool listdir (TiObj& out, std::string url="."); inline bool listdir (std::string url="."){return this->listdir(this->cache, url);} bool listdirtree (TiObj& out, std::string url="."); bool info (TiObj& out, std::string url="."); inline bool info (std::string url="."){return this->info(this->cache, url);} //bool select(TiObj& out, string query, string url); bool newfolder(std::string url, mode_t mode=0755); bool newfile (std::string url, mode_t mode=0644); bool newlink(std::string to, std::string in=""); bool rm (std::string url); bool rmdir (std::string url); bool rmtree(std::string url); bool cp (std::string from, std::string to); bool cptree(std::string from, std::string to); bool mv (std::string from, std::string to); bool rename(std::string old, std::string novo); bool node_exist (std::string url); inline bool exists (std::string url){return this->node_exist(url);} bool node_isfolder(std::string url); bool node_isfile (std::string url); bool node_islink (std::string url); bool node_isblock (std::string url); std::string node_type (std::string url); bool mount (); bool umount(); std::string last_error(); std::string file_type (std::string url); std::string folder_type(std::string url); private: void error(std::string msg); void log (std::string function); std::string path_set (std::string url); }; class Objsystem : public Filesystem { bool list (TiObj& out, std::string tiurl); bool list (TiObj& out, std::string query, std::string tiurl); bool listtree(TiObj& out, std::string query, std::string tiurl); bool info (TiObj& out, std::string tiurl); //bool context (std::string url); bool mkobj(std::string tiurl, TiObj& data); }; class System { bool listDevice (TiObj& out); bool listDeviceBlock (TiObj& out); bool listDeviceEthernet (TiObj& out); bool listDeviceVideo (TiObj& out); bool listDeviceInputVideo (TiObj& out); bool listDeviceAudio (TiObj& out); bool listDeviceInputAudio (TiObj& out); bool listUser (TiObj& out); bool listCmd (TiObj& out); bool listWifi (TiObj& out); //bool listLib(); }; class TiProcess { std::string buf_send; std::string buf_recv; std::string lasterror; FILE *wstream; FILE *rstream; pid_t id; public: ~TiProcess(); bool start(std::string cmd); int exec (std::string& out, std::string cmd); void send (std::string data); void recv (std::string& out); int recvAll(std::string& out); void recvObj(); void flush(); int wait (); void finalize(); }; /*namespace TiSys{ // Gerenciamento de Path std::string path_add(std::string base, std::string add1); std::string path_add(std::string base, std::string add1, std::string add2); std::string path_add(std::string base, std::string add1, std::string add2, std::string add3); std::string path_remove(std::string url); std::string path_last(std::string url); std::string path_absolute (std::string url); int newFolder(std::string path, mode_t mode=0755); bool existNode(std::string url); bool isFolder(std::string url); bool isFile(std::string url); int info(TiObj& out, std::string filename, std::string base=""); string getCtx(string classe, string _url=""); void getArgs(TiObj& out, int argc, char** argv); string getUrl(string tiurl); void listUsers(TiObj& out); void listBlockDevice(TiObj& out); bool listRecursive( TiObj& out, std::string classe, std::string url, std::string base="."); }*/ #endif <|endoftext|>
<commit_before>#include <ros/ros.h> #include <iostream> #include <sstream> #include <ctime> #include <sensor_msgs/PointCloud2.h> #include <std_msgs/Bool.h> #include <pcl/ros/conversions.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/filters/filter.h> #include <pcl/filters/voxel_grid.h> ros::NodeHandle *nh; ros::Rate * loop_rate; ros::Subscriber cameraSubscriber; ros::Subscriber startAcquisition; ros::Publisher voxelizedPC; //define a queue cloud that will be published only when the rate says it sensor_msgs::PointCloud2::Ptr queuedCloud (new sensor_msgs::PointCloud2 ()); void cloud_cb(const sensor_msgs::PointCloud2ConstPtr& msg); void acquisitionCamera(const std_msgs::Bool msg) { if(msg.data == true) { ROS_INFO("Start pointcloud publishing"); cameraSubscriber = nh->subscribe <sensor_msgs::PointCloud2> ("/camera/depth_registered/points",1,cloud_cb); } else { ROS_INFO("Stop pointcloud publishing"); cameraSubscriber.shutdown(); } } void cloud_cb(const sensor_msgs::PointCloud2ConstPtr& msg) { pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>()); sensor_msgs::PointCloud2::Ptr cloud_downsampled (new sensor_msgs::PointCloud2 ()); pcl::fromROSMsg(*msg,*cloud); // Create the filtering object pcl::VoxelGrid<sensor_msgs::PointCloud2> sor; sor.setInputCloud (msg); sor.setLeafSize (0.01, 0.01, 0.01); sor.filter (*cloud_downsampled); *queuedCloud = *cloud_downsampled; } int main(int argc, char ** argv) { ros::init(argc,argv,"pcl_stream"); nh = new ros::NodeHandle(); loop_rate = new ros::Rate(1); startAcquisition = nh->subscribe<std_msgs::Bool>("/camera/startAcquisition",1,acquisitionCamera); voxelizedPC = nh->advertise<sensor_msgs::PointCloud2>("/camera/voxelizedPC", 5); while(ros::ok()) { if(queuedCloud->data.size() > 0) { ROS_INFO("Published new pointcloud with required frequency"); voxelizedPC.publish(*queuedCloud); } loop_rate->sleep(); ros::spinOnce(); } return 0; }<commit_msg>forgot to reset queued cloud when stopping acquisition<commit_after>#include <ros/ros.h> #include <iostream> #include <sstream> #include <ctime> #include <sensor_msgs/PointCloud2.h> #include <std_msgs/Bool.h> #include <pcl/ros/conversions.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/filters/filter.h> #include <pcl/filters/voxel_grid.h> ros::NodeHandle *nh; ros::Rate * loop_rate; ros::Subscriber cameraSubscriber; ros::Subscriber startAcquisition; ros::Publisher voxelizedPC; //define a queue cloud that will be published only when the rate says it sensor_msgs::PointCloud2::Ptr queuedCloud (new sensor_msgs::PointCloud2 ()); void cloud_cb(const sensor_msgs::PointCloud2ConstPtr& msg); void acquisitionCamera(const std_msgs::Bool msg) { if(msg.data == true) { ROS_INFO("Start pointcloud publishing"); cameraSubscriber = nh->subscribe <sensor_msgs::PointCloud2> ("/camera/depth_registered/points",1,cloud_cb); } else { ROS_INFO("Stop pointcloud publishing"); queuedCloud = sensor_msgs::PointCloud2::Ptr(new sensor_msgs::PointCloud2()); cameraSubscriber.shutdown(); } } void cloud_cb(const sensor_msgs::PointCloud2ConstPtr& msg) { pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>()); sensor_msgs::PointCloud2::Ptr cloud_downsampled (new sensor_msgs::PointCloud2 ()); pcl::fromROSMsg(*msg,*cloud); // Create the filtering object pcl::VoxelGrid<sensor_msgs::PointCloud2> sor; sor.setInputCloud (msg); sor.setLeafSize (0.01, 0.01, 0.01); sor.filter (*cloud_downsampled); *queuedCloud = *cloud_downsampled; } int main(int argc, char ** argv) { ros::init(argc,argv,"pcl_stream"); nh = new ros::NodeHandle(); loop_rate = new ros::Rate(1); startAcquisition = nh->subscribe<std_msgs::Bool>("/camera/startAcquisition",1,acquisitionCamera); voxelizedPC = nh->advertise<sensor_msgs::PointCloud2>("/camera/voxelizedPC", 5); while(ros::ok()) { if(queuedCloud->data.size() > 0) { ROS_INFO("Published new pointcloud with required frequency"); voxelizedPC.publish(*queuedCloud); } loop_rate->sleep(); ros::spinOnce(); } return 0; }<|endoftext|>
<commit_before>#include "tmath.hpp" #include <sstream> /* ================================ SINE ======================================== */ TMath::DOUBLE TMath::sin(DOUBLE x) { x = mod(x + PI, 2 * PI) - PI; DOUBLE r = 0; for (LONG n = 0; n <= 8L; n++) { r += pow(DOUBLE(-1), n) * pow(x, 2 * n + 1) / fac(2 * n + 1); } return r; } TMath::DOUBLE TMath::asin(DOUBLE x) { DOUBLE r = 0; DOUBLE delta = 1; for (LONG n = 1; delta > 1e-6; n++) { LONG odd = 2 * n - 1; DOUBLE oddf = oddfacd(odd - 2); DOUBLE f = facd(odd); DOUBLE p = pow(x, odd); DOUBLE d = p / f * oddf * oddf; delta = abs(d); r += p / f * oddf * oddf; } return r; } TMath::DOUBLE TMath::sinh(DOUBLE x) { return 0.5 * (exp(x) - exp(-x)); } /* ================================ COSINE ======================================== */ TMath::DOUBLE TMath::cos(DOUBLE x) { x = mod(x + PI, 2 * PI) - PI; DOUBLE r = 0; for (LONG n = 0; n <= 8L; n++) { r += pow(DOUBLE(-1.0), n) * pow(x, 2 * n) / fac(2 * n); } return r; } TMath::DOUBLE TMath::acos(DOUBLE x) { return PI / 2 - asin(x); } TMath::DOUBLE TMath::cosh(DOUBLE x) { return 0.5 * (exp(x) + exp(-x)); } /* ================================ TANGENT ======================================== */ TMath::DOUBLE TMath::tan(DOUBLE x) { return sin(x) / cos(x); } TMath::DOUBLE TMath::atan(DOUBLE x) { DOUBLE r = 0; DOUBLE delta = 1; for (LONG n = 0; delta > 1e-4; n++) { LONG odd = 2 * n + 1; DOUBLE d = DOUBLE(pow(-1LL, n)) * pow(x, odd) / DOUBLE(odd); delta = abs(d); r += d; } return r; } TMath::DOUBLE TMath::tanh(DOUBLE x) { return sinh(x) / cosh(x); } /* ================================ COTANGENT ======================================== */ TMath::DOUBLE TMath::cot(DOUBLE x) { return cos(x) / sin(x); } TMath::DOUBLE TMath::acot(DOUBLE x) { return PI / 2 - atan(x); } TMath::DOUBLE TMath::coth(DOUBLE x) { return cosh(x) / sinh(x); } /* ================================ SECANT ======================================== */ TMath::DOUBLE TMath::sec(DOUBLE x) { return 1 / cos(x); } TMath::DOUBLE TMath::asec(DOUBLE x) { return acos(1 / x); } TMath::DOUBLE TMath::sech(DOUBLE x) { return 1 / cosh(x); } /* ================================ COSECANT ======================================== */ TMath::DOUBLE TMath::csc(DOUBLE x) { return 1 / sin(x); } TMath::DOUBLE TMath::acsc(DOUBLE x) { return asin(1 / x); } TMath::DOUBLE TMath::csch(DOUBLE x) { return 1 / sinh(x); } /* ================================= FLOOR, CEIL AND MODULO ======================================== */ TMath::LONG TMath::floor(DOUBLE x) { LONG truncated = LONG(x); if (x < 0) { if (truncated > x) { return truncated - 1; } else { return truncated; } } else { return truncated; } } TMath::LONG TMath::ceil(DOUBLE x) { LONG truncated = LONG(x); if (x < 0) { return truncated; } else { return truncated + 1; } } TMath::DOUBLE TMath::mod(DOUBLE x, DOUBLE y) { return y * ((x / y) - floor(x / y)); } /* =============================== EXPONENTIAL FUNCTION, SQRT, LOGARITHM ======================= */ TMath::DOUBLE TMath::exp(DOUBLE x) { DOUBLE r = 0; for (LONG n = 0; n <= 15L; n++) { r += pow(x, n) / facd(n); } return r; } TMath::DOUBLE TMath::sqrt(DOUBLE x) { return root(x, 2); } TMath::DOUBLE TMath::root(DOUBLE x, DOUBLE n) { return pow(x, 1 / n); } TMath::DOUBLE TMath::ln(DOUBLE x) { x = (x - 1) / (x + 1); DOUBLE r = 0; for (LONG n = 0; n <= 100L; n++) { r += 2 * pow(x, 2 * n + 1) / (2 * n + 1); } return r; } TMath::DOUBLE TMath::lg(DOUBLE x) { return ln(x) / ln(10); } TMath::DOUBLE TMath::lb(DOUBLE x) { return ln(x) / ln(2); } TMath::DOUBLE TMath::log(DOUBLE x, DOUBLE n) { return ln(x) / ln(n); } /* =================================== POWER FUNCTIONS =====================================================*/ TMath::DOUBLE TMath::pow(DOUBLE x, LONG n) { if (n < 0) { return 1 / pow(x, -n); } DOUBLE r = 1; for (LONG i = 1; i <= n; i++) { r *= x; } return r; } TMath::LONG TMath::pow(LONG x, LONG n) { if (n < 0) { return 1 / pow(x, -n); } LONG r = 1; for (LONG i = 1; i <= n; i++) { r *= x; } return r; } TMath::DOUBLE TMath::pow(DOUBLE x, DOUBLE n) { return exp(n * ln(x)); } /* ========================================== FACULTY ============================================*/ TMath::LONG TMath::fac(LONG n) { LONG r = 1; for (LONG i = 2; i <= n; i++) { r *= i; } return r; } TMath::DOUBLE TMath::facd(LONG n) { DOUBLE r = 1; for (LONG i = 2; i <= n; i++) { r *= DOUBLE(i); } return r; } TMath::LONG TMath::oddfac(LONG n) { LONG r = 1; for (LONG i = 3; i <= n; i += 2) { r *= i; } return r; } TMath::DOUBLE TMath::oddfacd(LONG n) { DOUBLE r = 1; for (LONG i = 3; i <= n; i += 2) { r *= DOUBLE(i); } return r; } TMath::DOUBLE TMath::abs(DOUBLE x) { if (x < 0) return -x; else return x; } /* ====================================== COMPARISONS ==========*/ TMath::DOUBLE TMath::equal(DOUBLE x, DOUBLE y) { return equal(x, y, EQUAL_EPSILON); } TMath::DOUBLE TMath::equal(DOUBLE x, DOUBLE y, DOUBLE eps) { return abs(x - y) < eps; } /* ========================================== DEGREE / RADIANT CONVERSION ================================*/ TMath::DOUBLE TMath::rad(DOUBLE deg) { return PI / 180 * deg; } TMath::DOUBLE TMath::deg(DOUBLE rad) { return 180 / PI * rad; } /* ======================================== VECTOR IMPLEMENTATIONS =====================================*/ // checkDimensions check if the dimensions of the vectors are equal. int TMath::Vector::checkDimensions(const Vector &a) const { int mdim = dim(); if (mdim != a.dim()) throw TMath::DIMENSION_ERROR; return mdim; } // [n] operator accesses the n-th element of the vector TMath::DOUBLE& TMath::Vector::operator[](const int &i) { return elements.at(i); }; // + operator sums up two vectors. // result = this + a TMath::Vector TMath::Vector::operator+(const Vector &a) const { int d = checkDimensions(a); Vector b(d); for (unsigned int i = 0; i < d; i++) { b[i] = elements.at(i) + a.elements.at(i); } return b; }; // - operator calculates the difference vector of the two vectors. // result = this - a TMath::Vector TMath::Vector::operator-(const Vector &a) const { int d = checkDimensions(a); Vector b(d); for (unsigned int i = 0; i < d; i++) { b[i] = elements.at(i) - a.elements.at(i); } return b; }; // - operator calculates the inversion of the vector. TMath::Vector TMath::Vector::operator-() const { int d = dim(); Vector b(d); for (unsigned int i = 0; i < d; i++) { b[i] = -elements.at(i); } return b; } // * operator scales the vector by the scalar. TMath::Vector TMath::Vector::operator*(const DOUBLE &scalar) const { int d = dim(); Vector b(d); for (unsigned int i = 0; i < d; i++) { b[i] = elements.at(i) * scalar; } return b; }; // / operator scales the vector by the inverse value of the scalar. TMath::Vector TMath::Vector::operator/(const DOUBLE &scalar) const { int d = dim(); Vector b(d); for (unsigned int i = 0; i < d; i++) { b[i] = elements.at(i) / scalar; } return b; }; // equal checks for equality of both vectors. bool TMath::Vector::equal(const Vector &a, const DOUBLE &eps) const { int d = checkDimensions(a); for (unsigned int i = 0; i < d; i++) { if (!TMath::equal(elements.at(i), a.elements.at(i), eps)) return false; } return true; }; // == operator checks for equality with a constant accuracy of EQUAL_EPSILON. bool TMath::Vector::operator==(const Vector &a) const { int d = checkDimensions(a); return this->equal(a, EQUAL_EPSILON); }; // != operator checks for inequality. bool TMath::Vector::operator!=(const Vector &a) const { int d = checkDimensions(a); return !this->equal(a, EQUAL_EPSILON); }; // dot operator calculates the dot product of the two vectors. TMath::DOUBLE TMath::Vector::dot(const Vector &a) const { int d = checkDimensions(a); Vector b(d); DOUBLE sum = 0; for (unsigned int i = 0; i < d; i++) sum += elements.at(i) * a.elements.at(i); return sum; }; // cross operator calculates the cross product of the two vectors. TMath::Vector TMath::Vector::cross(const Vector &a) const { int d = checkDimensions(a); if (d != 3) throw BAD_OPERATION; Vector b(3); for (unsigned int i = 0; i < 3; i++) { unsigned int p = (i+1) % 3, q = (i+2) % 3; b[i] = elements.at(i) * a.elements.at(q) - elements.at(q) * a.elements.at(p); } return b; }; // sum operator calculates the element sum of the vector. TMath::DOUBLE TMath::Vector::sum() const { int d = dim(); DOUBLE sum = 0; for (unsigned int i = 0; i < d; i++) sum += elements[i]; return sum; }; // norm operator calculates a normalized vector. TMath::Vector TMath::Vector::norm() const { int d = dim(); DOUBLE l = length(); Vector b(d); for (unsigned int i = 0; i < d; i++) b[i] = elements[i] / l; return b; } // length operator calculates the length of the vector. TMath::DOUBLE TMath::Vector::length() const { int d = dim(); DOUBLE sum = 0; for (unsigned int i = 0; i < d; i++) sum += elements[i] * elements[i]; return TMath::sqrt(sum); } // dim returns the vector tuple size. int TMath::Vector::dim() const { return elements.size(); } // to_string returns a string representation of the vector. std::string TMath::Vector::to_string() const { std::stringstream stream; stream << "{"; int d = dim(); for (unsigned int i = 0; i < d - 1; i++) stream << elements[i] << ", "; if (d > 0) stream << elements[d-1]; stream << "}"; return stream.str(); } <commit_msg>fix: block operations for null-sized tuples<commit_after>#include "tmath.hpp" #include <sstream> /* ================================ SINE ======================================== */ TMath::DOUBLE TMath::sin(DOUBLE x) { x = mod(x + PI, 2 * PI) - PI; DOUBLE r = 0; for (LONG n = 0; n <= 8L; n++) { r += pow(DOUBLE(-1), n) * pow(x, 2 * n + 1) / fac(2 * n + 1); } return r; } TMath::DOUBLE TMath::asin(DOUBLE x) { DOUBLE r = 0; DOUBLE delta = 1; for (LONG n = 1; delta > 1e-6; n++) { LONG odd = 2 * n - 1; DOUBLE oddf = oddfacd(odd - 2); DOUBLE f = facd(odd); DOUBLE p = pow(x, odd); DOUBLE d = p / f * oddf * oddf; delta = abs(d); r += p / f * oddf * oddf; } return r; } TMath::DOUBLE TMath::sinh(DOUBLE x) { return 0.5 * (exp(x) - exp(-x)); } /* ================================ COSINE ======================================== */ TMath::DOUBLE TMath::cos(DOUBLE x) { x = mod(x + PI, 2 * PI) - PI; DOUBLE r = 0; for (LONG n = 0; n <= 8L; n++) { r += pow(DOUBLE(-1.0), n) * pow(x, 2 * n) / fac(2 * n); } return r; } TMath::DOUBLE TMath::acos(DOUBLE x) { return PI / 2 - asin(x); } TMath::DOUBLE TMath::cosh(DOUBLE x) { return 0.5 * (exp(x) + exp(-x)); } /* ================================ TANGENT ======================================== */ TMath::DOUBLE TMath::tan(DOUBLE x) { return sin(x) / cos(x); } TMath::DOUBLE TMath::atan(DOUBLE x) { DOUBLE r = 0; DOUBLE delta = 1; for (LONG n = 0; delta > 1e-4; n++) { LONG odd = 2 * n + 1; DOUBLE d = DOUBLE(pow(-1LL, n)) * pow(x, odd) / DOUBLE(odd); delta = abs(d); r += d; } return r; } TMath::DOUBLE TMath::tanh(DOUBLE x) { return sinh(x) / cosh(x); } /* ================================ COTANGENT ======================================== */ TMath::DOUBLE TMath::cot(DOUBLE x) { return cos(x) / sin(x); } TMath::DOUBLE TMath::acot(DOUBLE x) { return PI / 2 - atan(x); } TMath::DOUBLE TMath::coth(DOUBLE x) { return cosh(x) / sinh(x); } /* ================================ SECANT ======================================== */ TMath::DOUBLE TMath::sec(DOUBLE x) { return 1 / cos(x); } TMath::DOUBLE TMath::asec(DOUBLE x) { return acos(1 / x); } TMath::DOUBLE TMath::sech(DOUBLE x) { return 1 / cosh(x); } /* ================================ COSECANT ======================================== */ TMath::DOUBLE TMath::csc(DOUBLE x) { return 1 / sin(x); } TMath::DOUBLE TMath::acsc(DOUBLE x) { return asin(1 / x); } TMath::DOUBLE TMath::csch(DOUBLE x) { return 1 / sinh(x); } /* ================================= FLOOR, CEIL AND MODULO ======================================== */ TMath::LONG TMath::floor(DOUBLE x) { LONG truncated = LONG(x); if (x < 0) { if (truncated > x) { return truncated - 1; } else { return truncated; } } else { return truncated; } } TMath::LONG TMath::ceil(DOUBLE x) { LONG truncated = LONG(x); if (x < 0) { return truncated; } else { return truncated + 1; } } TMath::DOUBLE TMath::mod(DOUBLE x, DOUBLE y) { return y * ((x / y) - floor(x / y)); } /* =============================== EXPONENTIAL FUNCTION, SQRT, LOGARITHM ======================= */ TMath::DOUBLE TMath::exp(DOUBLE x) { DOUBLE r = 0; for (LONG n = 0; n <= 15L; n++) { r += pow(x, n) / facd(n); } return r; } TMath::DOUBLE TMath::sqrt(DOUBLE x) { return root(x, 2); } TMath::DOUBLE TMath::root(DOUBLE x, DOUBLE n) { return pow(x, 1 / n); } TMath::DOUBLE TMath::ln(DOUBLE x) { x = (x - 1) / (x + 1); DOUBLE r = 0; for (LONG n = 0; n <= 100L; n++) { r += 2 * pow(x, 2 * n + 1) / (2 * n + 1); } return r; } TMath::DOUBLE TMath::lg(DOUBLE x) { return ln(x) / ln(10); } TMath::DOUBLE TMath::lb(DOUBLE x) { return ln(x) / ln(2); } TMath::DOUBLE TMath::log(DOUBLE x, DOUBLE n) { return ln(x) / ln(n); } /* =================================== POWER FUNCTIONS =====================================================*/ TMath::DOUBLE TMath::pow(DOUBLE x, LONG n) { if (n < 0) { return 1 / pow(x, -n); } DOUBLE r = 1; for (LONG i = 1; i <= n; i++) { r *= x; } return r; } TMath::LONG TMath::pow(LONG x, LONG n) { if (n < 0) { return 1 / pow(x, -n); } LONG r = 1; for (LONG i = 1; i <= n; i++) { r *= x; } return r; } TMath::DOUBLE TMath::pow(DOUBLE x, DOUBLE n) { return exp(n * ln(x)); } /* ========================================== FACULTY ============================================*/ TMath::LONG TMath::fac(LONG n) { LONG r = 1; for (LONG i = 2; i <= n; i++) { r *= i; } return r; } TMath::DOUBLE TMath::facd(LONG n) { DOUBLE r = 1; for (LONG i = 2; i <= n; i++) { r *= DOUBLE(i); } return r; } TMath::LONG TMath::oddfac(LONG n) { LONG r = 1; for (LONG i = 3; i <= n; i += 2) { r *= i; } return r; } TMath::DOUBLE TMath::oddfacd(LONG n) { DOUBLE r = 1; for (LONG i = 3; i <= n; i += 2) { r *= DOUBLE(i); } return r; } TMath::DOUBLE TMath::abs(DOUBLE x) { if (x < 0) return -x; else return x; } /* ====================================== COMPARISONS ==========*/ TMath::DOUBLE TMath::equal(DOUBLE x, DOUBLE y) { return equal(x, y, EQUAL_EPSILON); } TMath::DOUBLE TMath::equal(DOUBLE x, DOUBLE y, DOUBLE eps) { return abs(x - y) < eps; } /* ========================================== DEGREE / RADIANT CONVERSION ================================*/ TMath::DOUBLE TMath::rad(DOUBLE deg) { return PI / 180 * deg; } TMath::DOUBLE TMath::deg(DOUBLE rad) { return 180 / PI * rad; } /* ======================================== VECTOR IMPLEMENTATIONS =====================================*/ // checkDimensions check if the dimensions of the vectors are equal. int TMath::Vector::checkDimensions(const Vector &a) const { int mdim = dim(); if (mdim != a.dim()) throw TMath::DIMENSION_ERROR; return mdim; } // [n] operator accesses the n-th element of the vector TMath::DOUBLE& TMath::Vector::operator[](const int &i) { return elements.at(i); }; // + operator sums up two vectors. // result = this + a TMath::Vector TMath::Vector::operator+(const Vector &a) const { int d = checkDimensions(a); Vector b(d); for (unsigned int i = 0; i < d; i++) { b[i] = elements.at(i) + a.elements.at(i); } return b; }; // - operator calculates the difference vector of the two vectors. // result = this - a TMath::Vector TMath::Vector::operator-(const Vector &a) const { int d = checkDimensions(a); Vector b(d); for (unsigned int i = 0; i < d; i++) { b[i] = elements.at(i) - a.elements.at(i); } return b; }; // - operator calculates the inversion of the vector. TMath::Vector TMath::Vector::operator-() const { int d = dim(); Vector b(d); for (unsigned int i = 0; i < d; i++) { b[i] = -elements.at(i); } return b; } // * operator scales the vector by the scalar. TMath::Vector TMath::Vector::operator*(const DOUBLE &scalar) const { int d = dim(); Vector b(d); for (unsigned int i = 0; i < d; i++) { b[i] = elements.at(i) * scalar; } return b; }; // / operator scales the vector by the inverse value of the scalar. TMath::Vector TMath::Vector::operator/(const DOUBLE &scalar) const { int d = dim(); Vector b(d); for (unsigned int i = 0; i < d; i++) { b[i] = elements.at(i) / scalar; } return b; }; // equal checks for equality of both vectors. bool TMath::Vector::equal(const Vector &a, const DOUBLE &eps) const { int d = checkDimensions(a); for (unsigned int i = 0; i < d; i++) { if (!TMath::equal(elements.at(i), a.elements.at(i), eps)) return false; } return true; }; // == operator checks for equality with a constant accuracy of EQUAL_EPSILON. bool TMath::Vector::operator==(const Vector &a) const { int d = checkDimensions(a); return this->equal(a, EQUAL_EPSILON); }; // != operator checks for inequality. bool TMath::Vector::operator!=(const Vector &a) const { int d = checkDimensions(a); return !this->equal(a, EQUAL_EPSILON); }; // dot operator calculates the dot product of the two vectors. TMath::DOUBLE TMath::Vector::dot(const Vector &a) const { int d = checkDimensions(a); Vector b(d); DOUBLE sum = 0; for (unsigned int i = 0; i < d; i++) sum += elements.at(i) * a.elements.at(i); return sum; }; // cross operator calculates the cross product of the two vectors. TMath::Vector TMath::Vector::cross(const Vector &a) const { int d = checkDimensions(a); if (d != 3) throw BAD_OPERATION; Vector b(3); for (unsigned int i = 0; i < 3; i++) { unsigned int p = (i+1) % 3, q = (i+2) % 3; b[i] = elements.at(i) * a.elements.at(q) - elements.at(q) * a.elements.at(p); } return b; }; // sum operator calculates the element sum of the vector. TMath::DOUBLE TMath::Vector::sum() const { int d = dim(); DOUBLE sum = 0; for (unsigned int i = 0; i < d; i++) sum += elements[i]; return sum; }; // norm operator calculates a normalized vector. TMath::Vector TMath::Vector::norm() const { int d = dim(); if (d == 0) throw BAD_OPERATION; DOUBLE l = length(); Vector b(d); for (unsigned int i = 0; i < d; i++) b[i] = elements[i] / l; return b; } // length operator calculates the length of the vector. TMath::DOUBLE TMath::Vector::length() const { int d = dim(); if (d == 0) throw BAD_OPERATION; DOUBLE sum = 0; for (unsigned int i = 0; i < d; i++) sum += elements[i] * elements[i]; return TMath::sqrt(sum); } // dim returns the vector tuple size. int TMath::Vector::dim() const { return elements.size(); } // to_string returns a string representation of the vector. std::string TMath::Vector::to_string() const { std::stringstream stream; stream << "{"; int d = dim(); for (unsigned int i = 0; i < d - 1; i++) stream << elements[i] << ", "; if (d > 0) stream << elements[d-1]; stream << "}"; return stream.str(); } <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <cstring> #include <algorithm> #include <cassert> template<class T, size_t cmax, class LengthT = uint32_t> struct array_t { T list[cmax]; LengthT count; ///////////////////////////////// void construct(){ count = 0; } size_t capacity() const { return cmax; } bool full() const { return this->count >= cmax; } bool empty() const { return this->count == 0; } void clear() { this->count = 0; } bool operator == (const array_t & rhs) const { return compare(rhs) == 0; } bool operator < (const array_t & rhs) const { return compare(rhs) < 0; } bool operator > (const array_t & rhs) const { return compare(rhs) > 0; } int compare(const array_t & rhs) const { if (count < rhs.count){ for (LengthT i = 0; i < count; ++i){ if (list[i] < rhs.list[i]){ return -1; } else if (!(list[i] == rhs.list[i])){ return 1; } } } else { for (LengthT i = 0; i < rhs.count; ++i){ if (list[i] < rhs.list[i]){ return -1; } else if (!(list[i] == rhs.list[i])){ return 1; } } } return (int)(count - rhs.count); } //////////////////////////////////////////////////// //linear list/////////////////////////////////////// int lfind(const T & tk) const { for (LengthT i = 0; i < count && i < cmax; ++i){ if (list[i] == tk){ return i; } } return -1; } int lappend(const T & td, bool shift_overflow = false){ if (count >= cmax && !shift_overflow){ return -1; } if (count < cmax){ list[count] = td; ++count; return 0; } else { if (cmax > 0){ memmove(list, list + 1, (cmax - 1)*sizeof(T)); list[cmax - 1] = td; } } return 0; } int lremove(int idx, bool swap_remove = false){ if (idx < 0 || (LengthT)idx >= count){ return -1; } if (swap_remove){ list[idx] = list[cmax - 1]; //list[cmax - 1].construct(); } else { memmove(list + idx, list + idx + 1, (count - idx - 1)*sizeof(T)); } --count; return 0; } int linsert(int idx, const T & td, bool overflow_shift = false){ if (count >= cmax && !overflow_shift){ return -1; } if ((LengthT)idx >= count){ idx = count; } else if (idx < 0){ idx = 0; } if ((LengthT)idx == count){ return lappend(td, overflow_shift); } //--overlay------idx------>-----idx+1------------------------------ if (count >= cmax){ memmove(list + idx + 1, list + idx, (cmax - 1 - idx)*sizeof(T)); list[idx] = td; } else { memmove(list + idx + 1, list + idx, (count - idx)*sizeof(T)); list[idx] = td; ++count; } return 0; } void lsort(array_t & out) const { memcpy(&out, this, sizeof(*this)); ::std::sort(out.list, out.list + out.count); } ////////////////////////////////////////////////////////// /////////////////////binary-seaching////////////////////// int bfind(const T & tk) const { int idx1st = lower_bound(tk); int idx2nd = upper_bound(tk); if (idx1st == idx2nd){ return -1; } while (idx1st < idx2nd){ if (tk == list[idx1st]){ return idx1st; } ++idx1st; } return -1; } int binsert(const T & td, bool overflow_shift = false, bool uniq = false) { LengthT idx = lower_bound(td); if (uniq && idx < count) { if (list[idx] == td) { return -1; } } return linsert(idx, td, overflow_shift); } int bremove(const T & tk){ int idx = bfind(tk); if (idx < 0){ return -1; } return lremove(idx, false); } LengthT lower_bound(const T & tk) const { const T * p = ::std::lower_bound((T*)list, (T*)list + count, (T&)tk); return (p - list); } LengthT upper_bound(const T & tk) const { const T * p = ::std::upper_bound((T*)list, (T*)list + count, (T&)tk); return (p - list); } T & operator [](size_t idx){ assert(idx < count); return list[idx]; } const T & operator [](size_t idx) const { assert(idx < count); return list[idx]; } }; <commit_msg>fixing array bin<commit_after>#pragma once #include <cstdint> #include <cstring> #include <algorithm> #include <cassert> template<class T, size_t cmax, class LengthT = uint32_t> struct array_t { T list[cmax]; LengthT count; ///////////////////////////////// void construct(){ count = 0; } size_t capacity() const { return cmax; } bool full() const { return this->count >= cmax; } bool empty() const { return this->count == 0; } void clear() { this->count = 0; } bool operator == (const array_t & rhs) const { return compare(rhs) == 0; } bool operator < (const array_t & rhs) const { return compare(rhs) < 0; } bool operator > (const array_t & rhs) const { return compare(rhs) > 0; } int compare(const array_t & rhs) const { if (count < rhs.count){ for (LengthT i = 0; i < count; ++i){ if (list[i] < rhs.list[i]){ return -1; } else if (!(list[i] == rhs.list[i])){ return 1; } } } else { for (LengthT i = 0; i < rhs.count; ++i){ if (list[i] < rhs.list[i]){ return -1; } else if (!(list[i] == rhs.list[i])){ return 1; } } } return (int)(count - rhs.count); } //////////////////////////////////////////////////// //linear list/////////////////////////////////////// int lfind(const T & tk) const { for (LengthT i = 0; i < count && i < cmax; ++i){ if (list[i] == tk){ return i; } } return -1; } int lappend(const T & td, bool shift_overflow = false){ if (count >= cmax && !shift_overflow){ return -1; } if (count < cmax){ list[count] = td; ++count; return 0; } else { if (cmax > 0){ memmove(list, list + 1, (cmax - 1)*sizeof(T)); list[cmax - 1] = td; } } return 0; } int lremove(int idx, bool swap_remove = false){ if (idx < 0 || (LengthT)idx >= count){ return -1; } if (swap_remove){ list[idx] = list[cmax - 1]; //list[cmax - 1].construct(); } else { memmove(list + idx, list + idx + 1, (count - idx - 1)*sizeof(T)); } --count; return 0; } int linsert(int idx, const T & td, bool overflow_shift = false){ if (count >= cmax && !overflow_shift){ return -1; } if ((LengthT)idx >= count){ idx = count; } else if (idx < 0){ idx = 0; } if ((LengthT)idx == count){ return lappend(td, overflow_shift); } //--overlay------idx------>-----idx+1------------------------------ if (count >= cmax){ memmove(list + idx + 1, list + idx, (cmax - 1 - idx)*sizeof(T)); list[idx] = td; } else { memmove(list + idx + 1, list + idx, (count - idx)*sizeof(T)); list[idx] = td; ++count; } return 0; } void lsort(array_t & out) const { memcpy(&out, this, sizeof(*this)); ::std::sort(out.list, out.list + out.count); } ////////////////////////////////////////////////////////// /////////////////////binary-seaching////////////////////// int bfind(const T & tk) const { LengthT idx1st = lower_bound(tk); if (idx1st < count && list[idx1st] == tk) { return idx1st; } return -1; } int binsert(const T & td, bool overflow_shift = false, bool uniq = false) { LengthT idx = lower_bound(td); if (uniq && idx < count && list[idx] == td) { return -1; } return linsert(idx, td, overflow_shift); } int bremove(const T & tk){ int idx = bfind(tk); if (idx < 0){ return -1; } return lremove(idx, false); } LengthT lower_bound(const T & tk) const { const T * p = ::std::lower_bound(list, list + count, tk); return (p - list); } LengthT upper_bound(const T & tk) const { const T * p = ::std::upper_bound(list, list + count, tk); return (p - list); } T & operator [](size_t idx){ assert(idx < count); return list[idx]; } const T & operator [](size_t idx) const { assert(idx < count); return list[idx]; } }; <|endoftext|>
<commit_before>// // Splash.cpp // example // // Created by James Bentley on 1/5/15. // // #include "CRState.h" void CRState::setup() { sensitivity = 0.7; soundStream.setInput(this); soundStream.setup(0, 1, 44100, 512, 1); #ifdef __arm__ soundStream.setDeviceID(1); #endif //soundStream.stop(); imageIndex = 0; colorIndex = 0; vidOn = true; audioFramesSinceLastSwapped = 0; MIN_FRAMES_BETWEEN_SWAPS = 0.3 * 44100; // 0.3 seconds at 44.1 kHz mustSwap = false; } void CRState::update() { if(mustSwap) { swap(); mustSwap = false; } } void CRState::draw() { // ofDrawBitmapString("Call & Responce is currently under development: press 's' to return the splash page", 0, 10); ofPushStyle(); ofSetColor(getSharedData().pallete[colorIndex]); ofSetRectMode(OF_RECTMODE_CENTER); getSharedData().images[imageIndex].draw(ofGetWidth()/2, ofGetHeight()/2); ofPopStyle(); } string CRState::getName() { return "cr"; } void CRState::mousePressed(int x, int y, int button) { // unsigned char *pixels=images[imageIndex].getPixels(); // int numPixels = images[imageIndex].getHeight() + images[imageIndex].getWidth(); // for(int index = 0; index < numPixels*4; index += 4) // { // int red = pixels[index]; // int green = pixels[index+1]; // int blue = pixels[index+2]; // int alpha = pixels[index+3]; // printf(">>>>%i >>>%i >>>%i >>>%i >>>%i\n", index, red,green,blue,alpha); // } // cout<<numPixels<<endl; changeState("splash"); } void CRState::keyPressed(int key) { if(key == 's') { changeState("splash"); } } void CRState::tryToSwap() { mustSwap = true; } void CRState::swap() { colorIndex = (int)ofRandom(7); if(getSharedData().pallete[colorIndex] == getSharedData().background) { swap(); } int newIndex = (int)ofRandom(7); if(newIndex == imageIndex) { imageIndex++; imageIndex %= 7; } } void CRState::audioIn(float *samples, int length, int numChannels) { for(int i =0 ; i < length; i++) { float f = ABS(samples[i]); if(volume<f) volume = f; else volume *= 0.9995; displayVolume = sqrt(volume); if(displayVolume>sensitivity) { if(audioFramesSinceLastSwapped>MIN_FRAMES_BETWEEN_SWAPS) { tryToSwap(); getSharedData().wheelCount++; audioFramesSinceLastSwapped = 0; } } audioFramesSinceLastSwapped++; } } <commit_msg>Fixed Sound issue for rizzle<commit_after>// // Splash.cpp // example // // Created by James Bentley on 1/5/15. // // #include "CRState.h" void CRState::setup() { sensitivity = 0.7; soundStream.setInput(this); #ifdef __arm__ soundStream.setDeviceID(2); soundStream.listDevices(); #endif soundStream.setup(0, 1, 44100, 512, 1); //soundStream.stop(); imageIndex = 0; colorIndex = 0; vidOn = true; audioFramesSinceLastSwapped = 0; MIN_FRAMES_BETWEEN_SWAPS = 0.3 * 44100; // 0.3 seconds at 44.1 kHz mustSwap = false; } void CRState::update() { if(mustSwap) { swap(); mustSwap = false; } } void CRState::draw() { // ofDrawBitmapString("Call & Responce is currently under development: press 's' to return the splash page", 0, 10); ofPushStyle(); ofSetColor(getSharedData().pallete[colorIndex]); ofSetRectMode(OF_RECTMODE_CENTER); getSharedData().images[imageIndex].draw(ofGetWidth()/2, ofGetHeight()/2); ofPopStyle(); } string CRState::getName() { return "cr"; } void CRState::mousePressed(int x, int y, int button) { // unsigned char *pixels=images[imageIndex].getPixels(); // int numPixels = images[imageIndex].getHeight() + images[imageIndex].getWidth(); // for(int index = 0; index < numPixels*4; index += 4) // { // int red = pixels[index]; // int green = pixels[index+1]; // int blue = pixels[index+2]; // int alpha = pixels[index+3]; // printf(">>>>%i >>>%i >>>%i >>>%i >>>%i\n", index, red,green,blue,alpha); // } // cout<<numPixels<<endl; changeState("splash"); } void CRState::keyPressed(int key) { if(key == 's') { changeState("splash"); } } void CRState::tryToSwap() { mustSwap = true; } void CRState::swap() { colorIndex = (int)ofRandom(7); if(getSharedData().pallete[colorIndex] == getSharedData().background) { swap(); } int newIndex = (int)ofRandom(7); if(newIndex == imageIndex) { imageIndex++; imageIndex %= 7; } } void CRState::audioIn(float *samples, int length, int numChannels) { for(int i =0 ; i < length; i++) { float f = ABS(samples[i]); if(volume<f) volume = f; else volume *= 0.9995; displayVolume = sqrt(volume); if(displayVolume>sensitivity) { if(audioFramesSinceLastSwapped>MIN_FRAMES_BETWEEN_SWAPS) { tryToSwap(); getSharedData().wheelCount++; audioFramesSinceLastSwapped = 0; } } audioFramesSinceLastSwapped++; } } <|endoftext|>
<commit_before>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (testabilitydriver@nokia.com) ** ** This file is part of Testability Driver. ** ** If you have questions regarding the use of this file, please contact ** Nokia at testabilitydriver@nokia.com . ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QtPlugin> #include <QDebug> #include <QHash> #include <QVariant> //#include <QDomElement> //#include <QDomDocument> #include <visualizeraccessor.h> #include <tasqtdatamodel.h> #include <tdriver_tabbededitor.h> // //#include <dispatcher.h> //#include <includes.h> Q_EXPORT_PLUGIN2(visualizeraccessor, VisualizerAccessor) // fixture version information static QString FIXTURE_NAME = "VisualizerAccessor"; static QString FIXTURE_VERSION = "0.1"; static QString FIXTURE_DESCRIPTION = "API for accessing applications internal Qt methods"; // hash keys static QString CLASS_NAME = "class"; static QString METHOD_NAME = "method"; static QString METHOD_ARGS = "args"; // Constructor VisualizerAccessor::VisualizerAccessor( QObject *parent ) : QObject( parent ) { } bool VisualizerAccessor::execute(void * objectInstance, QString commandName, QHash<QString, QString> parameters, QString & resultString) { qDebug() << "VisualizerAccessor::execute"; qDebug() << "command:" << commandName; qDebug() << "parameters" << parameters; bool result = false; resultString = commandName; QString className; QObject *tmpQObject = reinterpret_cast<QObject*>(objectInstance); if (tmpQObject) className = tmpQObject->metaObject()->className(); // resultString.append(" "+className); TDriverTabbedEditor *tabs = qobject_cast<TDriverTabbedEditor*>(tmpQObject); // resultString = (resultString + " & %1 %2 %3"). // arg(reinterpret_cast<uint>(objectInstance), 8, 16, QChar('0')). // arg(reinterpret_cast<uint>(tmpQObject), 8, 16, QChar('0')). // arg(reinterpret_cast<uint>(tabs), 8, 16, QChar('0')); if (commandName == "editor_save") { if (tabs) { if (parameters.contains("filename")) { int index = QVariant(parameters.value("tabindex", "-1")).toInt(&result); if (result) { result = reinterpret_cast<TDriverTabbedEditor*>(objectInstance)->saveFile( parameters["filename"], index); resultString += ": saveFile called"; } else resultString += " error: invalid tab index"; } else resultString += " error: missing command parameter: filename"; } else { resultString = (commandName + " error: invalid object @0x%1 class name '%2'"). arg(reinterpret_cast<uint>(tmpQObject), 8, 16, QChar('0')). arg(className); } } else if (commandName == "editor_load") { if (tabs) { if (parameters.contains("filename")) { result = reinterpret_cast<TDriverTabbedEditor*>(objectInstance)->loadFile( parameters["filename"], QVariant(parameters.value("istemplate", false)).toBool()); resultString += ": loadFile called"; } else resultString += " error: missing command parameter: filename"; } else { resultString = (commandName + " error: invalid object @0x%1 class name '%2'"). arg(reinterpret_cast<uint>(tmpQObject), 8, 16, QChar('0')). arg(className); } } else if (commandName == "ping") { if (parameters.contains("data")) resultString = parameters["data"]; else resultString = "pong"; result = true; } else { resultString += " error: invalid command"; } return result; } <commit_msg>Fixed test fixture<commit_after>/*************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (testabilitydriver@nokia.com) ** ** This file is part of Testability Driver. ** ** If you have questions regarding the use of this file, please contact ** Nokia at testabilitydriver@nokia.com . ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include <QtPlugin> #include <QDebug> #include <QHash> #include <QVariant> //#include <QDomElement> //#include <QDomDocument> #include <visualizeraccessor.h> #include <tasqtdatamodel.h> #include <tdriver_tabbededitor.h> // //#include <dispatcher.h> //#include <includes.h> Q_EXPORT_PLUGIN2(visualizeraccessor, VisualizerAccessor) // fixture version information static QString FIXTURE_NAME = "VisualizerAccessor"; static QString FIXTURE_VERSION = "0.1"; static QString FIXTURE_DESCRIPTION = "API for accessing applications internal Qt methods"; // hash keys static QString CLASS_NAME = "class"; static QString METHOD_NAME = "method"; static QString METHOD_ARGS = "args"; // Constructor VisualizerAccessor::VisualizerAccessor( QObject *parent ) : QObject( parent ) { } bool VisualizerAccessor::execute(void * objectInstance, QString commandName, QHash<QString, QString> parameters, QString & resultString) { qDebug() << "VisualizerAccessor::execute"; qDebug() << "command:" << commandName; qDebug() << "parameters" << parameters; bool result = false; resultString = commandName; static QStringList valid_commands(QStringList() << "ping" << "editor_save" << "editor_load"); if (!valid_commands.contains(commandName)) { resultString += " error: invalid command"; } // first commands that do not need editor instance else if (commandName == "ping") { if (parameters.contains("data")) resultString = parameters["data"]; else resultString = "pong"; result = true; } // then commands that need editor instance else { // TODO: add code to check that objectInstance really is a QObject pointer TDriverTabbedEditor *tabs = qobject_cast<TDriverTabbedEditor*>( reinterpret_cast<QObject*>(objectInstance)); QString className = (tabs) ? tabs->metaObject()->className() : "<invalid>"; if (!tabs) { resultString = (commandName + " error: invalid object @0x%1 class name '%2'") .arg(reinterpret_cast<uint>(objectInstance), 8, 16, QChar('0')) .arg(className); } else if (commandName == "editor_save") { if (parameters.contains("filename")) { int index = QVariant(parameters.value("tabindex", "-1")).toInt(&result); if (result) { result = tabs->saveFile(parameters["filename"], index, true); resultString += ": saveFile called"; } else { resultString += " error: invalid tab index"; } } else { resultString += " error: missing command parameter: filename"; } } else if (commandName == "editor_load") { if (parameters.contains("filename")) { result = tabs->loadFile(parameters["filename"], QVariant(parameters.value("istemplate", false)).toBool()); resultString += ": loadFile called"; } else resultString += " error: missing command parameter: filename"; } } return result; } <|endoftext|>
<commit_before>// // Created by Tay on 10/10/17. // void selectionSort(int table[], int size) { int min, tmp; for (int i = 0; i < size - 1; i++) { min = i; for (int j = i + 1; j < size; j++) { if (table[j] < table[min]) { min = j; } } if (min != i) { tmp = table[i]; table[i] = table[min]; table[min] = tmp; } for (int a = 0; a < 7; a++) { std::cout << table[a] << " "; } std::cout << std::endl; } } int main() { int table[] = {13, 32, 43, 14, 25}; selectionSort(table, 5); return 0; }<commit_msg>Modified selection sort<commit_after>#include<iostream.h> #include<conio.h> void main() { clrscr(); int size, arr[50], i, j, temp; cout<<"Enter Array Size : "; cin>>size; cout<<"Enter Array Elements : "; for(i=0; i<size; i++) { cin>>arr[i]; } cout<<"Sorting array using selection sort...\n"; for(i=0; i<size; i++) { for(j=i+1; j<size; j++) { if(arr[i]>arr[j]) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } cout<<"Now the Array after sorting is :\n"; for(i=0; i<size; i++) { cout<<arr[i]<<" "; } getch(); } <|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <cstdio> #include <cerrno> #include <cassert> #include <cstring> #include <link.h> #include <sys/mman.h> /** * This is experimental code that will map code segments in binary and dso into * anonymous mappings prefering huge page mappings. */ namespace { constexpr size_t HUGEPAGE_SIZE = 0x200000; void * mmap_huge(size_t sz) { assert ((sz % HUGEPAGE_SIZE) == 0); void * mem = mmap(nullptr, sz, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); assert(mem != MAP_FAILED); if (madvise(mem, sz, MADV_HUGEPAGE) != 0) { fprintf(stderr, "load_as_huge.cpp:mmap_huge = > madvise(%p, %ld, MADV_HUGEPAGE) FAILED, errno= %d = %s\n", mem, sz, errno, strerror(errno)); } return mem; } size_t round_huge_down(size_t v) { return v & ~(HUGEPAGE_SIZE - 1); } size_t round_huge_up(size_t v) { return round_huge_down(v + (HUGEPAGE_SIZE - 1)); } void non_optimized_non_inlined_memcpy(void *dest_in, const void *src_in, size_t n) __attribute__((noinline, optimize(1))) ; // Simple memcpy replacement to avoid calling code in other dso. void non_optimized_non_inlined_memcpy(void *dest_in, const void *src_in, size_t n) { char *dest = static_cast<char *>(dest_in); const char *src = static_cast<const char *>(src_in); for (size_t i(0); i < n ; i++) { dest[i] = src[i]; } } /** * Make a large mapping if code is larger than HUGEPAGE_SIZE and copies the content of the various segments. * Then remaps the areas back to its original location. */ bool remap_segments(size_t base_vaddr, const Elf64_Phdr * segments, size_t count) { assert(count > 0); const Elf64_Phdr & first = segments[0]; const Elf64_Phdr & last = segments[count - 1]; size_t start_vaddr = base_vaddr + first.p_vaddr; size_t end_vaddr = base_vaddr + last.p_vaddr + last.p_memsz; if (end_vaddr - start_vaddr < HUGEPAGE_SIZE) { return false; } size_t huge_start = round_huge_down(start_vaddr); size_t huge_end = round_huge_up(end_vaddr); size_t huge_size = huge_end - huge_start; char * new_huge = static_cast<char *>(mmap_huge(huge_size)); char * new_huge_end = new_huge + huge_size; char * last_end = new_huge; for (size_t i(0); i < count; i++) { size_t vaddr = base_vaddr + segments[i].p_vaddr; size_t huge_offset = vaddr - huge_start; char * dest = new_huge + huge_offset; assert(dest >= last_end); if (dest > last_end) { int munmap_retval = munmap(last_end, dest - last_end); assert(munmap_retval == 0); } size_t sz = segments[i].p_memsz; last_end = dest + sz; if (madvise(dest, sz, MADV_HUGEPAGE) != 0) { fprintf(stderr, "load_as_huge.cpp:remap_segments => madvise(%p, %ld, MADV_HUGEPAGE) FAILED, errno= %d = %s\n", dest, sz, errno, strerror(errno)); } non_optimized_non_inlined_memcpy(dest, reinterpret_cast<void*>(vaddr), sz); int prot = PROT_READ; if (segments[i].p_flags & PF_X) prot|= PROT_EXEC; if (segments[i].p_flags & PF_W) prot|= PROT_WRITE; int mprotect_retval = mprotect(dest, sz, prot); if (mprotect_retval != 0) { fprintf(stderr, "mprotect(%p, %ld, %x) FAILED = %d, errno= %d = %s\n", dest, sz, prot, mprotect_retval, errno, strerror(errno)); } void * remapped = mremap(dest, sz, sz, MREMAP_FIXED | MREMAP_MAYMOVE, vaddr); assert(remapped != MAP_FAILED); assert(remapped == reinterpret_cast<void *>(vaddr)); fprintf(stdout, "remapped dest=%p, size=%lu to %p\n", dest, sz, remapped); } assert(new_huge_end >= last_end); if (new_huge_end > last_end) { int munmap_retval = munmap(last_end, new_huge_end - last_end); assert(munmap_retval); } return true; } int remapElfHeader(struct dl_phdr_info *info, size_t info_size, void *data) { (void) info_size; (void) data; fprintf(stdout, "processing elf header '%s' with %d entries, start=%lx\n", info->dlpi_name, info->dlpi_phnum, info->dlpi_addr); for (int i = 0; i < info->dlpi_phnum; i++) { const Elf64_Phdr &phdr = info->dlpi_phdr[i]; //fprintf(stdout, "p_vaddr=%lx p_paddr=%lx, p_offset=%lx p_filesz=%lx, p_memsz=%lx, allign=%lu type=%d flags=%x\n", // phdr.p_vaddr, phdr.p_paddr, phdr.p_offset, phdr.p_filesz, phdr.p_memsz, phdr.p_align, phdr.p_type, phdr.p_flags); if ((phdr.p_type == PT_LOAD) && (phdr.p_flags == (PF_R | PF_X))) { //void *vaddr = reinterpret_cast<void *>(info->dlpi_addr + phdr.p_vaddr); //uint64_t size = phdr.p_filesz; //fprintf(stdout, "LOAD_RX: vaddr=%lx p_filesz=%lu, p_memsz=%lu\n", phdr.p_vaddr, phdr.p_filesz, phdr.p_memsz); remap_segments(info->dlpi_addr, &phdr, 1); } } return 0; } } extern "C" int remapTextWithHugePages(); int remapTextWithHugePages() { int retval = dl_iterate_phdr(remapElfHeader, nullptr); fprintf(stdout, "dl_iterate_phdr() = %d\n", retval); return retval; } static long num_huge_code_pages = remapTextWithHugePages(); <commit_msg>Use clang attribute to turn off optimization when compiling with clang.<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <cstdio> #include <cerrno> #include <cassert> #include <cstring> #include <link.h> #include <sys/mman.h> /** * This is experimental code that will map code segments in binary and dso into * anonymous mappings prefering huge page mappings. */ namespace { constexpr size_t HUGEPAGE_SIZE = 0x200000; void * mmap_huge(size_t sz) { assert ((sz % HUGEPAGE_SIZE) == 0); void * mem = mmap(nullptr, sz, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); assert(mem != MAP_FAILED); if (madvise(mem, sz, MADV_HUGEPAGE) != 0) { fprintf(stderr, "load_as_huge.cpp:mmap_huge = > madvise(%p, %ld, MADV_HUGEPAGE) FAILED, errno= %d = %s\n", mem, sz, errno, strerror(errno)); } return mem; } size_t round_huge_down(size_t v) { return v & ~(HUGEPAGE_SIZE - 1); } size_t round_huge_up(size_t v) { return round_huge_down(v + (HUGEPAGE_SIZE - 1)); } #ifdef __clang__ void non_optimized_non_inlined_memcpy(void *dest_in, const void *src_in, size_t n) __attribute__((noinline, optnone)) ; #else void non_optimized_non_inlined_memcpy(void *dest_in, const void *src_in, size_t n) __attribute__((noinline, optimize(1))) ; #endif // Simple memcpy replacement to avoid calling code in other dso. void non_optimized_non_inlined_memcpy(void *dest_in, const void *src_in, size_t n) { char *dest = static_cast<char *>(dest_in); const char *src = static_cast<const char *>(src_in); for (size_t i(0); i < n ; i++) { dest[i] = src[i]; } } /** * Make a large mapping if code is larger than HUGEPAGE_SIZE and copies the content of the various segments. * Then remaps the areas back to its original location. */ bool remap_segments(size_t base_vaddr, const Elf64_Phdr * segments, size_t count) { assert(count > 0); const Elf64_Phdr & first = segments[0]; const Elf64_Phdr & last = segments[count - 1]; size_t start_vaddr = base_vaddr + first.p_vaddr; size_t end_vaddr = base_vaddr + last.p_vaddr + last.p_memsz; if (end_vaddr - start_vaddr < HUGEPAGE_SIZE) { return false; } size_t huge_start = round_huge_down(start_vaddr); size_t huge_end = round_huge_up(end_vaddr); size_t huge_size = huge_end - huge_start; char * new_huge = static_cast<char *>(mmap_huge(huge_size)); char * new_huge_end = new_huge + huge_size; char * last_end = new_huge; for (size_t i(0); i < count; i++) { size_t vaddr = base_vaddr + segments[i].p_vaddr; size_t huge_offset = vaddr - huge_start; char * dest = new_huge + huge_offset; assert(dest >= last_end); if (dest > last_end) { int munmap_retval = munmap(last_end, dest - last_end); assert(munmap_retval == 0); } size_t sz = segments[i].p_memsz; last_end = dest + sz; if (madvise(dest, sz, MADV_HUGEPAGE) != 0) { fprintf(stderr, "load_as_huge.cpp:remap_segments => madvise(%p, %ld, MADV_HUGEPAGE) FAILED, errno= %d = %s\n", dest, sz, errno, strerror(errno)); } non_optimized_non_inlined_memcpy(dest, reinterpret_cast<void*>(vaddr), sz); int prot = PROT_READ; if (segments[i].p_flags & PF_X) prot|= PROT_EXEC; if (segments[i].p_flags & PF_W) prot|= PROT_WRITE; int mprotect_retval = mprotect(dest, sz, prot); if (mprotect_retval != 0) { fprintf(stderr, "mprotect(%p, %ld, %x) FAILED = %d, errno= %d = %s\n", dest, sz, prot, mprotect_retval, errno, strerror(errno)); } void * remapped = mremap(dest, sz, sz, MREMAP_FIXED | MREMAP_MAYMOVE, vaddr); assert(remapped != MAP_FAILED); assert(remapped == reinterpret_cast<void *>(vaddr)); fprintf(stdout, "remapped dest=%p, size=%lu to %p\n", dest, sz, remapped); } assert(new_huge_end >= last_end); if (new_huge_end > last_end) { int munmap_retval = munmap(last_end, new_huge_end - last_end); assert(munmap_retval); } return true; } int remapElfHeader(struct dl_phdr_info *info, size_t info_size, void *data) { (void) info_size; (void) data; fprintf(stdout, "processing elf header '%s' with %d entries, start=%lx\n", info->dlpi_name, info->dlpi_phnum, info->dlpi_addr); for (int i = 0; i < info->dlpi_phnum; i++) { const Elf64_Phdr &phdr = info->dlpi_phdr[i]; //fprintf(stdout, "p_vaddr=%lx p_paddr=%lx, p_offset=%lx p_filesz=%lx, p_memsz=%lx, allign=%lu type=%d flags=%x\n", // phdr.p_vaddr, phdr.p_paddr, phdr.p_offset, phdr.p_filesz, phdr.p_memsz, phdr.p_align, phdr.p_type, phdr.p_flags); if ((phdr.p_type == PT_LOAD) && (phdr.p_flags == (PF_R | PF_X))) { //void *vaddr = reinterpret_cast<void *>(info->dlpi_addr + phdr.p_vaddr); //uint64_t size = phdr.p_filesz; //fprintf(stdout, "LOAD_RX: vaddr=%lx p_filesz=%lu, p_memsz=%lu\n", phdr.p_vaddr, phdr.p_filesz, phdr.p_memsz); remap_segments(info->dlpi_addr, &phdr, 1); } } return 0; } } extern "C" int remapTextWithHugePages(); int remapTextWithHugePages() { int retval = dl_iterate_phdr(remapElfHeader, nullptr); fprintf(stdout, "dl_iterate_phdr() = %d\n", retval); return retval; } static long num_huge_code_pages = remapTextWithHugePages(); <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <stdio.h> #include <string> #include "after_initialization_fixture.h" #include "test/testsupport/fileutils.h" namespace webrtc { namespace { const int16_t kLimiterHeadroom = 29204; // == -1 dbFS const int16_t kInt16Max = 0x7fff; const int kSampleRateHz = 16000; const int kTestDurationMs = 3000; const int kSkipOutputMs = 500; } // namespace class MixingTest : public AfterInitializationFixture { protected: MixingTest() : input_filename_(test::OutputPath() + "mixing_test_input.pcm"), output_filename_(test::OutputPath() + "mixing_test_output.pcm") { } void SetUp() { transport_ = new LoopBackTransport(voe_network_); } void TearDown() { delete transport_; } // Creates and mixes |num_remote_streams| which play a file "as microphone" // with |num_local_streams| which play a file "locally", using a constant // amplitude of |input_value|. The local streams manifest as "anonymous" // mixing participants, meaning they will be mixed regardless of the number // of participants. (A stream is a VoiceEngine "channel"). // // The mixed output is verified to always fall between |max_output_value| and // |min_output_value|, after a startup phase. // // |num_remote_streams_using_mono| of the remote streams use mono, with the // remainder using stereo. void RunMixingTest(int num_remote_streams, int num_local_streams, int num_remote_streams_using_mono, int16_t input_value, int16_t max_output_value, int16_t min_output_value) { ASSERT_LE(num_remote_streams_using_mono, num_remote_streams); GenerateInputFile(input_value); std::vector<int> local_streams(num_local_streams); for (size_t i = 0; i < local_streams.size(); ++i) { local_streams[i] = voe_base_->CreateChannel(); EXPECT_NE(-1, local_streams[i]); } StartLocalStreams(local_streams); TEST_LOG("Playing %d local streams.\n", num_local_streams); std::vector<int> remote_streams(num_remote_streams); for (size_t i = 0; i < remote_streams.size(); ++i) { remote_streams[i] = voe_base_->CreateChannel(); EXPECT_NE(-1, remote_streams[i]); } StartRemoteStreams(remote_streams, num_remote_streams_using_mono); TEST_LOG("Playing %d remote streams.\n", num_remote_streams); // Start recording the mixed output and wait. EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1 /* record meeting */, output_filename_.c_str())); Sleep(kTestDurationMs); EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1)); StopLocalStreams(local_streams); StopRemoteStreams(remote_streams); VerifyMixedOutput(max_output_value, min_output_value); } private: // Generate input file with constant values equal to |input_value|. The file // will be one second longer than the duration of the test. void GenerateInputFile(int16_t input_value) { FILE* input_file = fopen(input_filename_.c_str(), "wb"); ASSERT_TRUE(input_file != NULL); for (int i = 0; i < kSampleRateHz / 1000 * (kTestDurationMs + 1000); i++) { ASSERT_EQ(1u, fwrite(&input_value, sizeof(input_value), 1, input_file)); } ASSERT_EQ(0, fclose(input_file)); } void VerifyMixedOutput(int16_t max_output_value, int16_t min_output_value) { // Verify the mixed output. FILE* output_file = fopen(output_filename_.c_str(), "rb"); ASSERT_TRUE(output_file != NULL); int16_t output_value = 0; // Skip the first segment to avoid initialization and ramping-in effects. EXPECT_EQ(0, fseek(output_file, sizeof(output_value) * kSampleRateHz / 1000 * kSkipOutputMs, SEEK_SET)); int samples_read = 0; while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) { samples_read++; std::ostringstream trace_stream; trace_stream << samples_read << " samples read"; SCOPED_TRACE(trace_stream.str()); EXPECT_LE(output_value, max_output_value); EXPECT_GE(output_value, min_output_value); } // Ensure the recording length is close to the duration of the test. // We have to use a relaxed tolerance here due to filesystem flakiness on // the bots. ASSERT_GE((samples_read * 1000.0) / kSampleRateHz, 0.7 * (kTestDurationMs - kSkipOutputMs)); // Ensure we read the entire file. ASSERT_NE(0, feof(output_file)); ASSERT_EQ(0, fclose(output_file)); } // Start up local streams ("anonymous" participants). void StartLocalStreams(const std::vector<int>& streams) { for (size_t i = 0; i < streams.size(); ++i) { EXPECT_EQ(0, voe_base_->StartPlayout(streams[i])); EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(streams[i], input_filename_.c_str(), true)); } } void StopLocalStreams(const std::vector<int>& streams) { for (size_t i = 0; i < streams.size(); ++i) { EXPECT_EQ(0, voe_base_->StopPlayout(streams[i])); EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i])); } } // Start up remote streams ("normal" participants). void StartRemoteStreams(const std::vector<int>& streams, int num_remote_streams_using_mono) { // Use L16 at 16kHz to minimize distortion (file recording is 16kHz and // resampling will cause distortion). CodecInst codec_inst; strcpy(codec_inst.plname, "L16"); codec_inst.channels = 1; codec_inst.plfreq = kSampleRateHz; codec_inst.pltype = 105; codec_inst.pacsize = codec_inst.plfreq / 100; codec_inst.rate = codec_inst.plfreq * sizeof(int16_t) * 8; // 8 bits/byte. for (int i = 0; i < num_remote_streams_using_mono; ++i) { StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i); } // The remainder of the streams will use stereo. codec_inst.channels = 2; codec_inst.pltype++; for (size_t i = num_remote_streams_using_mono; i < streams.size(); ++i) { StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i); } } // Start up a single remote stream. void StartRemoteStream(int stream, const CodecInst& codec_inst, int port) { EXPECT_EQ(0, voe_codec_->SetRecPayloadType(stream, codec_inst)); EXPECT_EQ(0, voe_network_->RegisterExternalTransport(stream, *transport_)); EXPECT_EQ(0, voe_base_->StartReceive(stream)); EXPECT_EQ(0, voe_base_->StartPlayout(stream)); EXPECT_EQ(0, voe_codec_->SetSendCodec(stream, codec_inst)); EXPECT_EQ(0, voe_base_->StartSend(stream)); EXPECT_EQ(0, voe_file_->StartPlayingFileAsMicrophone(stream, input_filename_.c_str(), true)); } void StopRemoteStreams(const std::vector<int>& streams) { for (size_t i = 0; i < streams.size(); ++i) { EXPECT_EQ(0, voe_base_->StopSend(streams[i])); EXPECT_EQ(0, voe_base_->StopPlayout(streams[i])); EXPECT_EQ(0, voe_base_->StopReceive(streams[i])); EXPECT_EQ(0, voe_network_->DeRegisterExternalTransport(streams[i])); EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i])); } } const std::string input_filename_; const std::string output_filename_; LoopBackTransport* transport_; }; // These tests assume a maximum of three mixed participants. We typically allow // a +/- 10% range around the expected output level to account for distortion // from coding and processing in the loopback chain. TEST_F(MixingTest, FourChannelsWithOnlyThreeMixed) { const int16_t kInputValue = 1000; const int16_t kExpectedOutput = kInputValue * 3; RunMixingTest(4, 0, 4, kInputValue, 1.1 * kExpectedOutput, 0.9 * kExpectedOutput); } // Ensure the mixing saturation protection is working. We can do this because // the mixing limiter is given some headroom, so the expected output is less // than full scale. TEST_F(MixingTest, VerifySaturationProtection) { const int16_t kInputValue = 20000; const int16_t kExpectedOutput = kLimiterHeadroom; // If this isn't satisfied, we're not testing anything. ASSERT_GT(kInputValue * 3, kInt16Max); ASSERT_LT(1.1 * kExpectedOutput, kInt16Max); RunMixingTest(3, 0, 3, kInputValue, 1.1 * kExpectedOutput, 0.9 * kExpectedOutput); } TEST_F(MixingTest, SaturationProtectionHasNoEffectOnOneChannel) { const int16_t kInputValue = kInt16Max; const int16_t kExpectedOutput = kInt16Max; // If this isn't satisfied, we're not testing anything. ASSERT_GT(0.95 * kExpectedOutput, kLimiterHeadroom); // Tighter constraints are required here to properly test this. RunMixingTest(1, 0, 1, kInputValue, kExpectedOutput, 0.95 * kExpectedOutput); } TEST_F(MixingTest, VerifyAnonymousAndNormalParticipantMixing) { const int16_t kInputValue = 1000; const int16_t kExpectedOutput = kInputValue * 2; RunMixingTest(1, 1, 1, kInputValue, 1.1 * kExpectedOutput, 0.9 * kExpectedOutput); } TEST_F(MixingTest, AnonymousParticipantsAreAlwaysMixed) { const int16_t kInputValue = 1000; const int16_t kExpectedOutput = kInputValue * 4; RunMixingTest(3, 1, 3, kInputValue, 1.1 * kExpectedOutput, 0.9 * kExpectedOutput); } TEST_F(MixingTest, VerifyStereoAndMonoMixing) { const int16_t kInputValue = 1000; const int16_t kExpectedOutput = kInputValue * 2; RunMixingTest(2, 0, 1, kInputValue, 1.1 * kExpectedOutput, 0.9 * kExpectedOutput); } } // namespace webrtc <commit_msg>Disabling MixingTests due to race conditions.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <stdio.h> #include <string> #include "after_initialization_fixture.h" #include "test/testsupport/fileutils.h" namespace webrtc { namespace { const int16_t kLimiterHeadroom = 29204; // == -1 dbFS const int16_t kInt16Max = 0x7fff; const int kSampleRateHz = 16000; const int kTestDurationMs = 3000; const int kSkipOutputMs = 500; } // namespace class MixingTest : public AfterInitializationFixture { protected: MixingTest() : input_filename_(test::OutputPath() + "mixing_test_input.pcm"), output_filename_(test::OutputPath() + "mixing_test_output.pcm") { } void SetUp() { transport_ = new LoopBackTransport(voe_network_); } void TearDown() { delete transport_; } // Creates and mixes |num_remote_streams| which play a file "as microphone" // with |num_local_streams| which play a file "locally", using a constant // amplitude of |input_value|. The local streams manifest as "anonymous" // mixing participants, meaning they will be mixed regardless of the number // of participants. (A stream is a VoiceEngine "channel"). // // The mixed output is verified to always fall between |max_output_value| and // |min_output_value|, after a startup phase. // // |num_remote_streams_using_mono| of the remote streams use mono, with the // remainder using stereo. void RunMixingTest(int num_remote_streams, int num_local_streams, int num_remote_streams_using_mono, int16_t input_value, int16_t max_output_value, int16_t min_output_value) { ASSERT_LE(num_remote_streams_using_mono, num_remote_streams); GenerateInputFile(input_value); std::vector<int> local_streams(num_local_streams); for (size_t i = 0; i < local_streams.size(); ++i) { local_streams[i] = voe_base_->CreateChannel(); EXPECT_NE(-1, local_streams[i]); } StartLocalStreams(local_streams); TEST_LOG("Playing %d local streams.\n", num_local_streams); std::vector<int> remote_streams(num_remote_streams); for (size_t i = 0; i < remote_streams.size(); ++i) { remote_streams[i] = voe_base_->CreateChannel(); EXPECT_NE(-1, remote_streams[i]); } StartRemoteStreams(remote_streams, num_remote_streams_using_mono); TEST_LOG("Playing %d remote streams.\n", num_remote_streams); // Start recording the mixed output and wait. EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1 /* record meeting */, output_filename_.c_str())); Sleep(kTestDurationMs); EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1)); StopLocalStreams(local_streams); StopRemoteStreams(remote_streams); VerifyMixedOutput(max_output_value, min_output_value); } private: // Generate input file with constant values equal to |input_value|. The file // will be one second longer than the duration of the test. void GenerateInputFile(int16_t input_value) { FILE* input_file = fopen(input_filename_.c_str(), "wb"); ASSERT_TRUE(input_file != NULL); for (int i = 0; i < kSampleRateHz / 1000 * (kTestDurationMs + 1000); i++) { ASSERT_EQ(1u, fwrite(&input_value, sizeof(input_value), 1, input_file)); } ASSERT_EQ(0, fclose(input_file)); } void VerifyMixedOutput(int16_t max_output_value, int16_t min_output_value) { // Verify the mixed output. FILE* output_file = fopen(output_filename_.c_str(), "rb"); ASSERT_TRUE(output_file != NULL); int16_t output_value = 0; // Skip the first segment to avoid initialization and ramping-in effects. EXPECT_EQ(0, fseek(output_file, sizeof(output_value) * kSampleRateHz / 1000 * kSkipOutputMs, SEEK_SET)); int samples_read = 0; while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) { samples_read++; std::ostringstream trace_stream; trace_stream << samples_read << " samples read"; SCOPED_TRACE(trace_stream.str()); EXPECT_LE(output_value, max_output_value); EXPECT_GE(output_value, min_output_value); } // Ensure the recording length is close to the duration of the test. // We have to use a relaxed tolerance here due to filesystem flakiness on // the bots. ASSERT_GE((samples_read * 1000.0) / kSampleRateHz, 0.7 * (kTestDurationMs - kSkipOutputMs)); // Ensure we read the entire file. ASSERT_NE(0, feof(output_file)); ASSERT_EQ(0, fclose(output_file)); } // Start up local streams ("anonymous" participants). void StartLocalStreams(const std::vector<int>& streams) { for (size_t i = 0; i < streams.size(); ++i) { EXPECT_EQ(0, voe_base_->StartPlayout(streams[i])); EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(streams[i], input_filename_.c_str(), true)); } } void StopLocalStreams(const std::vector<int>& streams) { for (size_t i = 0; i < streams.size(); ++i) { EXPECT_EQ(0, voe_base_->StopPlayout(streams[i])); EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i])); } } // Start up remote streams ("normal" participants). void StartRemoteStreams(const std::vector<int>& streams, int num_remote_streams_using_mono) { // Use L16 at 16kHz to minimize distortion (file recording is 16kHz and // resampling will cause distortion). CodecInst codec_inst; strcpy(codec_inst.plname, "L16"); codec_inst.channels = 1; codec_inst.plfreq = kSampleRateHz; codec_inst.pltype = 105; codec_inst.pacsize = codec_inst.plfreq / 100; codec_inst.rate = codec_inst.plfreq * sizeof(int16_t) * 8; // 8 bits/byte. for (int i = 0; i < num_remote_streams_using_mono; ++i) { StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i); } // The remainder of the streams will use stereo. codec_inst.channels = 2; codec_inst.pltype++; for (size_t i = num_remote_streams_using_mono; i < streams.size(); ++i) { StartRemoteStream(streams[i], codec_inst, 1234 + 2 * i); } } // Start up a single remote stream. void StartRemoteStream(int stream, const CodecInst& codec_inst, int port) { EXPECT_EQ(0, voe_codec_->SetRecPayloadType(stream, codec_inst)); EXPECT_EQ(0, voe_network_->RegisterExternalTransport(stream, *transport_)); EXPECT_EQ(0, voe_base_->StartReceive(stream)); EXPECT_EQ(0, voe_base_->StartPlayout(stream)); EXPECT_EQ(0, voe_codec_->SetSendCodec(stream, codec_inst)); EXPECT_EQ(0, voe_base_->StartSend(stream)); EXPECT_EQ(0, voe_file_->StartPlayingFileAsMicrophone(stream, input_filename_.c_str(), true)); } void StopRemoteStreams(const std::vector<int>& streams) { for (size_t i = 0; i < streams.size(); ++i) { EXPECT_EQ(0, voe_base_->StopSend(streams[i])); EXPECT_EQ(0, voe_base_->StopPlayout(streams[i])); EXPECT_EQ(0, voe_base_->StopReceive(streams[i])); EXPECT_EQ(0, voe_network_->DeRegisterExternalTransport(streams[i])); EXPECT_EQ(0, voe_base_->DeleteChannel(streams[i])); } } const std::string input_filename_; const std::string output_filename_; LoopBackTransport* transport_; }; // These tests assume a maximum of three mixed participants. We typically allow // a +/- 10% range around the expected output level to account for distortion // from coding and processing in the loopback chain. TEST_F(MixingTest, DISABLED_FourChannelsWithOnlyThreeMixed) { const int16_t kInputValue = 1000; const int16_t kExpectedOutput = kInputValue * 3; RunMixingTest(4, 0, 4, kInputValue, 1.1 * kExpectedOutput, 0.9 * kExpectedOutput); } // Ensure the mixing saturation protection is working. We can do this because // the mixing limiter is given some headroom, so the expected output is less // than full scale. TEST_F(MixingTest, DISABLED_VerifySaturationProtection) { const int16_t kInputValue = 20000; const int16_t kExpectedOutput = kLimiterHeadroom; // If this isn't satisfied, we're not testing anything. ASSERT_GT(kInputValue * 3, kInt16Max); ASSERT_LT(1.1 * kExpectedOutput, kInt16Max); RunMixingTest(3, 0, 3, kInputValue, 1.1 * kExpectedOutput, 0.9 * kExpectedOutput); } TEST_F(MixingTest, DISABLED_SaturationProtectionHasNoEffectOnOneChannel) { const int16_t kInputValue = kInt16Max; const int16_t kExpectedOutput = kInt16Max; // If this isn't satisfied, we're not testing anything. ASSERT_GT(0.95 * kExpectedOutput, kLimiterHeadroom); // Tighter constraints are required here to properly test this. RunMixingTest(1, 0, 1, kInputValue, kExpectedOutput, 0.95 * kExpectedOutput); } TEST_F(MixingTest, DISABLED_VerifyAnonymousAndNormalParticipantMixing) { const int16_t kInputValue = 1000; const int16_t kExpectedOutput = kInputValue * 2; RunMixingTest(1, 1, 1, kInputValue, 1.1 * kExpectedOutput, 0.9 * kExpectedOutput); } TEST_F(MixingTest, DISABLED_AnonymousParticipantsAreAlwaysMixed) { const int16_t kInputValue = 1000; const int16_t kExpectedOutput = kInputValue * 4; RunMixingTest(3, 1, 3, kInputValue, 1.1 * kExpectedOutput, 0.9 * kExpectedOutput); } TEST_F(MixingTest, DISABLED_VerifyStereoAndMonoMixing) { const int16_t kInputValue = 1000; const int16_t kExpectedOutput = kInputValue * 2; RunMixingTest(2, 0, 1, kInputValue, 1.1 * kExpectedOutput, 0.9 * kExpectedOutput); } } // namespace webrtc <|endoftext|>
<commit_before>#include <iostream> #include <chrono> #include <pathfind/GraphReader.h> #include <pathfind/Graph.h> #include <pathfind/AStar.h> int main(int argc, char* argv[]) { // Read graph from file std::cout << "Loading graph from json file..." << std::endl; pathfind::GraphReader graphReader("../test/sa_nodes.json"); auto start = std::chrono::system_clock::now(); std::unique_ptr<pathfind::Graph> graph = graphReader.Read(); std::cout << "Done! (Took " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count() << "ms)" << std::endl; // Create instance of AStar pathfind::AStar pathfind(graph.get(), Vector3(-2427.625, -2474.75, 35.75), Vector3(0.0f, 0.0f, 0.0f)); // Run algorithm start = std::chrono::system_clock::now(); std::vector<pathfind::GraphNode*> path = pathfind.CalculateShortestPath(); std::cout << "Found a route in " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count() << "ms" << std::endl; // Print path std::cout << "Calculating path: \n"; for (pathfind::GraphNode* node : path) { std::cout << "Node " << node->id << " (" << node->position.GetX() << ", " << node->position.GetY() << ", " << node->position.GetZ() << ")\n"; } if (path.empty()) std::cout << "No path found"; std::cout << std::endl; std::cin.get(); return 0; } <commit_msg>Add initial node find benchmark Result: Finding start and end node takes only 1/10ms so it's not worth optimizing it<commit_after>#include <iostream> #include <chrono> #include <pathfind/GraphReader.h> #include <pathfind/Graph.h> #include <pathfind/AStar.h> int main(int argc, char* argv[]) { // Read graph from file std::cout << "Loading graph from json file..." << std::endl; pathfind::GraphReader graphReader("../test/sa_nodes.json"); auto start = std::chrono::system_clock::now(); std::unique_ptr<pathfind::Graph> graph = graphReader.Read(); std::cout << "Done! (Took " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count() << "ms)" << std::endl; // Create instance of AStar start = std::chrono::system_clock::now(); pathfind::AStar pathfind(graph.get(), Vector3(-2427.625, -2474.75, 35.75), Vector3(0.0f, 0.0f, 0.0f)); std::cout << "Found a start node in " << std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now() - start).count() << "micro s" << std::endl; // Run algorithm start = std::chrono::system_clock::now(); std::vector<pathfind::GraphNode*> path = pathfind.CalculateShortestPath(); std::cout << "Found a route in " << std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start).count() << "ms" << std::endl; // Print path std::cout << "Calculating path: \n"; for (pathfind::GraphNode* node : path) { std::cout << "Node " << node->id << " (" << node->position.GetX() << ", " << node->position.GetY() << ", " << node->position.GetZ() << ")\n"; } if (path.empty()) std::cout << "No path found"; std::cout << std::endl; std::cin.get(); return 0; } <|endoftext|>
<commit_before>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2017 Ryo Suzuki // Copyright (c) 2016-2017 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/Platform.hpp> # if defined(SIV3D_TARGET_LINUX) # include "../../ThirdParty/GLFW/include/GLFW/glfw3.h" # include "../Siv3DEngine.hpp" # include "CKeyboard_Linux.hpp" namespace s3d { namespace detail { constexpr std::pair<uint8, uint16> KeyConversionTable[] { { 0x03, 0 }, { 0x08, GLFW_KEY_BACKSPACE }, { 0x09, GLFW_KEY_TAB }, { 0x0C, 0 }, { 0x0D, GLFW_KEY_ENTER }, { 0x10, 0 }, // shift { 0x11, 0 }, // control { 0x12, 0 }, // alt { 0x13, GLFW_KEY_PAUSE }, { 0x1B, GLFW_KEY_ESCAPE }, { 0x20, GLFW_KEY_SPACE }, { 0x21, GLFW_KEY_PAGE_UP }, { 0x22, GLFW_KEY_PAGE_DOWN }, { 0x23, GLFW_KEY_END }, { 0x24, GLFW_KEY_HOME }, { 0x25, GLFW_KEY_LEFT }, { 0x26, GLFW_KEY_UP }, { 0x27, GLFW_KEY_RIGHT }, { 0x28, GLFW_KEY_DOWN }, { 0x2C, GLFW_KEY_PRINT_SCREEN }, { 0x2D, GLFW_KEY_INSERT }, { 0x2E, GLFW_KEY_DELETE }, { 0x30, GLFW_KEY_0 }, { 0x31, GLFW_KEY_1 }, { 0x32, GLFW_KEY_2 }, { 0x33, GLFW_KEY_3 }, { 0x34, GLFW_KEY_4 }, { 0x35, GLFW_KEY_5 }, { 0x36, GLFW_KEY_6 }, { 0x37, GLFW_KEY_7 }, { 0x38, GLFW_KEY_8 }, { 0x39, GLFW_KEY_9 }, { 0x41, GLFW_KEY_A }, { 0x42, GLFW_KEY_B }, { 0x43, GLFW_KEY_C }, { 0x44, GLFW_KEY_D }, { 0x45, GLFW_KEY_E }, { 0x46, GLFW_KEY_F }, { 0x47, GLFW_KEY_G }, { 0x48, GLFW_KEY_H }, { 0x49, GLFW_KEY_I }, { 0x4A, GLFW_KEY_J }, { 0x4B, GLFW_KEY_K }, { 0x4C, GLFW_KEY_L }, { 0x4D, GLFW_KEY_M }, { 0x4E, GLFW_KEY_N }, { 0x4F, GLFW_KEY_O }, { 0x50, GLFW_KEY_P }, { 0x51, GLFW_KEY_Q }, { 0x52, GLFW_KEY_R }, { 0x53, GLFW_KEY_S }, { 0x54, GLFW_KEY_T }, { 0x55, GLFW_KEY_U }, { 0x56, GLFW_KEY_V }, { 0x57, GLFW_KEY_W }, { 0x58, GLFW_KEY_X }, { 0x59, GLFW_KEY_Y }, { 0x5A, GLFW_KEY_Z }, { 0x60, GLFW_KEY_KP_0 }, { 0x61, GLFW_KEY_KP_1 }, { 0x62, GLFW_KEY_KP_2 }, { 0x63, GLFW_KEY_KP_3 }, { 0x64, GLFW_KEY_KP_4 }, { 0x65, GLFW_KEY_KP_5 }, { 0x66, GLFW_KEY_KP_6 }, { 0x67, GLFW_KEY_KP_7 }, { 0x68, GLFW_KEY_KP_8 }, { 0x69, GLFW_KEY_KP_9 }, { 0x6A, GLFW_KEY_KP_MULTIPLY }, { 0x6B, GLFW_KEY_KP_ADD }, { 0x6C, GLFW_KEY_KP_ENTER }, { 0x6D, GLFW_KEY_KP_SUBTRACT }, { 0x6E, GLFW_KEY_KP_DECIMAL }, { 0x6F, GLFW_KEY_KP_DIVIDE }, { 0x70, GLFW_KEY_F1 }, { 0x71, GLFW_KEY_F2 }, { 0x72, GLFW_KEY_F3 }, { 0x73, GLFW_KEY_F4 }, { 0x74, GLFW_KEY_F5 }, { 0x75, GLFW_KEY_F6 }, { 0x76, GLFW_KEY_F7 }, { 0x77, GLFW_KEY_F8 }, { 0x78, GLFW_KEY_F9 }, { 0x79, GLFW_KEY_F10 }, { 0x7A, GLFW_KEY_F11 }, { 0x7B, GLFW_KEY_F12 }, { 0x7C, GLFW_KEY_F13 }, { 0x7D, GLFW_KEY_F14 }, { 0x7E, GLFW_KEY_F15 }, { 0x7F, GLFW_KEY_F16 }, { 0x80, GLFW_KEY_F17 }, { 0x81, GLFW_KEY_F18 }, { 0x82, GLFW_KEY_F19 }, { 0x83, GLFW_KEY_F20 }, { 0x84, GLFW_KEY_F21 }, { 0x85, GLFW_KEY_F22 }, { 0x86, GLFW_KEY_F23 }, { 0x87, GLFW_KEY_F24 }, { 0x90, GLFW_KEY_NUM_LOCK }, { 0xA0, GLFW_KEY_LEFT_SHIFT }, { 0xA1, GLFW_KEY_RIGHT_SHIFT }, { 0xA2, GLFW_KEY_LEFT_CONTROL }, { 0xA3, GLFW_KEY_RIGHT_CONTROL }, { 0xA4, GLFW_KEY_LEFT_ALT }, { 0xA5, GLFW_KEY_RIGHT_ALT }, { 0xB0, 0 }, // media next track { 0xB1, 0 }, // media previous track { 0xB2, 0 }, // media stop { 0xB3, 0 }, // media play/pause { 0xBA, GLFW_KEY_APOSTROPHE }, // ? [Siv3D TODO] { 0xBB, GLFW_KEY_SEMICOLON }, // ? [Siv3D TODO] { 0xBC, GLFW_KEY_COMMA }, { 0xBD, GLFW_KEY_MINUS }, { 0xBE, GLFW_KEY_PERIOD }, { 0xBF, GLFW_KEY_SLASH }, { 0xC0, GLFW_KEY_GRAVE_ACCENT }, // ? [Siv3D TODO] { 0xD8, 0 }, // command { 0xD9, GLFW_KEY_LEFT_SUPER }, { 0xDA, GLFW_KEY_RIGHT_SUPER }, { 0xDB, GLFW_KEY_LEFT_BRACKET }, // ? [Siv3D TODO] { 0xDC, GLFW_KEY_BACKSLASH }, // ? [Siv3D TODO] { 0xDD, GLFW_KEY_RIGHT_BRACKET }, // ? [Siv3D TODO] { 0xDE, 0 }, // ? [Siv3D TODO] { 0xE2, 0 }, // ? [Siv3D TODO] }; } CKeyboard_Linux::CKeyboard_Linux() { } CKeyboard_Linux::~CKeyboard_Linux() { } bool CKeyboard_Linux::init() { m_glfwWindow = Siv3DEngine::GetWindow()->getHandle(); return true; } void CKeyboard_Linux::update() { const char* keys = ::glfwGetKeysSiv3D(m_glfwWindow); for (const auto& keyPair : detail::KeyConversionTable) { const bool pressed = (keys[keyPair.second] == GLFW_PRESS); m_states[keyPair.first].update(pressed); } const bool shiftPressed = (keys[GLFW_KEY_LEFT_SHIFT] == GLFW_PRESS) || (keys[GLFW_KEY_RIGHT_SHIFT] == GLFW_PRESS); m_states[0x10].update(shiftPressed); const bool controlPressed = (keys[GLFW_KEY_LEFT_CONTROL] == GLFW_PRESS) || (keys[GLFW_KEY_RIGHT_CONTROL] == GLFW_PRESS); m_states[0x11].update(controlPressed); const bool altPressed = (keys[GLFW_KEY_LEFT_ALT] == GLFW_PRESS) || (keys[GLFW_KEY_RIGHT_ALT] == GLFW_PRESS); m_states[0x12].update(altPressed); const bool commandPressed = (keys[GLFW_KEY_LEFT_SUPER] == GLFW_PRESS) || (keys[GLFW_KEY_RIGHT_SUPER] == GLFW_PRESS); m_states[0xD8].update(commandPressed); } bool CKeyboard_Linux::down(const uint32 index) const { return m_states[index].down; } bool CKeyboard_Linux::pressed(const uint32 index) const { return m_states[index].pressed; } bool CKeyboard_Linux::up(const uint32 index) const { return m_states[index].up; } MillisecondsF CKeyboard_Linux::pressedDuration(const uint32 index) const { return m_states[index].pressedDuration; } } # endif <commit_msg>インクルード順入れ替え<commit_after>//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2017 Ryo Suzuki // Copyright (c) 2016-2017 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/Platform.hpp> # if defined(SIV3D_TARGET_LINUX) # include "../Siv3DEngine.hpp" # include "CKeyboard_Linux.hpp" # include "../../ThirdParty/GLFW/include/GLFW/glfw3.h" namespace s3d { namespace detail { constexpr std::pair<uint8, uint16> KeyConversionTable[] { { 0x03, 0 }, { 0x08, GLFW_KEY_BACKSPACE }, { 0x09, GLFW_KEY_TAB }, { 0x0C, 0 }, { 0x0D, GLFW_KEY_ENTER }, { 0x10, 0 }, // shift { 0x11, 0 }, // control { 0x12, 0 }, // alt { 0x13, GLFW_KEY_PAUSE }, { 0x1B, GLFW_KEY_ESCAPE }, { 0x20, GLFW_KEY_SPACE }, { 0x21, GLFW_KEY_PAGE_UP }, { 0x22, GLFW_KEY_PAGE_DOWN }, { 0x23, GLFW_KEY_END }, { 0x24, GLFW_KEY_HOME }, { 0x25, GLFW_KEY_LEFT }, { 0x26, GLFW_KEY_UP }, { 0x27, GLFW_KEY_RIGHT }, { 0x28, GLFW_KEY_DOWN }, { 0x2C, GLFW_KEY_PRINT_SCREEN }, { 0x2D, GLFW_KEY_INSERT }, { 0x2E, GLFW_KEY_DELETE }, { 0x30, GLFW_KEY_0 }, { 0x31, GLFW_KEY_1 }, { 0x32, GLFW_KEY_2 }, { 0x33, GLFW_KEY_3 }, { 0x34, GLFW_KEY_4 }, { 0x35, GLFW_KEY_5 }, { 0x36, GLFW_KEY_6 }, { 0x37, GLFW_KEY_7 }, { 0x38, GLFW_KEY_8 }, { 0x39, GLFW_KEY_9 }, { 0x41, GLFW_KEY_A }, { 0x42, GLFW_KEY_B }, { 0x43, GLFW_KEY_C }, { 0x44, GLFW_KEY_D }, { 0x45, GLFW_KEY_E }, { 0x46, GLFW_KEY_F }, { 0x47, GLFW_KEY_G }, { 0x48, GLFW_KEY_H }, { 0x49, GLFW_KEY_I }, { 0x4A, GLFW_KEY_J }, { 0x4B, GLFW_KEY_K }, { 0x4C, GLFW_KEY_L }, { 0x4D, GLFW_KEY_M }, { 0x4E, GLFW_KEY_N }, { 0x4F, GLFW_KEY_O }, { 0x50, GLFW_KEY_P }, { 0x51, GLFW_KEY_Q }, { 0x52, GLFW_KEY_R }, { 0x53, GLFW_KEY_S }, { 0x54, GLFW_KEY_T }, { 0x55, GLFW_KEY_U }, { 0x56, GLFW_KEY_V }, { 0x57, GLFW_KEY_W }, { 0x58, GLFW_KEY_X }, { 0x59, GLFW_KEY_Y }, { 0x5A, GLFW_KEY_Z }, { 0x60, GLFW_KEY_KP_0 }, { 0x61, GLFW_KEY_KP_1 }, { 0x62, GLFW_KEY_KP_2 }, { 0x63, GLFW_KEY_KP_3 }, { 0x64, GLFW_KEY_KP_4 }, { 0x65, GLFW_KEY_KP_5 }, { 0x66, GLFW_KEY_KP_6 }, { 0x67, GLFW_KEY_KP_7 }, { 0x68, GLFW_KEY_KP_8 }, { 0x69, GLFW_KEY_KP_9 }, { 0x6A, GLFW_KEY_KP_MULTIPLY }, { 0x6B, GLFW_KEY_KP_ADD }, { 0x6C, GLFW_KEY_KP_ENTER }, { 0x6D, GLFW_KEY_KP_SUBTRACT }, { 0x6E, GLFW_KEY_KP_DECIMAL }, { 0x6F, GLFW_KEY_KP_DIVIDE }, { 0x70, GLFW_KEY_F1 }, { 0x71, GLFW_KEY_F2 }, { 0x72, GLFW_KEY_F3 }, { 0x73, GLFW_KEY_F4 }, { 0x74, GLFW_KEY_F5 }, { 0x75, GLFW_KEY_F6 }, { 0x76, GLFW_KEY_F7 }, { 0x77, GLFW_KEY_F8 }, { 0x78, GLFW_KEY_F9 }, { 0x79, GLFW_KEY_F10 }, { 0x7A, GLFW_KEY_F11 }, { 0x7B, GLFW_KEY_F12 }, { 0x7C, GLFW_KEY_F13 }, { 0x7D, GLFW_KEY_F14 }, { 0x7E, GLFW_KEY_F15 }, { 0x7F, GLFW_KEY_F16 }, { 0x80, GLFW_KEY_F17 }, { 0x81, GLFW_KEY_F18 }, { 0x82, GLFW_KEY_F19 }, { 0x83, GLFW_KEY_F20 }, { 0x84, GLFW_KEY_F21 }, { 0x85, GLFW_KEY_F22 }, { 0x86, GLFW_KEY_F23 }, { 0x87, GLFW_KEY_F24 }, { 0x90, GLFW_KEY_NUM_LOCK }, { 0xA0, GLFW_KEY_LEFT_SHIFT }, { 0xA1, GLFW_KEY_RIGHT_SHIFT }, { 0xA2, GLFW_KEY_LEFT_CONTROL }, { 0xA3, GLFW_KEY_RIGHT_CONTROL }, { 0xA4, GLFW_KEY_LEFT_ALT }, { 0xA5, GLFW_KEY_RIGHT_ALT }, { 0xB0, 0 }, // media next track { 0xB1, 0 }, // media previous track { 0xB2, 0 }, // media stop { 0xB3, 0 }, // media play/pause { 0xBA, GLFW_KEY_APOSTROPHE }, // ? [Siv3D TODO] { 0xBB, GLFW_KEY_SEMICOLON }, // ? [Siv3D TODO] { 0xBC, GLFW_KEY_COMMA }, { 0xBD, GLFW_KEY_MINUS }, { 0xBE, GLFW_KEY_PERIOD }, { 0xBF, GLFW_KEY_SLASH }, { 0xC0, GLFW_KEY_GRAVE_ACCENT }, // ? [Siv3D TODO] { 0xD8, 0 }, // command { 0xD9, GLFW_KEY_LEFT_SUPER }, { 0xDA, GLFW_KEY_RIGHT_SUPER }, { 0xDB, GLFW_KEY_LEFT_BRACKET }, // ? [Siv3D TODO] { 0xDC, GLFW_KEY_BACKSLASH }, // ? [Siv3D TODO] { 0xDD, GLFW_KEY_RIGHT_BRACKET }, // ? [Siv3D TODO] { 0xDE, 0 }, // ? [Siv3D TODO] { 0xE2, 0 }, // ? [Siv3D TODO] }; } CKeyboard_Linux::CKeyboard_Linux() { } CKeyboard_Linux::~CKeyboard_Linux() { } bool CKeyboard_Linux::init() { m_glfwWindow = Siv3DEngine::GetWindow()->getHandle(); return true; } void CKeyboard_Linux::update() { const char* keys = ::glfwGetKeysSiv3D(m_glfwWindow); for (const auto& keyPair : detail::KeyConversionTable) { const bool pressed = (keys[keyPair.second] == GLFW_PRESS); m_states[keyPair.first].update(pressed); } const bool shiftPressed = (keys[GLFW_KEY_LEFT_SHIFT] == GLFW_PRESS) || (keys[GLFW_KEY_RIGHT_SHIFT] == GLFW_PRESS); m_states[0x10].update(shiftPressed); const bool controlPressed = (keys[GLFW_KEY_LEFT_CONTROL] == GLFW_PRESS) || (keys[GLFW_KEY_RIGHT_CONTROL] == GLFW_PRESS); m_states[0x11].update(controlPressed); const bool altPressed = (keys[GLFW_KEY_LEFT_ALT] == GLFW_PRESS) || (keys[GLFW_KEY_RIGHT_ALT] == GLFW_PRESS); m_states[0x12].update(altPressed); const bool commandPressed = (keys[GLFW_KEY_LEFT_SUPER] == GLFW_PRESS) || (keys[GLFW_KEY_RIGHT_SUPER] == GLFW_PRESS); m_states[0xD8].update(commandPressed); } bool CKeyboard_Linux::down(const uint32 index) const { return m_states[index].down; } bool CKeyboard_Linux::pressed(const uint32 index) const { return m_states[index].pressed; } bool CKeyboard_Linux::up(const uint32 index) const { return m_states[index].up; } MillisecondsF CKeyboard_Linux::pressedDuration(const uint32 index) const { return m_states[index].pressedDuration; } } # endif <|endoftext|>
<commit_before>#include <cstdio> #include <algorithm> #include <string> #include <map> #include <cstdlib> using namespace std; map <string ,int> Dict; FILE *fp; //debug fp=stdio; string getword(){ char ch; string s; while((ch=getc(fp))!=EOF){ if(ch=='-'){ if(getc(fp)=='\n'){ continue; }else{ fseek(fp,ftell(fp)-1); break; } } if(ch>'A'&&ch<'Z' || ch>'a'&&ch<'z') s.push_back(ch); else break; } } int main(int argc, char const *argv[]) { /* code */ return 0; } <commit_msg>update uoj1109<commit_after>#include <cstdio> #include <algorithm> #include <string> #include <map> #include <cstdlib> using namespace std; map <string ,int> Dict; FILE *fp; //debug fp=stdio; string getword(){ char ch; string s; while((ch=getc(fp))!=EOF){ if(ch=='-'){ if(getc(fp)=='\n'){ continue; }else{ fseek(fp,ftell(fp)-1,SEEK_CUR); break; } } if(ch>'A'&&ch<'Z' || ch>'a'&&ch<'z') s.push_back(ch); else break; } } int main(int argc, char const *argv[]) { /* code */ return 0; } <|endoftext|>
<commit_before>#include <stdio.h> #include <queue> #include <vector> #include <utility> #include <string> #include <stack> typedef user pair<int,string> stack<string> lv1; stack<string> lv2; stack<string> lv3; string temp; int templv; int temptime=0; int read(int now){ if(now < temptime) return 0; do{ if(temp.empty()){ }else{ switch(templv){ case 1: lv1.push(temp);break; case 2: lv2.push(temp);break; case 3: lv3.push(temp);break; } } cin >>temptime>>templv>>temp; }while(temptime>=now); } int main(int argc, char const *argv[]) { whlie(1){ read(); cout<<lv1.size()<<lv2.size()<<lv3.size(); } return 0; }<commit_msg>update uoj2254<commit_after>#include <stdio.h> #include <queue> #include <vector> #include <utility> #include <string> #include <stack> stack<string> lv1; stack<string> lv2; stack<string> lv3; string temp; int templv; int temptime=0; int read(int now){ if(now < temptime) return 0; do{ if(temp.empty()){ }else{ switch(templv){ case 1: lv1.push(temp);break; case 2: lv2.push(temp);break; case 3: lv3.push(temp);break; } } cin >>temptime>>templv>>temp; }while(temptime>=now); } int main(int argc, char const *argv[]) { whlie(1){ read(); cout<<lv1.size()<<lv2.size()<<lv3.size(); } return 0; }<|endoftext|>
<commit_before>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); const int maxw=50000; double dp[maxw+10]; struct node { int a,b; bool operator <(const node t) const { return 1.0*b/a>1.0*t.b/t.a;//单价最高的 } }wa[110],st[110]; double Greed(int n,int w) { double sum=0; int i=0; while(w&&i<n) { if(w>=wa[i].a)//从单价最高的开始取,取到不能全部放入 { sum+=wa[i].b; w-=wa[i++].a; } else//不能全部放入就放满 { sum+=w*1.0*wa[i].b/wa[i].a; w=0; } } return sum; } int n,w; int c,i,l=0,r=0; void Init(){ memset(dp,0,sizeof(dp)); for(i=0;i<n;i++) { scanf("%d%d%d",&st[l].a,&st[l].b,&c); if(c) wa[r++]=st[l]; else l++; } sort(wa,wa+r); return ; } void Solve(){ //先全部放水 REP(i,1,w) dp[i]=Greed(r,i); //01背包咯 REP(i,0,l-1) REPD(j,w,st[i].a) dp[j]>?=(dp[j-st[i].a]+st[i].b); printf("%.2lf\n",dp[w]); return ; } int main(){ freopen("uoj9513.in","r",stdin); while(~scanf("%d%d",&n,&w)) Init(),Solve(); return 0; }<commit_msg>update uoj9513<commit_after>#include <iostream> #include <cstdio> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <cstring> #include <string> #include <vector> #include <iomanip> #include <cmath> #include <list> #include <bitset> using namespace std; #define ll long long #define lson l,mid,id<<1 #define rson mid+1,r,id<<1|1 typedef pair<int, int>pii; typedef pair<ll, ll>pll; typedef pair<double, double>pdd; const double eps = 1e-6; const ll LINF = 0x3f3f3f3f3f3f3f3fLL; const int INF = 0x3f3f3f3f; const double FINF = 1e18; #define x first #define y second #define REP(i,j,k) for(int i =(j);i<=(k);i++) #define REPD(i,j,k) for(int i =(j);i>=(k);i--) #define print(x) cout<<(x)<<endl; #define IOS ios::sync_with_stdio(0);cin.tie(0); const int maxw=50000; double dp[maxw+10]; struct node { int a,b; bool operator <(const node t) const { return 1.0*b/a>1.0*t.b/t.a;//单价最高的 } }wa[110],st[110]; double Greed(int n,int w) { double sum=0; int i=0; while(w&&i<n) { if(w>=wa[i].a)//从单价最高的开始取,取到不能全部放入 { sum+=wa[i].b; w-=wa[i++].a; } else//不能全部放入就放满 { sum+=w*1.0*wa[i].b/wa[i].a; w=0; } } return sum; } int n,w; int c,i,l=0,r=0; void Init(){ memset(dp,0,sizeof(dp)); for(i=0;i<n;i++) { scanf("%d%d%d",&st[l].a,&st[l].b,&c); if(c) wa[r++]=st[l]; else l++; } sort(wa,wa+r); return ; } void Solve(){ //先全部放水 REP(i,1,w) dp[i]=Greed(r,i); //01背包咯 REP(i,0,l-1) REPD(j,w,st[i].a) dp[j]=max(dp[j],dp[j-st[i].a]+st[i].b); printf("%.2lf\n",dp[w]); return ; } int main(){ freopen("uoj9513.in","r",stdin); while(~scanf("%d%d",&n,&w)) Init(),Solve(); return 0; }<|endoftext|>
<commit_before>/* * LibCassandra * Copyright (C) 2010 Padraig O'Sullivan * All rights reserved. * * Use and distribution licensed under the BSD license. See * the COPYING file in the parent directory for full text. */ #include <string> #include <set> #include <iostream> #include <sstream> #include <protocol/TBinaryProtocol.h> #include <transport/TSocket.h> #include <transport/TTransportUtils.h> #include <gtest/gtest.h> #include <libgenthrift/Cassandra.h> #include <libcassandra/cassandra.h> #include <libcassandra/cassandra_factory.h> #include <libcassandra/column_family_definition.h> #include <libcassandra/keyspace.h> #include <libcassandra/keyspace_definition.h> using namespace std; using namespace libcassandra; using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace org::apache::cassandra; using namespace boost; class ClientTest : public testing::Test { protected: virtual void SetUp() { const string host("localhost"); int port= 9160; cf= tr1::shared_ptr<CassandraFactory>(new CassandraFactory(host, port)); c= tr1::shared_ptr<Cassandra>(cf->create()); } tr1::shared_ptr<CassandraFactory> cf; tr1::shared_ptr<Cassandra> c; }; TEST(Cassandra, DefaultConstructor) { const Cassandra c; EXPECT_EQ(0, c.getPort()); } TEST(Cassandra, ConsructorFromHostAndPort) { const string host("localhost"); int port= 9160; boost::shared_ptr<TTransport> socket(new TSocket(host, port)); boost::shared_ptr<TTransport> transport(new TFramedTransport(socket)); boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); CassandraClient *client= new CassandraClient(protocol); transport->open(); Cassandra c(client, host, port); EXPECT_EQ(client, c.getCassandra()); EXPECT_EQ(host, c.getHost()); EXPECT_EQ(port, c.getPort()); EXPECT_STREQ("localhost", c.getHost().c_str()); } TEST(Cassandra, GetServerVersion) { const string host("localhost"); int port= 9160; boost::shared_ptr<TTransport> socket(new TSocket(host, port)); boost::shared_ptr<TTransport> transport(new TFramedTransport(socket)); boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); CassandraClient *client= new CassandraClient(protocol); transport->open(); Cassandra c(client, host, port); const string version("19.4.0"); EXPECT_EQ(version, c.getServerVersion()); EXPECT_STREQ(version.c_str(), c.getServerVersion().c_str()); } TEST(Cassandra, GetClusterName) { const string host("localhost"); int port= 9160; boost::shared_ptr<TTransport> socket(new TSocket(host, port)); boost::shared_ptr<TTransport> transport(new TFramedTransport(socket)); boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); CassandraClient *client= new CassandraClient(protocol); transport->open(); Cassandra c(client, host, port); const string name("Test Cluster"); EXPECT_EQ(name, c.getClusterName()); EXPECT_STREQ(name.c_str(), c.getClusterName().c_str()); } TEST(Cassandra, GetKeyspaces) { const string host("localhost"); int port= 9160; boost::shared_ptr<TTransport> socket(new TSocket(host, port)); boost::shared_ptr<TTransport> transport(new TFramedTransport(socket)); boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); CassandraClient *client= new CassandraClient(protocol); transport->open(); Cassandra c(client, host, port); vector<KeyspaceDefinition> keyspaces= c.getKeyspaces(); /* we assume the test server only has 1 keyspace: system */ EXPECT_EQ(1, keyspaces.size()); } TEST_F(ClientTest, InsertColumn) { const string mock_data("this is mock data being inserted..."); KeyspaceDefinition ks_def; ks_def.setName("unittest"); c->createKeyspace(ks_def); ColumnFamilyDefinition cf_def; cf_def.setName("padraig"); cf_def.setKeyspaceName(ks_def.getName()); c->setKeyspace(ks_def.getName()); c->createColumnFamily(cf_def); c->insertColumn("sarah", "padraig", "third", mock_data); string res= c->getColumnValue("sarah", "padraig", "third"); EXPECT_EQ(mock_data, res); EXPECT_STREQ(mock_data.c_str(), res.c_str()); c->dropColumnFamily("padraig"); c->dropKeyspace("unittest"); } TEST_F(ClientTest, DeleteColumn) { KeyspaceDefinition ks_def; ks_def.setName("unittest"); c->createKeyspace(ks_def); ColumnFamilyDefinition cf_def; cf_def.setName("padraig"); cf_def.setKeyspaceName(ks_def.getName()); c->setKeyspace(ks_def.getName()); c->createColumnFamily(cf_def); c->removeColumn("sarah", "padraig", "", "third"); ASSERT_THROW(c->getColumnValue("sarah", "padraig", "third"), org::apache::cassandra::NotFoundException); c->dropColumnFamily("padraig"); c->dropKeyspace("unittest"); } TEST_F(ClientTest, DeleteEntireRow) { const string mock_data("this is mock data being inserted..."); KeyspaceDefinition ks_def; ks_def.setName("unittest"); c->createKeyspace(ks_def); ColumnFamilyDefinition cf_def; cf_def.setName("padraig"); cf_def.setKeyspaceName(ks_def.getName()); c->setKeyspace(ks_def.getName()); c->createColumnFamily(cf_def); c->insertColumn("sarah", "padraig", "third", mock_data); string res= c->getColumnValue("sarah", "padraig", "third"); EXPECT_EQ(mock_data, res); EXPECT_STREQ(mock_data.c_str(), res.c_str()); c->remove("sarah", "padraig", "", ""); ASSERT_THROW(c->getColumnValue("sarah", "padraig", "third"), org::apache::cassandra::NotFoundException); c->dropColumnFamily("padraig"); c->dropKeyspace("unittest"); } TEST_F(ClientTest, InsertSuperColumn) { const string mock_data("this is mock data being inserted..."); KeyspaceDefinition ks_def; ks_def.setName("unittest"); c->createKeyspace(ks_def); ColumnFamilyDefinition cf_def; cf_def.setName("Super1"); cf_def.setColumnType("Super"); cf_def.setKeyspaceName(ks_def.getName()); c->setKeyspace(ks_def.getName()); c->createColumnFamily(cf_def); c->insertColumn("teeny", "Super1", "padraig", "third", mock_data); string res= c->getColumnValue("teeny", "Super1", "padraig", "third"); EXPECT_EQ(mock_data, res); EXPECT_STREQ(mock_data.c_str(), res.c_str()); c->dropColumnFamily("Super1"); c->dropKeyspace("unittest"); } TEST_F(ClientTest, DeleteSuperColumn) { KeyspaceDefinition ks_def; ks_def.setName("unittest"); c->createKeyspace(ks_def); ColumnFamilyDefinition cf_def; cf_def.setName("Super1"); cf_def.setColumnType("Super"); cf_def.setKeyspaceName(ks_def.getName()); c->setKeyspace(ks_def.getName()); c->createColumnFamily(cf_def); c->removeSuperColumn("teeny", "Super1", "padraig"); ASSERT_THROW(c->getColumnValue("teeny", "Super1", "padraig", "third"), org::apache::cassandra::NotFoundException); c->dropColumnFamily("Super1"); c->dropKeyspace("unittest"); } <commit_msg>Added unit test for queries on secondary indexes.<commit_after>/* * LibCassandra * Copyright (C) 2010 Padraig O'Sullivan * All rights reserved. * * Use and distribution licensed under the BSD license. See * the COPYING file in the parent directory for full text. */ #include <string> #include <set> #include <iostream> #include <sstream> #include <protocol/TBinaryProtocol.h> #include <transport/TSocket.h> #include <transport/TTransportUtils.h> #include <gtest/gtest.h> #include <libgenthrift/Cassandra.h> #include <libcassandra/cassandra.h> #include <libcassandra/cassandra_factory.h> #include <libcassandra/column_family_definition.h> #include <libcassandra/indexed_slices_query.h> #include <libcassandra/keyspace.h> #include <libcassandra/keyspace_definition.h> using namespace std; using namespace libcassandra; using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace org::apache::cassandra; using namespace boost; class ClientTest : public testing::Test { protected: virtual void SetUp() { const string host("localhost"); int port= 9160; cf= tr1::shared_ptr<CassandraFactory>(new CassandraFactory(host, port)); c= tr1::shared_ptr<Cassandra>(cf->create()); } tr1::shared_ptr<CassandraFactory> cf; tr1::shared_ptr<Cassandra> c; }; TEST(Cassandra, DefaultConstructor) { const Cassandra c; EXPECT_EQ(0, c.getPort()); } TEST(Cassandra, ConsructorFromHostAndPort) { const string host("localhost"); int port= 9160; boost::shared_ptr<TTransport> socket(new TSocket(host, port)); boost::shared_ptr<TTransport> transport(new TFramedTransport(socket)); boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); CassandraClient *client= new CassandraClient(protocol); transport->open(); Cassandra c(client, host, port); EXPECT_EQ(client, c.getCassandra()); EXPECT_EQ(host, c.getHost()); EXPECT_EQ(port, c.getPort()); EXPECT_STREQ("localhost", c.getHost().c_str()); } TEST(Cassandra, GetServerVersion) { const string host("localhost"); int port= 9160; boost::shared_ptr<TTransport> socket(new TSocket(host, port)); boost::shared_ptr<TTransport> transport(new TFramedTransport(socket)); boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); CassandraClient *client= new CassandraClient(protocol); transport->open(); Cassandra c(client, host, port); const string version("19.4.0"); EXPECT_EQ(version, c.getServerVersion()); EXPECT_STREQ(version.c_str(), c.getServerVersion().c_str()); } TEST(Cassandra, GetClusterName) { const string host("localhost"); int port= 9160; boost::shared_ptr<TTransport> socket(new TSocket(host, port)); boost::shared_ptr<TTransport> transport(new TFramedTransport(socket)); boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); CassandraClient *client= new CassandraClient(protocol); transport->open(); Cassandra c(client, host, port); const string name("Test Cluster"); EXPECT_EQ(name, c.getClusterName()); EXPECT_STREQ(name.c_str(), c.getClusterName().c_str()); } TEST(Cassandra, GetKeyspaces) { const string host("localhost"); int port= 9160; boost::shared_ptr<TTransport> socket(new TSocket(host, port)); boost::shared_ptr<TTransport> transport(new TFramedTransport(socket)); boost::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport)); CassandraClient *client= new CassandraClient(protocol); transport->open(); Cassandra c(client, host, port); vector<KeyspaceDefinition> keyspaces= c.getKeyspaces(); /* we assume the test server only has 1 keyspace: system */ EXPECT_EQ(1, keyspaces.size()); } TEST_F(ClientTest, InsertColumn) { const string mock_data("this is mock data being inserted..."); KeyspaceDefinition ks_def; ks_def.setName("unittest"); c->createKeyspace(ks_def); ColumnFamilyDefinition cf_def; cf_def.setName("padraig"); cf_def.setKeyspaceName(ks_def.getName()); c->setKeyspace(ks_def.getName()); c->createColumnFamily(cf_def); c->insertColumn("sarah", "padraig", "third", mock_data); string res= c->getColumnValue("sarah", "padraig", "third"); EXPECT_EQ(mock_data, res); EXPECT_STREQ(mock_data.c_str(), res.c_str()); c->dropColumnFamily("padraig"); c->dropKeyspace("unittest"); } TEST_F(ClientTest, DeleteColumn) { KeyspaceDefinition ks_def; ks_def.setName("unittest"); c->createKeyspace(ks_def); ColumnFamilyDefinition cf_def; cf_def.setName("padraig"); cf_def.setKeyspaceName(ks_def.getName()); c->setKeyspace(ks_def.getName()); c->createColumnFamily(cf_def); c->removeColumn("sarah", "padraig", "", "third"); ASSERT_THROW(c->getColumnValue("sarah", "padraig", "third"), org::apache::cassandra::NotFoundException); c->dropColumnFamily("padraig"); c->dropKeyspace("unittest"); } TEST_F(ClientTest, DeleteEntireRow) { const string mock_data("this is mock data being inserted..."); KeyspaceDefinition ks_def; ks_def.setName("unittest"); c->createKeyspace(ks_def); ColumnFamilyDefinition cf_def; cf_def.setName("padraig"); cf_def.setKeyspaceName(ks_def.getName()); c->setKeyspace(ks_def.getName()); c->createColumnFamily(cf_def); c->insertColumn("sarah", "padraig", "third", mock_data); string res= c->getColumnValue("sarah", "padraig", "third"); EXPECT_EQ(mock_data, res); EXPECT_STREQ(mock_data.c_str(), res.c_str()); c->remove("sarah", "padraig", "", ""); ASSERT_THROW(c->getColumnValue("sarah", "padraig", "third"), org::apache::cassandra::NotFoundException); c->dropColumnFamily("padraig"); c->dropKeyspace("unittest"); } TEST_F(ClientTest, InsertSuperColumn) { const string mock_data("this is mock data being inserted..."); KeyspaceDefinition ks_def; ks_def.setName("unittest"); c->createKeyspace(ks_def); ColumnFamilyDefinition cf_def; cf_def.setName("Super1"); cf_def.setColumnType("Super"); cf_def.setKeyspaceName(ks_def.getName()); c->setKeyspace(ks_def.getName()); c->createColumnFamily(cf_def); c->insertColumn("teeny", "Super1", "padraig", "third", mock_data); string res= c->getColumnValue("teeny", "Super1", "padraig", "third"); EXPECT_EQ(mock_data, res); EXPECT_STREQ(mock_data.c_str(), res.c_str()); c->dropColumnFamily("Super1"); c->dropKeyspace("unittest"); } TEST_F(ClientTest, DeleteSuperColumn) { KeyspaceDefinition ks_def; ks_def.setName("unittest"); c->createKeyspace(ks_def); ColumnFamilyDefinition cf_def; cf_def.setName("Super1"); cf_def.setColumnType("Super"); cf_def.setKeyspaceName(ks_def.getName()); c->setKeyspace(ks_def.getName()); c->createColumnFamily(cf_def); c->removeSuperColumn("teeny", "Super1", "padraig"); ASSERT_THROW(c->getColumnValue("teeny", "Super1", "padraig", "third"), org::apache::cassandra::NotFoundException); c->dropColumnFamily("Super1"); c->dropKeyspace("unittest"); } /** * This unit test uses the blog post from data stax as its basis * http://www.datastax.com/dev/blog/whats-new-cassandra-07-secondary-indexes */ TEST_F(ClientTest, SecondaryIndexes) { KeyspaceDefinition ks_def; ks_def.setName("unittest"); c->createKeyspace(ks_def); ColumnFamilyDefinition cf_def; cf_def.setName("users"); cf_def.setKeyspaceName(ks_def.getName()); ColumnDefinition name_col; name_col.setName("full_name"); name_col.setValidationClass("UTF8Type"); ColumnDefinition sec_col; sec_col.setName("birth_date"); sec_col.setValidationClass("LongType"); sec_col.setIndexType(IndexType::KEYS); ColumnDefinition third_col; third_col.setName("state"); third_col.setValidationClass("UTF8Type"); third_col.setIndexType(IndexType::KEYS); cf_def.addColumnMetadata(name_col); cf_def.addColumnMetadata(sec_col); cf_def.addColumnMetadata(third_col); c->setKeyspace(ks_def.getName()); c->createColumnFamily(cf_def); c->insertColumn("bsanderson", cf_def.getName(), "full_name", "Brandon Sanderson"); c->insertColumn("bsanderson", cf_def.getName(), "birth_date", "00001975"); c->insertColumn("bsanderson", cf_def.getName(), "state", "UT"); c->insertColumn("prothfuss", cf_def.getName(), "full_name", "Patrick Rothfuss"); c->insertColumn("prothfuss", cf_def.getName(), "birth_date", "00001973"); c->insertColumn("prothfuss", cf_def.getName(), "state", "WI"); c->insertColumn("htayler", cf_def.getName(), "full_name", "Howard Tayler"); c->insertColumn("htayler", cf_def.getName(), "birth_date", "00001968"); c->insertColumn("htayler", cf_def.getName(), "state", "UT"); IndexedSlicesQuery query; vector<string> column_names; column_names.push_back("full_name"); column_names.push_back("birth_data"); column_names.push_back("state"); query.setColumns(column_names); query.addGtExpression("birth_date", "00001970"); query.addEqualsExpression("state", "UT"); query.setColumnFamily("users"); map<string, map<string, string> > res= c->getIndexedSlices(query); EXPECT_EQ(1, res.size()); for (map<string, map<string, string> >::iterator it= res.begin(); it != res.end(); ++it) { EXPECT_EQ("bsanderson", it->first); } c->dropColumnFamily("users"); c->dropKeyspace("unittest"); } <|endoftext|>
<commit_before> extern "C" { #include "cx/syscx.h" } #include "cx/fileb.hh" #include "cx/tuple.hh" #include "prot-ofile.hh" #include "prot-xfile.hh" #include "xnsys.hh" #include <vector> using Cx::Tuple; using Cx::mk_Tuple; using std::vector; typedef uint PcState; uint ReadUniRing(const char* filepath, Xn::Sys& sys, vector< Tuple<PcState,2> >& legits); bool WriteUniRing(const char* filepath, const Xn::Sys& sys, const vector< Tuple<PcState,3> >& actions); /** Execute me now!**/ int main(int argc, char** argv) { int argi = init_sysCx(&argc, &argv); if (argi + 1 > argc) failout_sysCx("Need at least one argument (an input file)."); const char* in_filepath = argv[argi++]; Xn::Sys sys; /// For I/O only. vector< Tuple<PcState,2> > legits; uint domsz = ReadUniRing(in_filepath, sys, legits); if (domsz == 0) failout_sysCx(in_filepath); vector< Tuple<PcState,3> > actions; // ... build this up ... // Here's a hard-coded protocol for Sum-Not-Two: actions.push_back(mk_Tuple<PcState>(0,2,1)); actions.push_back(mk_Tuple<PcState>(1,1,2)); actions.push_back(mk_Tuple<PcState>(2,0,1)); const char* out_filepath = argv[argi]; if (out_filepath) { ++ argi; WriteUniRing(out_filepath, sys, actions); } lose_sysCx(); return 0; } /** Read a unidirectional ring specification.**/ uint ReadUniRing(const char* filepath, Xn::Sys& sys, vector< Tuple<PcState,2> >& legits) { legits.clear(); sys.topology.lightweight = true; ProtoconFileOpt infile_opt; infile_opt.text.moveq(textfile_AlphaTab (0, filepath)); if (!ReadProtoconFile(sys, infile_opt)) BailOut(0, "Cannot read file!"); const Xn::Net& topo = sys.topology; // Do some ad-hoc checking that this is a unidirectional ring. if (sys.direct_pfmla.sat_ck()) BailOut(0, "Should not have actions."); if (topo.pc_symms.sz() != 1) { DBog_ujint(topo.pc_symms.sz()); BailOut(0, "Should have only one kind of process."); } if (topo.pcs.sz() < 2) BailOut(0, "Should have more than 1 process."); // Ensure the invariant is given inside the process definition. { P::Fmla invariant(true); for (uint i = 0; i < topo.pcs.sz(); ++i) { invariant &= topo.pcs[i].invariant; } if (!invariant.equiv_ck(sys.invariant)) BailOut(0, "Please specify invariant in process definition."); } // Just look at process P[0]. const Xn::PcSymm& pc_symm = topo.pc_symms[0]; const Xn::Pc& pc = *pc_symm.membs[0]; if (pc.wvbls.sz() != 1) BailOut(0, "Should write 1 variable."); if (pc.rvbls.sz() != 2) BailOut(0, "Should read-only 1 variable."); // Get references to this process's variables that can be // used in the context of the predicate formulas. Cx::Table<uint> rvbl_indices(2); rvbl_indices[0] = pc.rvbls[0]->pfmla_idx; rvbl_indices[1] = pc.rvbls[1]->pfmla_idx; if (pc_symm.wmap[0]==0) SwapT(uint, rvbl_indices[0], rvbl_indices[1]); // Get all legitimate states. P::Fmla legit_pf = pc.invariant; while (legit_pf.sat_ck()) { Cx::Table<uint> state(2); // Find a readable state of this process that fits the legitimate states. legit_pf.state(&state[0], rvbl_indices); // Remove the corresponding predicate formula from {legit_pf}. legit_pf -= topo.pfmla_ctx.pfmla_of_state(&state[0], rvbl_indices); legits.push_back(mk_Tuple<PcState>(state[0], state[1])); } return topo.vbl_symms[0].domsz; } /** Write a unidirectional ring protocol file.**/ bool WriteUniRing(const char* filepath, const Xn::Sys& sys, const vector< Tuple<PcState,3> >& actions) { const Xn::Net& topo = sys.topology; const Xn::PcSymm& pc_symm = topo.pc_symms[0]; vector<uint> enum_actions; for (uint i = 0; i < actions.size(); ++i) { Xn::ActSymm act; act.pc_symm = &pc_symm; act.vals << actions[i][0] << actions[i][1] << actions[i][2]; if (pc_symm.wmap[0]==0) SwapT(uint, act.vals[0], act.vals[1]); enum_actions.push_back(topo.action_index(act)); } return oput_protocon_file (filepath, sys, topo, enum_actions, false, 0); } <commit_msg>Add debugging statements to unisyn<commit_after> extern "C" { #include "cx/syscx.h" } #include "cx/fileb.hh" #include "cx/tuple.hh" #include "prot-ofile.hh" #include "prot-xfile.hh" #include "xnsys.hh" #include <vector> using Cx::Tuple; using Cx::mk_Tuple; using std::vector; typedef uint PcState; uint ReadUniRing(const char* filepath, Xn::Sys& sys, vector< Tuple<PcState,2> >& legits); bool WriteUniRing(const char* filepath, const Xn::Sys& sys, const vector< Tuple<PcState,3> >& actions); /** Execute me now!**/ int main(int argc, char** argv) { int argi = init_sysCx(&argc, &argv); if (argi + 1 > argc) failout_sysCx("Need at least one argument (an input file)."); const char* in_filepath = argv[argi++]; Xn::Sys sys; /// For I/O only. vector< Tuple<PcState,2> > legits; uint domsz = ReadUniRing(in_filepath, sys, legits); if (domsz == 0) failout_sysCx(in_filepath); // (Debugging) Output all the legitimate readable states. printf("Legitimate states for P[i]:\n"); for (uint i = 0; i < legits.size(); ++i) { printf("x[i-1]==%u && x[i]==%u\n", legits[i][0], legits[i][1]); } vector< Tuple<PcState,3> > actions; // ... build this up ... // Here's a hard-coded protocol for Sum-Not-Two: actions.push_back(mk_Tuple<PcState>(0,2,1)); actions.push_back(mk_Tuple<PcState>(1,1,2)); actions.push_back(mk_Tuple<PcState>(2,0,1)); // (Debugging) Output all the synthesized acctions. printf("Synthesized actions for P[i]:\n"); for (uint i = 0; i < actions.size(); ++i) { printf("x[i-1]==%u && x[i]==%u --> x[i]:=%u\n", actions[i][0], actions[i][1], actions[i][2]); } const char* out_filepath = argv[argi]; if (out_filepath) { ++ argi; WriteUniRing(out_filepath, sys, actions); } lose_sysCx(); return 0; } /** Read a unidirectional ring specification.**/ uint ReadUniRing(const char* filepath, Xn::Sys& sys, vector< Tuple<PcState,2> >& legits) { legits.clear(); sys.topology.lightweight = true; ProtoconFileOpt infile_opt; infile_opt.text.moveq(textfile_AlphaTab (0, filepath)); if (!ReadProtoconFile(sys, infile_opt)) BailOut(0, "Cannot read file!"); const Xn::Net& topo = sys.topology; // Do some ad-hoc checking that this is a unidirectional ring. if (sys.direct_pfmla.sat_ck()) BailOut(0, "Should not have actions."); if (topo.pc_symms.sz() != 1) { DBog_ujint(topo.pc_symms.sz()); BailOut(0, "Should have only one kind of process."); } if (topo.pcs.sz() < 2) BailOut(0, "Should have more than 1 process."); // Ensure the invariant is given inside the process definition. { P::Fmla invariant(true); for (uint i = 0; i < topo.pcs.sz(); ++i) { invariant &= topo.pcs[i].invariant; } if (!invariant.equiv_ck(sys.invariant)) BailOut(0, "Please specify invariant in process definition."); } // Just look at process P[0]. const Xn::PcSymm& pc_symm = topo.pc_symms[0]; const Xn::Pc& pc = *pc_symm.membs[0]; if (pc.wvbls.sz() != 1) BailOut(0, "Should write 1 variable."); if (pc.rvbls.sz() != 2) BailOut(0, "Should read-only 1 variable."); // Get references to this process's variables that can be // used in the context of the predicate formulas. Cx::Table<uint> rvbl_indices(2); rvbl_indices[0] = pc.rvbls[0]->pfmla_idx; rvbl_indices[1] = pc.rvbls[1]->pfmla_idx; if (pc_symm.wmap[0]==0) SwapT(uint, rvbl_indices[0], rvbl_indices[1]); // Get all legitimate states. P::Fmla legit_pf = pc.invariant; while (legit_pf.sat_ck()) { Cx::Table<uint> state(2); // Find a readable state of this process that fits the legitimate states. legit_pf.state(&state[0], rvbl_indices); // Remove the corresponding predicate formula from {legit_pf}. legit_pf -= topo.pfmla_ctx.pfmla_of_state(&state[0], rvbl_indices); legits.push_back(mk_Tuple<PcState>(state[0], state[1])); } return topo.vbl_symms[0].domsz; } /** Write a unidirectional ring protocol file.**/ bool WriteUniRing(const char* filepath, const Xn::Sys& sys, const vector< Tuple<PcState,3> >& actions) { const Xn::Net& topo = sys.topology; const Xn::PcSymm& pc_symm = topo.pc_symms[0]; vector<uint> enum_actions; for (uint i = 0; i < actions.size(); ++i) { Xn::ActSymm act; act.pc_symm = &pc_symm; act.vals << actions[i][0] << actions[i][1] << actions[i][2]; if (pc_symm.wmap[0]==0) SwapT(uint, act.vals[0], act.vals[1]); enum_actions.push_back(topo.action_index(act)); } return oput_protocon_file (filepath, sys, topo, enum_actions, false, 0); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "Render/Geometry/ParserGLTF.h" #include "AssetsSystem/AssetsSystem.h" #include "Core/Logger/Logger.h" #include "Render/Geometry/IntermediateMesh.h" #define TINYGLTF_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #define TINYGLTF_NOEXCEPTION #define JSON_NOEXCEPTION #include "Sources/External/TinyGLTF/tiny_gltf.h" namespace Kioto { void ParserGLTF::Init() { } void ParserGLTF::Shutdown() { } Renderer::Mesh* ParserGLTF::ParseMesh(const std::string& path) { return nullptr; } void ParserGLTF::ParseMesh(Renderer::Mesh* dst) { tinygltf::Model model; bool res = LoadModel(dst->GetAssetPath(), model); const tinygltf::Scene& scene = model.scenes[model.defaultScene]; for (int node : scene.nodes) { ParseModelNodes(model, model.nodes[node], dst); } } bool ParserGLTF::LoadModel(const std::string& path, tinygltf::Model& model) { tinygltf::TinyGLTF loader; std::string err; std::string warn; bool res = false; std::string ext = AssetsSystem::GetFileExtension(path); if (ext == ".glb") res = loader.LoadBinaryFromFile(&model, &err, &warn, path.c_str()); else if (ext == ".gltf") res = loader.LoadASCIIFromFile(&model, &err, &warn, path.c_str()); else assert(false); if (!warn.empty()) LOG("WARN: ", warn); if (!err.empty()) LOG("ERR: ", err); if (!res) LOG("Failed to load glTF: ", path); else LOG("Loaded glTF: ", path); return res; } void ParserGLTF::ParseModelNodes(const tinygltf::Model& model, const tinygltf::Node& node, Renderer::Mesh* dst) { ParseGLTFMesh(model, model.meshes[node.mesh], dst); for (int i : node.children) // [a_vorontsov] Not really supported at the moment... ParseModelNodes(model, model.nodes[i], dst); } void ParserGLTF::ParseGLTFMesh(const tinygltf::Model& model, const tinygltf::Mesh& mesh, Renderer::Mesh* dst) { Renderer::IntermediateMesh resMesh; for (size_t i = 0; i < mesh.primitives.size(); ++i) { tinygltf::Primitive primitive = mesh.primitives[i]; tinygltf::Accessor indexAccessor = model.accessors[primitive.indices]; for (auto& attrib : primitive.attributes) { tinygltf::Accessor accessor = model.accessors[attrib.second]; const tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView]; const tinygltf::Buffer& buffer = model.buffers[bufferView.buffer]; const byte* bufferData = &model.buffers[bufferView.buffer].data.at(0); size_t byteOffset = bufferView.byteOffset; size_t byteLength = bufferView.byteLength; uint32 byteStride = accessor.ByteStride(bufferView); size_t elemNumber = byteLength / byteStride; if (resMesh.Vertices.size() == 0) resMesh.Vertices.resize(elemNumber); uint32 size = 1; if (accessor.type != TINYGLTF_TYPE_SCALAR) size = accessor.type; uint32 elementByteSize = size * 4; std::vector<Vector3> positions; if (attrib.first.compare("POSITION") == 0) { resMesh.LayoutMask |= Renderer::IntermediateMesh::Position; const byte* bufferStart = bufferData + byteOffset; for (size_t i = 0; i < elemNumber; ++i) { float32 x = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 0)); float32 y = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 4)); float32 z = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 8)); resMesh.Vertices[i].Pos = { x, y, z, 0.0f }; } } else if (attrib.first.compare("NORMAL") == 0) { resMesh.LayoutMask |= Renderer::IntermediateMesh::Normal; const byte* bufferStart = bufferData + byteOffset; for (size_t i = 0; i < elemNumber; ++i) { float32 x = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 0)); float32 y = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 4)); float32 z = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 8)); resMesh.Vertices[i].Norm = { x, y, z, 0.0f }; } } else if (attrib.first.compare("TEXCOORD_0") == 0) { resMesh.LayoutMask |= Renderer::IntermediateMesh::UV0; const byte* bufferStart = bufferData + byteOffset; for (size_t i = 0; i < elemNumber; ++i) { float32 u = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 0)); float32 v = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 4)); resMesh.Vertices[i].Uv.push_back({ u, v }); } } else assert(false); } } resMesh.Indexate(); dst->FromIntermediateMesh(resMesh); // [a_vorontcov] You can also find image part of the parsing here https://github.com/syoyo/tinygltf/blob/master/examples/basic/main.cpp } }<commit_msg>And parse indices<commit_after>#include "stdafx.h" #include "Render/Geometry/ParserGLTF.h" #include "AssetsSystem/AssetsSystem.h" #include "Core/Logger/Logger.h" #include "Render/Geometry/IntermediateMesh.h" #define TINYGLTF_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #define TINYGLTF_NOEXCEPTION #define JSON_NOEXCEPTION #include "Sources/External/TinyGLTF/tiny_gltf.h" namespace Kioto { void ParserGLTF::Init() { } void ParserGLTF::Shutdown() { } Renderer::Mesh* ParserGLTF::ParseMesh(const std::string& path) { return nullptr; } void ParserGLTF::ParseMesh(Renderer::Mesh* dst) { tinygltf::Model model; bool res = LoadModel(dst->GetAssetPath(), model); const tinygltf::Scene& scene = model.scenes[model.defaultScene]; for (int node : scene.nodes) { ParseModelNodes(model, model.nodes[node], dst); } } bool ParserGLTF::LoadModel(const std::string& path, tinygltf::Model& model) { tinygltf::TinyGLTF loader; std::string err; std::string warn; bool res = false; std::string ext = AssetsSystem::GetFileExtension(path); if (ext == ".glb") res = loader.LoadBinaryFromFile(&model, &err, &warn, path.c_str()); else if (ext == ".gltf") res = loader.LoadASCIIFromFile(&model, &err, &warn, path.c_str()); else assert(false); if (!warn.empty()) LOG("WARN: ", warn); if (!err.empty()) LOG("ERR: ", err); if (!res) LOG("Failed to load glTF: ", path); else LOG("Loaded glTF: ", path); return res; } void ParserGLTF::ParseModelNodes(const tinygltf::Model& model, const tinygltf::Node& node, Renderer::Mesh* dst) { ParseGLTFMesh(model, model.meshes[node.mesh], dst); for (int i : node.children) // [a_vorontsov] Not really supported at the moment... ParseModelNodes(model, model.nodes[i], dst); } void ParserGLTF::ParseGLTFMesh(const tinygltf::Model& model, const tinygltf::Mesh& mesh, Renderer::Mesh* dst) { Renderer::IntermediateMesh resMesh; for (size_t i = 0; i < mesh.primitives.size(); ++i) { tinygltf::Primitive primitive = mesh.primitives[i]; for (auto& attrib : primitive.attributes) { tinygltf::Accessor accessor = model.accessors[attrib.second]; const tinygltf::BufferView& bufferView = model.bufferViews[accessor.bufferView]; const tinygltf::Buffer& buffer = model.buffers[bufferView.buffer]; const byte* bufferData = &model.buffers[bufferView.buffer].data.at(0); size_t byteOffset = bufferView.byteOffset; size_t byteLength = bufferView.byteLength; uint32 byteStride = accessor.ByteStride(bufferView); size_t elemNumber = byteLength / byteStride; if (resMesh.Vertices.size() == 0) resMesh.Vertices.resize(elemNumber); assert(resMesh.Vertices.size() == elemNumber); uint32 size = 1; if (accessor.type != TINYGLTF_TYPE_SCALAR) size = accessor.type; uint32 elementByteSize = size * 4; std::vector<Vector3> positions; if (attrib.first.compare("POSITION") == 0) { resMesh.LayoutMask |= Renderer::IntermediateMesh::Position; const byte* bufferStart = bufferData + byteOffset; for (size_t i = 0; i < elemNumber; ++i) { float32 x = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 0)); float32 y = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 4)); float32 z = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 8)); resMesh.Vertices[i].Pos = { x, y, z, 0.0f }; } } else if (attrib.first.compare("NORMAL") == 0) { resMesh.LayoutMask |= Renderer::IntermediateMesh::Normal; const byte* bufferStart = bufferData + byteOffset; for (size_t i = 0; i < elemNumber; ++i) { float32 x = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 0)); float32 y = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 4)); float32 z = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 8)); resMesh.Vertices[i].Norm = { x, y, z, 0.0f }; } } else if (attrib.first.compare("TEXCOORD_0") == 0) { resMesh.LayoutMask |= Renderer::IntermediateMesh::UV0; const byte* bufferStart = bufferData + byteOffset; for (size_t i = 0; i < elemNumber; ++i) { float32 u = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 0)); float32 v = *(reinterpret_cast<const float32*>(bufferStart + size_t(byteStride) * size_t(i) + 4)); resMesh.Vertices[i].Uv.push_back({ u, v }); } } else assert(false); } tinygltf::Accessor indexAccessor = model.accessors[primitive.indices]; const tinygltf::BufferView& indexView = model.bufferViews[indexAccessor.bufferView]; const byte* indexBufferData = &model.buffers[indexView.buffer].data.at(0); size_t indexByteOffset = indexView.byteOffset; size_t indexByteLength = indexView.byteLength; uint32 indexByteStride = indexAccessor.ByteStride(indexView); if (indexByteStride == 2) { for (size_t i = 0; i < indexAccessor.count; ++i) { const byte* bufferStart = indexBufferData + indexByteOffset; int16 index = *(reinterpret_cast<const int16*>(bufferStart + size_t(indexByteStride) * size_t(i))); resMesh.Indices.push_back(index); } } else if (indexByteStride == 4) { for (size_t i = 0; i < indexAccessor.count; ++i) { const byte* bufferStart = indexBufferData + indexByteOffset; int32 index = *(reinterpret_cast<const int32*>(bufferStart + size_t(indexByteStride) * size_t(i))); resMesh.Indices.push_back(index); } } else assert(false); } dst->FromIntermediateMesh(resMesh); // [a_vorontcov] You can also find image part of the parsing here https://github.com/syoyo/tinygltf/blob/master/examples/basic/main.cpp } }<|endoftext|>
<commit_before>#include "utils.h" #include "jwtxx/jwt.h" // Key::Error #include <openssl/pem.h> #include <openssl/x509.h> #include <openssl/err.h> #include <algorithm> // std::min #include <exception> #include <cstring> // strerror #include <cstdio> // fopen, fclose #include <cerrno> // errno namespace Utils = JWTXX::Utils; namespace { struct PasswordCallbackTester { explicit PasswordCallbackTester(const JWTXX::Key::PasswordCallback& cb) noexcept : callback(cb) {} JWTXX::Key::PasswordCallback callback; std::exception_ptr exception; }; struct FileCloser { void operator()(FILE* fp) const noexcept { fclose(fp); } }; typedef std::unique_ptr<FILE, FileCloser> FilePtr; struct X509Deleter { void operator()(X509* cert) const noexcept { X509_free(cert); } }; typedef std::unique_ptr<X509, X509Deleter> X509Ptr; std::string sysError() noexcept { return strerror(errno); } Utils::EVPKeyPtr readPublicKey(const std::string& src) { // src is file name FilePtr fp(fopen(src.c_str(), "rb")); if (fp) return Utils::EVPKeyPtr(PEM_read_PUBKEY(fp.get(), nullptr, nullptr, nullptr)); // src is key data if (src.find("-----BEGIN") != 0) { throw JWTXX::Key::Error("Public key = " + src + " is not valid " + sysError()); } BIO* bio = BIO_new_mem_buf(src.data(), static_cast<int>(src.size())); Utils::EVPKeyPtr key(PEM_read_bio_PUBKEY(bio, nullptr, nullptr, nullptr)); BIO_free(bio); return key; } Utils::EVPKeyPtr readCert(const std::string& fileName) { FilePtr fp(fopen(fileName.c_str(), "rb")); if (!fp) throw JWTXX::Key::Error("Can't open key file '" + fileName + "'. " + sysError()); X509Ptr cert(PEM_read_X509(fp.get(), nullptr, nullptr, nullptr)); if (!cert) return {}; return Utils::EVPKeyPtr(X509_get_pubkey(cert.get())); } int passwordCallback(char* buf, int size, int /*rwflag*/, void* data) { if (data == nullptr) return 0; PasswordCallbackTester& tester = *static_cast<PasswordCallbackTester*>(data); try { auto password = tester.callback(); std::strncpy(buf, password.c_str(), size - 1); buf[size - 1] = '\0'; return std::min<int>(size, password.length()); } catch (...) { tester.exception = std::current_exception(); return 0; } } } Utils::EVPKeyPtr Utils::readPEMPrivateKey(const std::string& fileName, const JWTXX::Key::PasswordCallback& cb) { FilePtr fp(fopen(fileName.c_str(), "rb")); if (!fp) throw Key::Error("Can't open key file '" + fileName + "'. " + sysError()); try { PasswordCallbackTester tester(cb); EVPKeyPtr key(PEM_read_PrivateKey(fp.get(), nullptr, passwordCallback, &tester)); if (tester.exception) std::rethrow_exception(tester.exception); if (!key) throw Key::Error("Can't read private key '" + fileName + "'. " + OPENSSLError()); return key; } catch (const PasswordCallbackError&) { throw Key::Error("Can't read password-protected private key '" + fileName + "' without a password callback function."); } } Utils::EVPKeyPtr Utils::readPEMPublicKey(const std::string& fileName) { auto key = readPublicKey(fileName); std::string pkError; if (!key) { pkError = OPENSSLError(); key = readCert(fileName); } if (!key) throw Key::Error("File '" + fileName + "' is neither public key (" + pkError + ") nor certificate (" + OPENSSLError() + ")."); return key; } std::string Utils::OPENSSLError() noexcept { char buf[256]; ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); return buf; } Utils::Triple Utils::split(const std::string& token) { auto pos = token.find_first_of('.'); if (pos == std::string::npos) throw JWT::ParseError("JWT should have at least 2 parts separated by a dot."); auto spos = token.find_first_of('.', pos + 1); if (spos == std::string::npos) return std::make_tuple(token.substr(0, pos), token.substr(pos + 1, token.length() - pos - 1), ""); return std::make_tuple(token.substr(0, pos), token.substr(pos + 1, spos - pos - 1), token.substr(spos + 1, token.length() - spos - 1)); } <commit_msg>Remove extra check<commit_after>#include "utils.h" #include "jwtxx/jwt.h" // Key::Error #include <openssl/pem.h> #include <openssl/x509.h> #include <openssl/err.h> #include <algorithm> // std::min #include <exception> #include <cstring> // strerror #include <cstdio> // fopen, fclose #include <cerrno> // errno namespace Utils = JWTXX::Utils; namespace { struct PasswordCallbackTester { explicit PasswordCallbackTester(const JWTXX::Key::PasswordCallback& cb) noexcept : callback(cb) {} JWTXX::Key::PasswordCallback callback; std::exception_ptr exception; }; struct FileCloser { void operator()(FILE* fp) const noexcept { fclose(fp); } }; typedef std::unique_ptr<FILE, FileCloser> FilePtr; struct X509Deleter { void operator()(X509* cert) const noexcept { X509_free(cert); } }; typedef std::unique_ptr<X509, X509Deleter> X509Ptr; std::string sysError() noexcept { return strerror(errno); } Utils::EVPKeyPtr readPublicKey(const std::string& src) { // src is file name FilePtr fp(fopen(src.c_str(), "rb")); if (fp) return Utils::EVPKeyPtr(PEM_read_PUBKEY(fp.get(), nullptr, nullptr, nullptr)); // src is key data BIO* bio = BIO_new_mem_buf(src.data(), static_cast<int>(src.size())); Utils::EVPKeyPtr key(PEM_read_bio_PUBKEY(bio, nullptr, nullptr, nullptr)); BIO_free(bio); return key; } Utils::EVPKeyPtr readCert(const std::string& fileName) { FilePtr fp(fopen(fileName.c_str(), "rb")); if (!fp) throw JWTXX::Key::Error("Can't open key file '" + fileName + "'. " + sysError()); X509Ptr cert(PEM_read_X509(fp.get(), nullptr, nullptr, nullptr)); if (!cert) return {}; return Utils::EVPKeyPtr(X509_get_pubkey(cert.get())); } int passwordCallback(char* buf, int size, int /*rwflag*/, void* data) { if (data == nullptr) return 0; PasswordCallbackTester& tester = *static_cast<PasswordCallbackTester*>(data); try { auto password = tester.callback(); std::strncpy(buf, password.c_str(), size - 1); buf[size - 1] = '\0'; return std::min<int>(size, password.length()); } catch (...) { tester.exception = std::current_exception(); return 0; } } } Utils::EVPKeyPtr Utils::readPEMPrivateKey(const std::string& fileName, const JWTXX::Key::PasswordCallback& cb) { FilePtr fp(fopen(fileName.c_str(), "rb")); if (!fp) throw Key::Error("Can't open key file '" + fileName + "'. " + sysError()); try { PasswordCallbackTester tester(cb); EVPKeyPtr key(PEM_read_PrivateKey(fp.get(), nullptr, passwordCallback, &tester)); if (tester.exception) std::rethrow_exception(tester.exception); if (!key) throw Key::Error("Can't read private key '" + fileName + "'. " + OPENSSLError()); return key; } catch (const PasswordCallbackError&) { throw Key::Error("Can't read password-protected private key '" + fileName + "' without a password callback function."); } } Utils::EVPKeyPtr Utils::readPEMPublicKey(const std::string& fileName) { auto key = readPublicKey(fileName); std::string pkError; if (!key) { pkError = OPENSSLError(); key = readCert(fileName); } if (!key) throw Key::Error("File '" + fileName + "' is neither public key (" + pkError + ") nor certificate (" + OPENSSLError() + ")."); return key; } std::string Utils::OPENSSLError() noexcept { char buf[256]; ERR_error_string_n(ERR_get_error(), buf, sizeof(buf)); return buf; } Utils::Triple Utils::split(const std::string& token) { auto pos = token.find_first_of('.'); if (pos == std::string::npos) throw JWT::ParseError("JWT should have at least 2 parts separated by a dot."); auto spos = token.find_first_of('.', pos + 1); if (spos == std::string::npos) return std::make_tuple(token.substr(0, pos), token.substr(pos + 1, token.length() - pos - 1), ""); return std::make_tuple(token.substr(0, pos), token.substr(pos + 1, spos - pos - 1), token.substr(spos + 1, token.length() - spos - 1)); } <|endoftext|>
<commit_before>#include "utils.h" static QString gRclone; static QString gRcloneConf; static QString gRclonePassword; void ReadSettings(QSettings* settings, QObject* widget) { QString name = widget->objectName(); if (!name.isEmpty() && settings->contains(name)) { if (QRadioButton* obj = qobject_cast<QRadioButton*>(widget)) { obj->setChecked(settings->value(name).toBool()); return; } if (QCheckBox* obj = qobject_cast<QCheckBox*>(widget)) { obj->setChecked(settings->value(name).toBool()); return; } if (QComboBox* obj = qobject_cast<QComboBox*>(widget)) { obj->setCurrentIndex(settings->value(name).toInt()); return; } if (QSpinBox* obj = qobject_cast<QSpinBox*>(widget)) { obj->setValue(settings->value(name).toInt()); return; } if (QLineEdit* obj = qobject_cast<QLineEdit*>(widget)) { obj->setText(settings->value(name).toString()); return; } if (QPlainTextEdit* obj = qobject_cast<QPlainTextEdit*>(widget)) { int count = settings->beginReadArray(name); QStringList lines; lines.reserve(count); for (int i=0; i<count; i++) { settings->setArrayIndex(i); lines.append(settings->value("value").toString()); } settings->endArray(); obj->setPlainText(lines.join('\n')); return; } } for (auto child : widget->children()) { ReadSettings(settings, child); } } void WriteSettings(QSettings* settings, QObject* widget) { QString name = widget->objectName(); if (QCheckBox* obj = qobject_cast<QCheckBox*>(widget)) { settings->setValue(name, obj->isChecked()); return; } if (QComboBox* obj = qobject_cast<QComboBox*>(widget)) { settings->setValue(name, obj->currentIndex()); return; } if (QSpinBox* obj = qobject_cast<QSpinBox*>(widget)) { settings->setValue(name, obj->value()); return; } if (QLineEdit* obj = qobject_cast<QLineEdit*>(widget)) { if (!obj->text().isEmpty()) { settings->setValue(name, obj->text()); } return; } if (QPlainTextEdit* obj = qobject_cast<QPlainTextEdit*>(widget)) { QString text = obj->toPlainText().trimmed(); if (!text.isEmpty()) { QStringList lines = text.split('\n'); settings->beginWriteArray(name, lines.size()); for (int i=0; i<lines.count(); i++) { settings->setArrayIndex(i); settings->setValue("value", lines[i]); } settings->endArray(); } return; } for (auto child : widget->children()) { WriteSettings(settings, child); } } QStringList GetRcloneConf() { if (gRcloneConf.isEmpty()) { return QStringList(); } return QStringList() << "--config" << gRcloneConf; } void SetRcloneConf(const QString& rcloneConf) { gRcloneConf = rcloneConf; } QString GetRclone() { return gRclone; } void SetRclone(const QString& rclone) { gRclone = rclone.trimmed(); } void UseRclonePassword(QProcess* process) { if (!gRclonePassword.isEmpty()) { QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); env.insert("RCLONE_CONFIG_PASS", gRclonePassword); process->setProcessEnvironment(env); } } void SetRclonePassword(const QString& rclonePassword) { gRclonePassword = rclonePassword; } <commit_msg>remove empty text fields from settings<commit_after>#include "utils.h" static QString gRclone; static QString gRcloneConf; static QString gRclonePassword; void ReadSettings(QSettings* settings, QObject* widget) { QString name = widget->objectName(); if (!name.isEmpty() && settings->contains(name)) { if (QRadioButton* obj = qobject_cast<QRadioButton*>(widget)) { obj->setChecked(settings->value(name).toBool()); return; } if (QCheckBox* obj = qobject_cast<QCheckBox*>(widget)) { obj->setChecked(settings->value(name).toBool()); return; } if (QComboBox* obj = qobject_cast<QComboBox*>(widget)) { obj->setCurrentIndex(settings->value(name).toInt()); return; } if (QSpinBox* obj = qobject_cast<QSpinBox*>(widget)) { obj->setValue(settings->value(name).toInt()); return; } if (QLineEdit* obj = qobject_cast<QLineEdit*>(widget)) { obj->setText(settings->value(name).toString()); return; } if (QPlainTextEdit* obj = qobject_cast<QPlainTextEdit*>(widget)) { int count = settings->beginReadArray(name); QStringList lines; lines.reserve(count); for (int i=0; i<count; i++) { settings->setArrayIndex(i); lines.append(settings->value("value").toString()); } settings->endArray(); obj->setPlainText(lines.join('\n')); return; } } for (auto child : widget->children()) { ReadSettings(settings, child); } } void WriteSettings(QSettings* settings, QObject* widget) { QString name = widget->objectName(); if (QCheckBox* obj = qobject_cast<QCheckBox*>(widget)) { settings->setValue(name, obj->isChecked()); return; } if (QComboBox* obj = qobject_cast<QComboBox*>(widget)) { settings->setValue(name, obj->currentIndex()); return; } if (QSpinBox* obj = qobject_cast<QSpinBox*>(widget)) { settings->setValue(name, obj->value()); return; } if (QLineEdit* obj = qobject_cast<QLineEdit*>(widget)) { if (obj->text().isEmpty()) { settings->remove(name); } else { settings->setValue(name, obj->text()); } return; } if (QPlainTextEdit* obj = qobject_cast<QPlainTextEdit*>(widget)) { QString text = obj->toPlainText().trimmed(); if (!text.isEmpty()) { QStringList lines = text.split('\n'); settings->beginWriteArray(name, lines.size()); for (int i=0; i<lines.count(); i++) { settings->setArrayIndex(i); settings->setValue("value", lines[i]); } settings->endArray(); } return; } for (auto child : widget->children()) { WriteSettings(settings, child); } } QStringList GetRcloneConf() { if (gRcloneConf.isEmpty()) { return QStringList(); } return QStringList() << "--config" << gRcloneConf; } void SetRcloneConf(const QString& rcloneConf) { gRcloneConf = rcloneConf; } QString GetRclone() { return gRclone; } void SetRclone(const QString& rclone) { gRclone = rclone.trimmed(); } void UseRclonePassword(QProcess* process) { if (!gRclonePassword.isEmpty()) { QProcessEnvironment env = QProcessEnvironment::systemEnvironment(); env.insert("RCLONE_CONFIG_PASS", gRclonePassword); process->setProcessEnvironment(env); } } void SetRclonePassword(const QString& rclonePassword) { gRclonePassword = rclonePassword; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "keystore.h" #include "script.h" extern bool fWalletUnlockMintOnly; bool CKeyStore::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const { CKey key; if (!GetKey(address, key)) return false; vchPubKeyOut = key.GetPubKey(); return true; } bool CBasicKeyStore::AddKey(const CKey& key) { bool fCompressed = false; CSecret secret = key.GetSecret(fCompressed); { LOCK(cs_KeyStore); mapKeys[key.GetPubKey().GetID()] = make_pair(secret, fCompressed); } return true; } bool CBasicKeyStore::AddCScript(const CScript& redeemScript) { { LOCK(cs_KeyStore); mapScripts[redeemScript.GetID()] = redeemScript; } return true; } bool CBasicKeyStore::HaveCScript(const CScriptID& hash) const { bool result; { LOCK(cs_KeyStore); result = (mapScripts.count(hash) > 0); } return result; } bool CBasicKeyStore::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const { { LOCK(cs_KeyStore); ScriptMap::const_iterator mi = mapScripts.find(hash); if (mi != mapScripts.end()) { redeemScriptOut = (*mi).second; return true; } } return false; } bool CBasicKeyStore::AddWatchOnly(const CTxDestination &dest) { LOCK(cs_KeyStore); setWatchOnly.insert(dest); return true; } bool CBasicKeyStore::HaveWatchOnly(const CTxDestination &dest) const { LOCK(cs_KeyStore); return setWatchOnly.count(dest) > 0; } bool CCryptoKeyStore::SetCrypted() { { LOCK(cs_KeyStore); if (fUseCrypto) return true; if (!mapKeys.empty()) return false; fUseCrypto = true; } return true; } bool CCryptoKeyStore::Lock() { if (!SetCrypted()) return false; { LOCK(cs_KeyStore); vMasterKey.clear(); fWalletUnlockMintOnly = false; } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin(); for (; mi != mapCryptedKeys.end(); ++mi) { const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; CSecret vchSecret; if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) return false; if (vchSecret.size() != 32) return false; CKey key; key.SetPubKey(vchPubKey); key.SetSecret(vchSecret); if (key.GetPubKey() == vchPubKey) break; return false; } vMasterKey = vMasterKeyIn; } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::AddKey(const CKey& key) { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::AddKey(key); if (IsLocked()) return false; std::vector<unsigned char> vchCryptedSecret; CPubKey vchPubKey = key.GetPubKey(); bool fCompressed; if (!EncryptSecret(vMasterKey, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret)) return false; } return true; } bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret); } return true; } bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::GetKey(address, keyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; CSecret vchSecret; if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) return false; if (vchSecret.size() != 32) return false; keyOut.SetPubKey(vchPubKey); keyOut.SetSecret(vchSecret); return true; } } return false; } bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CKeyStore::GetPubKey(address, vchPubKeyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { vchPubKeyOut = (*mi).second.first; return true; } } return false; } bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!mapCryptedKeys.empty() || IsCrypted()) return false; fUseCrypto = true; BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys) { CKey key; if (!key.SetSecret(mKey.second.first, mKey.second.second)) return false; const CPubKey vchPubKey = key.GetPubKey(); std::vector<unsigned char> vchCryptedSecret; bool fCompressed; if (!EncryptSecret(vMasterKeyIn, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; } mapKeys.clear(); } return true; } <commit_msg>Prevent import keys for watch-only addresses and vice versa.<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "keystore.h" #include "script.h" #include "base58.h" extern bool fWalletUnlockMintOnly; bool CKeyStore::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const { CKey key; if (!GetKey(address, key)) return false; vchPubKeyOut = key.GetPubKey(); return true; } bool CBasicKeyStore::AddKey(const CKey& key) { bool fCompressed = false; CSecret secret = key.GetSecret(fCompressed); { LOCK(cs_KeyStore); mapKeys[key.GetPubKey().GetID()] = make_pair(secret, fCompressed); } return true; } bool CBasicKeyStore::AddCScript(const CScript& redeemScript) { { LOCK(cs_KeyStore); mapScripts[redeemScript.GetID()] = redeemScript; } return true; } bool CBasicKeyStore::HaveCScript(const CScriptID& hash) const { bool result; { LOCK(cs_KeyStore); result = (mapScripts.count(hash) > 0); } return result; } bool CBasicKeyStore::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) const { { LOCK(cs_KeyStore); ScriptMap::const_iterator mi = mapScripts.find(hash); if (mi != mapScripts.end()) { redeemScriptOut = (*mi).second; return true; } } return false; } bool CBasicKeyStore::AddWatchOnly(const CTxDestination &dest) { LOCK(cs_KeyStore); CKeyID keyID; CBitcoinAddress(dest).GetKeyID(keyID); if (HaveKey(keyID)) return false; setWatchOnly.insert(dest); return true; } bool CBasicKeyStore::HaveWatchOnly(const CTxDestination &dest) const { LOCK(cs_KeyStore); return setWatchOnly.count(dest) > 0; } bool CCryptoKeyStore::SetCrypted() { { LOCK(cs_KeyStore); if (fUseCrypto) return true; if (!mapKeys.empty()) return false; fUseCrypto = true; } return true; } bool CCryptoKeyStore::Lock() { if (!SetCrypted()) return false; { LOCK(cs_KeyStore); vMasterKey.clear(); fWalletUnlockMintOnly = false; } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::Unlock(const CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; CryptedKeyMap::const_iterator mi = mapCryptedKeys.begin(); for (; mi != mapCryptedKeys.end(); ++mi) { const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; CSecret vchSecret; if(!DecryptSecret(vMasterKeyIn, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) return false; if (vchSecret.size() != 32) return false; CKey key; key.SetPubKey(vchPubKey); key.SetSecret(vchSecret); if (key.GetPubKey() == vchPubKey) break; return false; } vMasterKey = vMasterKeyIn; } NotifyStatusChanged(this); return true; } bool CCryptoKeyStore::AddKey(const CKey& key) { { LOCK(cs_KeyStore); CTxDestination address = key.GetPubKey().GetID(); if (HaveWatchOnly(address)) return false; if (!IsCrypted()) return CBasicKeyStore::AddKey(key); if (IsLocked()) return false; std::vector<unsigned char> vchCryptedSecret; CPubKey vchPubKey = key.GetPubKey(); bool fCompressed; if (!EncryptSecret(vMasterKey, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(key.GetPubKey(), vchCryptedSecret)) return false; } return true; } bool CCryptoKeyStore::AddCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret) { { LOCK(cs_KeyStore); if (!SetCrypted()) return false; mapCryptedKeys[vchPubKey.GetID()] = make_pair(vchPubKey, vchCryptedSecret); } return true; } bool CCryptoKeyStore::GetKey(const CKeyID &address, CKey& keyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CBasicKeyStore::GetKey(address, keyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { const CPubKey &vchPubKey = (*mi).second.first; const std::vector<unsigned char> &vchCryptedSecret = (*mi).second.second; CSecret vchSecret; if (!DecryptSecret(vMasterKey, vchCryptedSecret, vchPubKey.GetHash(), vchSecret)) return false; if (vchSecret.size() != 32) return false; keyOut.SetPubKey(vchPubKey); keyOut.SetSecret(vchSecret); return true; } } return false; } bool CCryptoKeyStore::GetPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const { { LOCK(cs_KeyStore); if (!IsCrypted()) return CKeyStore::GetPubKey(address, vchPubKeyOut); CryptedKeyMap::const_iterator mi = mapCryptedKeys.find(address); if (mi != mapCryptedKeys.end()) { vchPubKeyOut = (*mi).second.first; return true; } } return false; } bool CCryptoKeyStore::EncryptKeys(CKeyingMaterial& vMasterKeyIn) { { LOCK(cs_KeyStore); if (!mapCryptedKeys.empty() || IsCrypted()) return false; fUseCrypto = true; BOOST_FOREACH(KeyMap::value_type& mKey, mapKeys) { CKey key; if (!key.SetSecret(mKey.second.first, mKey.second.second)) return false; const CPubKey vchPubKey = key.GetPubKey(); std::vector<unsigned char> vchCryptedSecret; bool fCompressed; if (!EncryptSecret(vMasterKeyIn, key.GetSecret(fCompressed), vchPubKey.GetHash(), vchCryptedSecret)) return false; if (!AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; } mapKeys.clear(); } return true; } <|endoftext|>
<commit_before><commit_msg>fdo#76778 fix wildcard support in File Open dialog<commit_after><|endoftext|>
<commit_before>/* Copyright (c) 2017. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdint.h> #include <stddef.h> #include <string.h> #include <yara.h> extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv) { yr_initialize(); return 0; } extern "C" int LLVMFuzzerTestOneInput(const char *data, size_t size) { YR_RULES* rules; YR_COMPILER* compiler; char* buffer = (char*) malloc(size + 1); if (!buffer) return 1; strlcpy(buffer, data, size + 1); if (yr_compiler_create(&compiler) != ERROR_SUCCESS) return 1; if (yr_compiler_add_string(compiler, (const char*) buffer, NULL) == 0) { if (yr_compiler_get_rules(compiler, &rules) != ERROR_SUCCESS) return 1; } yr_compiler_destroy(compiler); return 0; }<commit_msg>Use strncpy instead of strlcpy in rules fuzzer as strlcpy is not defined in standard C.<commit_after>/* Copyright (c) 2017. The YARA Authors. All Rights Reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdint.h> #include <stddef.h> #include <string.h> #include <yara.h> extern "C" int LLVMFuzzerInitialize(int* argc, char*** argv) { yr_initialize(); return 0; } extern "C" int LLVMFuzzerTestOneInput(const char *data, size_t size) { YR_RULES* rules; YR_COMPILER* compiler; char* buffer = (char*) malloc(size + 1); if (!buffer) return 1; strncpy(buffer, data, size); buffer[size] = 0; if (yr_compiler_create(&compiler) != ERROR_SUCCESS) return 1; if (yr_compiler_add_string(compiler, (const char*) buffer, NULL) == 0) { if (yr_compiler_get_rules(compiler, &rules) != ERROR_SUCCESS) return 1; } yr_compiler_destroy(compiler); return 0; }<|endoftext|>
<commit_before>/* * MusicBrainz -- The Internet music metadatabase * * Copyright (C) 2006 Lukas Lalinsky * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ #include <string> #include <hash_map> #include <musicbrainz3/utils.h> using namespace std; using namespace stdext; using namespace MusicBrainz; std::string MusicBrainz::extractFragment(const string &uri) { // FIXME: proper URI parsing string::size_type pos = uri.find_last_of('#'); if (pos == string::npos) return uri; else return uri.substr(pos + 1); } std::string MusicBrainz::extractUuid(const string &uri) { if (uri.empty()) return uri; string types[] = {"artist/", "release/", "track/"}; for (int i = 0; i < 3; i++) { string::size_type pos = uri.find(types[0]); if (pos != string::npos) { pos += types[i].size() + 1; if (pos + 36 <= uri.size()) { return uri.substr(pos, 36); } } } // FIXME: ugh... if (uri.size() == 36) return uri; throw ValueError(uri + "is not a valid MusicBrainz ID."); } #include "utils_countrynames.h" string MusicBrainz::getCountryName(const string &id) { static bool countryNamesMapBuilt = false; static hash_map<string, string> countryNamesMap; if (!countryNamesMapBuilt) { for (int i = 0; i < (int)(sizeof(countryNames) / sizeof(countryNames[0])); i++) countryNamesMap[countryNames[i][0]] = countryNames[i][1]; countryNamesMapBuilt = true; } hash_map<string, string>::iterator i = countryNamesMap.find(id); return i == countryNamesMap.end() ? string() : i->second; } #include "utils_languagenames.h" string MusicBrainz::getLanguageName(const string &id) { static bool languageNamesMapBuilt = false; static hash_map<string, string> languageNamesMap; if (!languageNamesMapBuilt) { for (int i = 0; i < (int)(sizeof(languageNames) / sizeof(languageNames[0])); i++) languageNamesMap[languageNames[i][0]] = languageNames[i][1]; languageNamesMapBuilt = true; } hash_map<string, string>::iterator i = languageNamesMap.find(id); return i == languageNamesMap.end() ? string() : i->second; } #include "utils_scriptnames.h" string MusicBrainz::getScriptName(const string &id) { static bool scriptNamesMapBuilt = false; static hash_map<string, string> scriptNamesMap; if (!scriptNamesMapBuilt) { for (int i = 0; i < (int)(sizeof(scriptNames) / sizeof(scriptNames[0])); i++) scriptNamesMap[scriptNames[i][0]] = scriptNames[i][1]; scriptNamesMapBuilt = true; } hash_map<string, string>::iterator i = scriptNamesMap.find(id); return i == scriptNamesMap.end() ? string() : i->second; } #include "utils_releasetypenames.h" string MusicBrainz::getReleaseTypeName(const string &id) { static bool releaseTypeNamesMapBuilt = false; static hash_map<string, string> releaseTypeNamesMap; if (!releaseTypeNamesMapBuilt) { for (int i = 0; i < (int)(sizeof(releaseTypeNames) / sizeof(releaseTypeNames[0])); i++) releaseTypeNamesMap[releaseTypeNames[i][0]] = releaseTypeNames[i][1]; releaseTypeNamesMapBuilt = true; } hash_map<string, string>::iterator i = releaseTypeNamesMap.find(id); return i == releaseTypeNamesMap.end() ? string() : i->second; } <commit_msg>Use std::map for now.<commit_after>/* * MusicBrainz -- The Internet music metadatabase * * Copyright (C) 2006 Lukas Lalinsky * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id$ */ #include <string> #include <map> #include <musicbrainz3/utils.h> using namespace std; using namespace MusicBrainz; std::string MusicBrainz::extractFragment(const string &uri) { // FIXME: proper URI parsing string::size_type pos = uri.find_last_of('#'); if (pos == string::npos) return uri; else return uri.substr(pos + 1); } std::string MusicBrainz::extractUuid(const string &uri) { if (uri.empty()) return uri; string types[] = {"artist/", "release/", "track/"}; for (int i = 0; i < 3; i++) { string::size_type pos = uri.find(types[0]); if (pos != string::npos) { pos += types[i].size() + 1; if (pos + 36 <= uri.size()) { return uri.substr(pos, 36); } } } // FIXME: ugh... if (uri.size() == 36) return uri; throw ValueError(uri + "is not a valid MusicBrainz ID."); } #include "utils_countrynames.h" string MusicBrainz::getCountryName(const string &id) { static bool countryNamesMapBuilt = false; static map<string, string> countryNamesMap; if (!countryNamesMapBuilt) { for (int i = 0; i < (int)(sizeof(countryNames) / sizeof(countryNames[0])); i++) countryNamesMap[countryNames[i][0]] = countryNames[i][1]; countryNamesMapBuilt = true; } map<string, string>::iterator i = countryNamesMap.find(id); return i == countryNamesMap.end() ? string() : i->second; } #include "utils_languagenames.h" string MusicBrainz::getLanguageName(const string &id) { static bool languageNamesMapBuilt = false; static map<string, string> languageNamesMap; if (!languageNamesMapBuilt) { for (int i = 0; i < (int)(sizeof(languageNames) / sizeof(languageNames[0])); i++) languageNamesMap[languageNames[i][0]] = languageNames[i][1]; languageNamesMapBuilt = true; } map<string, string>::iterator i = languageNamesMap.find(id); return i == languageNamesMap.end() ? string() : i->second; } #include "utils_scriptnames.h" string MusicBrainz::getScriptName(const string &id) { static bool scriptNamesMapBuilt = false; static map<string, string> scriptNamesMap; if (!scriptNamesMapBuilt) { for (int i = 0; i < (int)(sizeof(scriptNames) / sizeof(scriptNames[0])); i++) scriptNamesMap[scriptNames[i][0]] = scriptNames[i][1]; scriptNamesMapBuilt = true; } map<string, string>::iterator i = scriptNamesMap.find(id); return i == scriptNamesMap.end() ? string() : i->second; } #include "utils_releasetypenames.h" string MusicBrainz::getReleaseTypeName(const string &id) { static bool releaseTypeNamesMapBuilt = false; static map<string, string> releaseTypeNamesMap; if (!releaseTypeNamesMapBuilt) { for (int i = 0; i < (int)(sizeof(releaseTypeNames) / sizeof(releaseTypeNames[0])); i++) releaseTypeNamesMap[releaseTypeNames[i][0]] = releaseTypeNames[i][1]; releaseTypeNamesMapBuilt = true; } map<string, string>::iterator i = releaseTypeNamesMap.find(id); return i == releaseTypeNamesMap.end() ? string() : i->second; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #define CLIENT_VERSION_SUFFIX "" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "657c9ed" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>util, info, txout<commit_after>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Satoshi"); // Client version number #define CLIENT_VERSION_SUFFIX "" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "e33e004" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("VCoin"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "54182cb" # define GIT_COMMIT_DATE "Mon, 7 Jul 2014 08:01:20 -0700" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>Update version.cpp<commit_after>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("Vcoin"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "54182cb" # define GIT_COMMIT_DATE "Mon, 7 Jul 2014 08:01:20 -0700" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>// Copyright (c) 2012 The paccoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both paccoind and paccoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("paccoin"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "99999" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE "July 4, 2013" # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>Update version.cpp<commit_after>// Copyright (c) 2012 The paccoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both paccoind and paccoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("paccoin"); // Client version number #define CLIENT_VERSION_SUFFIX "-beta" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "0" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE "Dec. 25, 2013" # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cybertron/cybertron.h" #include "cybertron/proto/chatter.pb.h" void MessageCallback( const std::shared_ptr<apollo::cybertron::proto::Chatter>& msg) { AINFO << "Received message seq-> " << msg->seq(); AINFO << "msgcontent->" << msg->content(); } int main(int argc, char *argv[]) { // init cybertron framework apollo::cybertron::Init(argv[0]); // create listener node auto listener_node = apollo::cybertron::CreateNode("listener"); // create listener auto listener = listener_node->CreateReader<apollo::cybertron::proto::Chatter>( "channel/chatter", MessageCallback); apollo::cybertron::WaitForShutdown(); return 0; } <commit_msg>framework: update listener example<commit_after>/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "cybertron/cybertron.h" #include "cybertron/proto/chatter.pb.h" void MessageCallback( const std::shared_ptr<apollo::cybertron::proto::Chatter>& msg) { AINFO << "Received message seq-> " << msg->seq(); AINFO << "msgcontent->" << msg->content(); } int main(int argc, char* argv[]) { // init cybertron framework apollo::cybertron::Init(argv[0]); // create listener node auto listener_node = apollo::cybertron::CreateNode("listener"); // create listener apollo::cybertron::proto::RoleAttributes attr; attr.set_channel_name("channel/chatter"); auto qos_profile = attr.mutable_qos_profile(); qos_profile->set_depth(10); auto listener = listener_node->CreateReader<apollo::cybertron::proto::Chatter>( attr, MessageCallback); apollo::cybertron::WaitForShutdown(); return 0; } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- Copyright (c) 2010 Nigel Atkinson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include <lua.hpp> #include <OgrePrerequisites.h> #include <OgreString.h> #include <OgreStringConverter.h> #include <git_versioning.h> #include <LuaBridge.h> Ogre::String versionString() { Ogre::String version; version = "Game Engine Testbed\n"; version += GIT_REPO_VERSION_STR; version += "\n"; version += "Ogre "; version += Ogre::StringConverter::toString( OGRE_VERSION_MAJOR ); version += "."; version += Ogre::StringConverter::toString( OGRE_VERSION_MINOR ); version += "."; version += Ogre::StringConverter::toString( OGRE_VERSION_PATCH ); version += " "; version += OGRE_VERSION_NAME; version += " "; version += OGRE_VERSION_SUFFIX; version += "\n"; version += LUA_RELEASE; version += "\n"; version += "LuaBridge "; version += Ogre::StringConverter::toString( LUABRIDGE_MAJOR_VERSION ); version += "."; version += Ogre::StringConverter::toString( LUABRIDGE_MINOR_VERSION ); version += "\n"; version += "Boost "; version += Ogre::StringConverter::toString( BOOST_VERSION / 100000 ); version += "."; version += Ogre::StringConverter::toString( BOOST_VERSION / 100 % 1000 ); version += "."; version += Ogre::StringConverter::toString( BOOST_VERSION % 100 ); version += "\n"; return version; } <commit_msg>Add boost header to version.cpp<commit_after>/* ----------------------------------------------------------------------------- Copyright (c) 2010 Nigel Atkinson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include <lua.hpp> #include <OgrePrerequisites.h> #include <OgreString.h> #include <OgreStringConverter.h> #include <git_versioning.h> #include <LuaBridge.h> #include <boost/version.hpp> Ogre::String versionString() { Ogre::String version; version = "Game Engine Testbed\n"; version += GIT_REPO_VERSION_STR; version += "\n"; version += "Ogre "; version += Ogre::StringConverter::toString( OGRE_VERSION_MAJOR ); version += "."; version += Ogre::StringConverter::toString( OGRE_VERSION_MINOR ); version += "."; version += Ogre::StringConverter::toString( OGRE_VERSION_PATCH ); version += " "; version += OGRE_VERSION_NAME; version += " "; version += OGRE_VERSION_SUFFIX; version += "\n"; version += LUA_RELEASE; version += "\n"; version += "LuaBridge "; version += Ogre::StringConverter::toString( LUABRIDGE_MAJOR_VERSION ); version += "."; version += Ogre::StringConverter::toString( LUABRIDGE_MINOR_VERSION ); version += "\n"; version += "Boost "; version += Ogre::StringConverter::toString( BOOST_VERSION / 100000 ); version += "."; version += Ogre::StringConverter::toString( BOOST_VERSION / 100 % 1000 ); version += "."; version += Ogre::StringConverter::toString( BOOST_VERSION % 100 ); version += "\n"; return version; } <|endoftext|>
<commit_before>// Copyright (c) 2016, blockoperation. All rights reserved. // boxnope is distributed under the terms of the BSD license. // See LICENSE for details. #ifndef BOXNOPE_UTILS_HPP #define BOXNOPE_UTILS_HPP #define QS(s) QString(s) #define QSL(s) QStringLiteral(s) #define QL1S(s) QLatin1String(s) #define QC(s) QChar(c) #define QL1C(c) QLatin1Char(c) #endif <commit_msg>Remove unused macros (and a typo)<commit_after>// Copyright (c) 2016, blockoperation. All rights reserved. // boxnope is distributed under the terms of the BSD license. // See LICENSE for details. #ifndef BOXNOPE_UTILS_HPP #define BOXNOPE_UTILS_HPP #define QS(s) QString(s) #define QSL(s) QStringLiteral(s) #define QL1S(s) QLatin1String(s) #endif <|endoftext|>
<commit_before>/* * Phusion Passenger - https://www.phusionpassenger.com/ * Copyright (c) 2014-2015 Phusion Holding B.V. * * "Passenger", "Phusion Passenger" and "Union Station" are registered * trademarks of Phusion Holding B.V. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <Core/Controller.h> /************************************************************************* * * Initialization and shutdown-related code for Core::Controller * *************************************************************************/ namespace Passenger { namespace Core { using namespace std; using namespace boost; /**************************** * * Public methods * ****************************/ Controller::Controller(ServerKit::Context *context, const VariantMap *_agentsOptions, unsigned int _threadNumber) : ParentClass(context), statThrottleRate(_agentsOptions->getInt("stat_throttle_rate")), responseBufferHighWatermark(_agentsOptions->getInt("response_buffer_high_watermark")), benchmarkMode(parseBenchmarkMode(_agentsOptions->get("benchmark_mode", false))), singleAppMode(false), showVersionInHeader(_agentsOptions->getBool("show_version_in_header")), stickySessions(_agentsOptions->getBool("sticky_sessions")), gracefulExit(_agentsOptions->getBool("core_graceful_exit")), agentsOptions(_agentsOptions), stringPool(psg_create_pool(1024 * 4)), poolOptionsCache(4), PASSENGER_APP_GROUP_NAME("!~PASSENGER_APP_GROUP_NAME"), PASSENGER_ENV_VARS("!~PASSENGER_ENV_VARS"), PASSENGER_MAX_REQUESTS("!~PASSENGER_MAX_REQUESTS"), PASSENGER_STICKY_SESSIONS("!~PASSENGER_STICKY_SESSIONS"), PASSENGER_STICKY_SESSIONS_COOKIE_NAME("!~PASSENGER_STICKY_SESSIONS_COOKIE_NAME"), PASSENGER_REQUEST_OOB_WORK("!~Request-OOB-Work"), UNION_STATION_SUPPORT("!~UNION_STATION_SUPPORT"), REMOTE_ADDR("!~REMOTE_ADDR"), REMOTE_PORT("!~REMOTE_PORT"), REMOTE_USER("!~REMOTE_USER"), FLAGS("!~FLAGS"), HTTP_COOKIE("cookie"), HTTP_DATE("date"), HTTP_HOST("host"), HTTP_CONTENT_LENGTH("content-length"), HTTP_CONTENT_TYPE("content-type"), HTTP_EXPECT("expect"), HTTP_CONNECTION("connection"), HTTP_STATUS("status"), HTTP_TRANSFER_ENCODING("transfer-encoding"), threadNumber(_threadNumber), turboCaching(getTurboCachingInitialState(_agentsOptions)) { defaultRuby = psg_pstrdup(stringPool, agentsOptions->get("default_ruby")); ustRouterAddress = psg_pstrdup(stringPool, agentsOptions->get("ust_router_address", false)); ustRouterPassword = psg_pstrdup(stringPool, agentsOptions->get("ust_router_password", false)); defaultUser = psg_pstrdup(stringPool, agentsOptions->get("default_user", false)); defaultGroup = psg_pstrdup(stringPool, agentsOptions->get("default_group", false)); defaultServerName = psg_pstrdup(stringPool, agentsOptions->get("default_server_name")); defaultServerPort = psg_pstrdup(stringPool, agentsOptions->get("default_server_port")); serverSoftware = psg_pstrdup(stringPool, agentsOptions->get("server_software")); defaultStickySessionsCookieName = psg_pstrdup(stringPool, agentsOptions->get("sticky_sessions_cookie_name")); if (agentsOptions->has("vary_turbocache_by_cookie")) { defaultVaryTurbocacheByCookie = psg_pstrdup(stringPool, agentsOptions->get("vary_turbocache_by_cookie")); } generateServerLogName(_threadNumber); if (!agentsOptions->getBool("multi_app")) { boost::shared_ptr<Options> options = boost::make_shared<Options>(); singleAppMode = true; fillPoolOptionsFromAgentsOptions(*options); options->appRoot = psg_pstrdup(stringPool, agentsOptions->get("app_root")); options->environment = psg_pstrdup(stringPool, agentsOptions->get("environment")); options->appType = psg_pstrdup(stringPool, agentsOptions->get("app_type")); options->startupFile = psg_pstrdup(stringPool, agentsOptions->get("startup_file")); poolOptionsCache.insert(options->getAppGroupName(), options); } ev_check_init(&checkWatcher, onEventLoopCheck); ev_set_priority(&checkWatcher, EV_MAXPRI); ev_check_start(getLoop(), &checkWatcher); checkWatcher.data = this; #ifdef DEBUG_CC_EVENT_LOOP_BLOCKING ev_prepare_init(&prepareWatcher, onEventLoopPrepare); ev_prepare_start(getLoop(), &prepareWatcher); prepareWatcher.data = this; timeBeforeBlocking = 0; #endif } Controller::~Controller() { psg_destroy_pool(stringPool); } void Controller::initialize() { TRACE_POINT(); if (resourceLocator == NULL) { throw RuntimeException("ResourceLocator not initialized"); } if (appPool == NULL) { throw RuntimeException("AppPool not initialized"); } if (unionStationContext == NULL) { unionStationContext = appPool->getUnionStationContext(); } } } // namespace Core } // namespace Passenger <commit_msg>Core::Controller: stop checkWatcher upon destruction<commit_after>/* * Phusion Passenger - https://www.phusionpassenger.com/ * Copyright (c) 2014-2015 Phusion Holding B.V. * * "Passenger", "Phusion Passenger" and "Union Station" are registered * trademarks of Phusion Holding B.V. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <Core/Controller.h> /************************************************************************* * * Initialization and shutdown-related code for Core::Controller * *************************************************************************/ namespace Passenger { namespace Core { using namespace std; using namespace boost; /**************************** * * Public methods * ****************************/ Controller::Controller(ServerKit::Context *context, const VariantMap *_agentsOptions, unsigned int _threadNumber) : ParentClass(context), statThrottleRate(_agentsOptions->getInt("stat_throttle_rate")), responseBufferHighWatermark(_agentsOptions->getInt("response_buffer_high_watermark")), benchmarkMode(parseBenchmarkMode(_agentsOptions->get("benchmark_mode", false))), singleAppMode(false), showVersionInHeader(_agentsOptions->getBool("show_version_in_header")), stickySessions(_agentsOptions->getBool("sticky_sessions")), gracefulExit(_agentsOptions->getBool("core_graceful_exit")), agentsOptions(_agentsOptions), stringPool(psg_create_pool(1024 * 4)), poolOptionsCache(4), PASSENGER_APP_GROUP_NAME("!~PASSENGER_APP_GROUP_NAME"), PASSENGER_ENV_VARS("!~PASSENGER_ENV_VARS"), PASSENGER_MAX_REQUESTS("!~PASSENGER_MAX_REQUESTS"), PASSENGER_STICKY_SESSIONS("!~PASSENGER_STICKY_SESSIONS"), PASSENGER_STICKY_SESSIONS_COOKIE_NAME("!~PASSENGER_STICKY_SESSIONS_COOKIE_NAME"), PASSENGER_REQUEST_OOB_WORK("!~Request-OOB-Work"), UNION_STATION_SUPPORT("!~UNION_STATION_SUPPORT"), REMOTE_ADDR("!~REMOTE_ADDR"), REMOTE_PORT("!~REMOTE_PORT"), REMOTE_USER("!~REMOTE_USER"), FLAGS("!~FLAGS"), HTTP_COOKIE("cookie"), HTTP_DATE("date"), HTTP_HOST("host"), HTTP_CONTENT_LENGTH("content-length"), HTTP_CONTENT_TYPE("content-type"), HTTP_EXPECT("expect"), HTTP_CONNECTION("connection"), HTTP_STATUS("status"), HTTP_TRANSFER_ENCODING("transfer-encoding"), threadNumber(_threadNumber), turboCaching(getTurboCachingInitialState(_agentsOptions)) { defaultRuby = psg_pstrdup(stringPool, agentsOptions->get("default_ruby")); ustRouterAddress = psg_pstrdup(stringPool, agentsOptions->get("ust_router_address", false)); ustRouterPassword = psg_pstrdup(stringPool, agentsOptions->get("ust_router_password", false)); defaultUser = psg_pstrdup(stringPool, agentsOptions->get("default_user", false)); defaultGroup = psg_pstrdup(stringPool, agentsOptions->get("default_group", false)); defaultServerName = psg_pstrdup(stringPool, agentsOptions->get("default_server_name")); defaultServerPort = psg_pstrdup(stringPool, agentsOptions->get("default_server_port")); serverSoftware = psg_pstrdup(stringPool, agentsOptions->get("server_software")); defaultStickySessionsCookieName = psg_pstrdup(stringPool, agentsOptions->get("sticky_sessions_cookie_name")); if (agentsOptions->has("vary_turbocache_by_cookie")) { defaultVaryTurbocacheByCookie = psg_pstrdup(stringPool, agentsOptions->get("vary_turbocache_by_cookie")); } generateServerLogName(_threadNumber); if (!agentsOptions->getBool("multi_app")) { boost::shared_ptr<Options> options = boost::make_shared<Options>(); singleAppMode = true; fillPoolOptionsFromAgentsOptions(*options); options->appRoot = psg_pstrdup(stringPool, agentsOptions->get("app_root")); options->environment = psg_pstrdup(stringPool, agentsOptions->get("environment")); options->appType = psg_pstrdup(stringPool, agentsOptions->get("app_type")); options->startupFile = psg_pstrdup(stringPool, agentsOptions->get("startup_file")); poolOptionsCache.insert(options->getAppGroupName(), options); } ev_check_init(&checkWatcher, onEventLoopCheck); ev_set_priority(&checkWatcher, EV_MAXPRI); ev_check_start(getLoop(), &checkWatcher); checkWatcher.data = this; #ifdef DEBUG_CC_EVENT_LOOP_BLOCKING ev_prepare_init(&prepareWatcher, onEventLoopPrepare); ev_prepare_start(getLoop(), &prepareWatcher); prepareWatcher.data = this; timeBeforeBlocking = 0; #endif } Controller::~Controller() { ev_check_stop(getLoop(), &checkWatcher); psg_destroy_pool(stringPool); } void Controller::initialize() { TRACE_POINT(); if (resourceLocator == NULL) { throw RuntimeException("ResourceLocator not initialized"); } if (appPool == NULL) { throw RuntimeException("AppPool not initialized"); } if (unionStationContext == NULL) { unionStationContext = appPool->getUnionStationContext(); } } } // namespace Core } // namespace Passenger <|endoftext|>
<commit_before>/* * Copyright 2003-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "transformer.h" #include <log4cxx/file.h> #include <apr_thread_proc.h> #include <apr_pools.h> #include <apr_file_io.h> #include <assert.h> #include <iostream> using namespace log4cxx; using namespace log4cxx::helpers; #if !defined(APR_FOPEN_READ) #define APR_FOPEN_READ APR_READ #define APR_FOPEN_CREATE APR_CREATE #define APR_FOPEN_WRITE APR_WRITE #define APR_FOPEN_TRUNCATE APR_TRUNCATE #define APR_FOPEN_APPEND APR_APPEND #endif void Transformer::transform(const File& in, const File& out, const std::vector<Filter *>& filters) { log4cxx::Filter::PatternList patterns; for(std::vector<Filter*>::const_iterator iter = filters.begin(); iter != filters.end(); iter++) { const log4cxx::Filter::PatternList& thesePatterns = (*iter)->getPatterns(); for (log4cxx::Filter::PatternList::const_iterator pattern = thesePatterns.begin(); pattern != thesePatterns.end(); pattern++) { patterns.push_back(*pattern); } } transform(in, out, patterns); } void Transformer::transform(const File& in, const File& out, const Filter& filter) { transform(in, out, filter.getPatterns()); } void Transformer::transform(const File& in, const File& out, const log4cxx::Filter::PatternList& patterns) { apr_pool_t* pool; apr_status_t stat = apr_pool_create(&pool, NULL); if (patterns.size() == 0) { // // fairly naive file copy code // // apr_file_t* child_out; apr_int32_t flags = APR_FOPEN_WRITE | APR_FOPEN_CREATE | APR_FOPEN_TRUNCATE; stat = apr_file_open(&child_out, out.getOSName().c_str(), flags, APR_OS_DEFAULT, pool); assert(stat == 0); apr_file_t* in_file; stat = apr_file_open(&in_file, in.getOSName().c_str(), APR_FOPEN_READ, APR_OS_DEFAULT, pool); assert(stat == 0); apr_size_t bufsize = 32000; void* buf = apr_palloc(pool, bufsize); apr_size_t bytesRead = bufsize; while(stat == 0 && bytesRead == bufsize) { stat = apr_file_read(in_file, buf, &bytesRead); if (stat == 0 && bytesRead > 0) { stat = apr_file_write(child_out, buf, &bytesRead); assert(stat == 0); } } } else { // // if there are patterns, invoke sed to execute the replacements // // apr_procattr_t* attr = NULL; stat = apr_procattr_create(&attr, pool); assert(stat == 0); // // find the program on the path // stat = apr_procattr_cmdtype_set(attr, APR_PROGRAM_PATH); assert(stat == 0); // // build the argument list // using Q as regex separator on s command // const char** args = (const char**) apr_palloc(pool, 6 * sizeof(*args)); int i = 0; // // write the regex's to a temporary file since they // may get mangled if passed as parameters // apr_file_t* regexFile; char regexName[400]; const char* tmpDir; stat = apr_temp_dir_get(&tmpDir, pool); strcpy(regexName, tmpDir); strcat(regexName, "/regexpXXXXXX"); stat = apr_file_mktemp(&regexFile, regexName, APR_WRITE | APR_CREATE, pool); assert(stat == 0); args[i++] = "-f"; const char* tmpName; stat = apr_file_name_get(&tmpName, regexFile); assert(stat == 0); args[i++] = tmpName; // // specify the input file args[i++] = in.getOSName().c_str(); args[i] = NULL; std::string tmp; for (log4cxx::Filter::PatternList::const_iterator iter = patterns.begin(); iter != patterns.end(); iter++) { tmp = "sQ"; tmp.append(iter->first); tmp.append(1, 'Q'); tmp.append(iter->second); tmp.append("Qg\n"); apr_file_puts(tmp.c_str(), regexFile); } apr_file_close(regexFile); // // set the output stream to go to the out file // apr_file_t* child_out; stat = apr_file_open(&child_out, out.getOSName().c_str(), APR_FOPEN_WRITE | APR_FOPEN_CREATE | APR_FOPEN_TRUNCATE, APR_OS_DEFAULT, pool); assert(stat == 0); stat = apr_procattr_child_out_set(attr, child_out, NULL); assert(stat == 0); // // redirect the child's error stream this processes // apr_file_t* child_err; stat = apr_file_open_stderr(&child_err, pool); assert(stat == 0); stat = apr_procattr_child_err_set(attr, child_err, NULL); assert(stat == 0); // // echo command to stdout // std::cout << "Running sed"; for(const char** arg = args; *arg != NULL; arg++) { std::cout << ' ' << *arg; } std::cout << " > " << out.getOSName(); apr_proc_t pid; stat = apr_proc_create(&pid,"sed", args, NULL, attr, pool); assert(stat == 0); apr_proc_wait(&pid, NULL, NULL, APR_WAIT); } apr_pool_destroy(pool); } <commit_msg>LOGCXX-54: boost-regex replacement still not quite working<commit_after>/* * Copyright 2003-2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "transformer.h" #include <log4cxx/file.h> #include <apr_thread_proc.h> #include <apr_pools.h> #include <apr_file_io.h> #include <assert.h> #include <iostream> using namespace log4cxx; using namespace log4cxx::helpers; #if !defined(APR_FOPEN_READ) #define APR_FOPEN_READ APR_READ #define APR_FOPEN_CREATE APR_CREATE #define APR_FOPEN_WRITE APR_WRITE #define APR_FOPEN_TRUNCATE APR_TRUNCATE #define APR_FOPEN_APPEND APR_APPEND #endif void Transformer::transform(const File& in, const File& out, const std::vector<Filter *>& filters) { log4cxx::Filter::PatternList patterns; for(std::vector<Filter*>::const_iterator iter = filters.begin(); iter != filters.end(); iter++) { const log4cxx::Filter::PatternList& thesePatterns = (*iter)->getPatterns(); for (log4cxx::Filter::PatternList::const_iterator pattern = thesePatterns.begin(); pattern != thesePatterns.end(); pattern++) { patterns.push_back(*pattern); } } transform(in, out, patterns); } void Transformer::transform(const File& in, const File& out, const Filter& filter) { transform(in, out, filter.getPatterns()); } void Transformer::transform(const File& in, const File& out, const log4cxx::Filter::PatternList& patterns) { { apr_pool_t* pool; apr_status_t stat = apr_pool_create(&pool, NULL); // // fairly naive file copy code // // apr_file_t* child_out; apr_int32_t flags = APR_FOPEN_WRITE | APR_FOPEN_CREATE | APR_FOPEN_TRUNCATE; stat = apr_file_open(&child_out, out.getOSName().c_str(), flags, APR_OS_DEFAULT, pool); assert(stat == 0); apr_file_t* in_file; stat = apr_file_open(&in_file, in.getOSName().c_str(), APR_FOPEN_READ, APR_OS_DEFAULT, pool); assert(stat == 0); apr_size_t bufsize = 32000; void* buf = apr_palloc(pool, bufsize); apr_size_t bytesRead = bufsize; while(stat == 0 && bytesRead == bufsize) { stat = apr_file_read(in_file, buf, &bytesRead); if (stat == 0 && bytesRead > 0) { stat = apr_file_write(child_out, buf, &bytesRead); assert(stat == 0); } } stat = apr_file_close(child_out); assert(stat == 0); apr_pool_destroy(pool); } if (patterns.size() > 0) { apr_pool_t* pool; apr_status_t stat = apr_pool_create(&pool, NULL); // // if there are patterns, invoke sed to execute the replacements // // apr_procattr_t* attr = NULL; stat = apr_procattr_create(&attr, pool); assert(stat == 0); // // find the program on the path // stat = apr_procattr_cmdtype_set(attr, APR_PROGRAM_PATH); assert(stat == 0); // // build the argument list // using Q as regex separator on s command // const char** args = (const char**) apr_palloc(pool, 6 * sizeof(*args)); int i = 0; // // write the regex's to a temporary file since they // may get mangled if passed as parameters // apr_file_t* regexFile; char regexName[400]; const char* tmpDir; stat = apr_temp_dir_get(&tmpDir, pool); strcpy(regexName, tmpDir); strcat(regexName, "/regexpXXXXXX"); apr_pool_t* regexPool; stat = apr_pool_create(&regexPool, pool); stat = apr_file_mktemp(&regexFile, regexName, APR_WRITE | APR_CREATE, regexPool); assert(stat == 0); args[i++] = "-f"; const char* tmpName; stat = apr_file_name_get(&tmpName, regexFile); assert(stat == 0); char* tmpName2 = (char*) apr_palloc(pool, strlen(tmpName) + 1); strcpy(tmpName2, tmpName); args[i++] = tmpName2; args[i++] = "-i"; // // specify the input file args[i++] = out.getOSName().c_str(); args[i] = NULL; std::string tmp; for (log4cxx::Filter::PatternList::const_iterator iter = patterns.begin(); iter != patterns.end(); iter++) { tmp = "sQ"; tmp.append(iter->first); tmp.append(1, 'Q'); tmp.append(iter->second); tmp.append("Qg\n"); apr_file_puts(tmp.c_str(), regexFile); } apr_file_close(regexFile); apr_pool_destroy(regexPool); // // set the output stream to go to the console // apr_file_t* child_out; stat = apr_file_open_stdout(&child_out, pool); assert(stat == 0); stat = apr_procattr_child_out_set(attr, child_out, NULL); assert(stat == 0); // // redirect the child's error stream this processes // apr_file_t* child_err; stat = apr_file_open_stderr(&child_err, pool); assert(stat == 0); stat = apr_procattr_child_err_set(attr, child_err, NULL); assert(stat == 0); // // echo command to stdout // std::cout << "Running sed"; for(const char** arg = args; *arg != NULL; arg++) { std::cout << ' ' << *arg; } std::cout << std::endl; apr_proc_t pid; stat = apr_proc_create(&pid,"sed", args, NULL, attr, pool); assert(stat == 0); apr_proc_wait(&pid, NULL, NULL, APR_WAIT); apr_pool_destroy(pool); } } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // Copyright (c) 2016 John D. Haughton // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //------------------------------------------------------------------------------ // Stub Frame implementation #include "PLT/Frame.h" namespace PLT { Frame::Frame(const char* title_, unsigned width_, unsigned height_, uint32_t flags_) : Image(width_, height_) { } Frame::~Frame() { } void Frame::blit(unsigned x, unsigned y, unsigned src_offset, unsigned src_width, const Image& src) { } void Frame::resize(unsigned width_, unsigned height_) { } void Frame::refresh() { } } // namespace PLT <commit_msg>Fix a warning in the Frame stub<commit_after>//------------------------------------------------------------------------------ // Copyright (c) 2016 John D. Haughton // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //------------------------------------------------------------------------------ // Stub Frame implementation #include "PLT/Frame.h" namespace PLT { Frame::Frame(const char* title_, unsigned width_, unsigned height_, uint32_t flags_) : Image(width_, height_) { pimpl = nullptr; } Frame::~Frame() { } void Frame::blit(unsigned x, unsigned y, unsigned src_offset, unsigned src_width, const Image& src) { } void Frame::resize(unsigned width_, unsigned height_) { } void Frame::refresh() { } } // namespace PLT <|endoftext|>
<commit_before>#include "GoogleLogFatalHandler.hpp" #include "Headers.hpp" namespace google { namespace glog_internal_namespace_ { void DumpStackTraceToString(string* stacktrace); } } // namespace google static void DumpStackTraceToFileAndExit() { string s; google::glog_internal_namespace_::DumpStackTraceToString(&s); LOG(ERROR) << "STACK TRACE:\n" << s; abort(); } namespace et { void GoogleLogFatalHandler::handle() { google::InstallFailureFunction(&DumpStackTraceToFileAndExit); } } // namespace et <commit_msg>Flush log after writing stack trace<commit_after>#include "GoogleLogFatalHandler.hpp" #include "Headers.hpp" namespace google { namespace glog_internal_namespace_ { void DumpStackTraceToString(string* stacktrace); } } // namespace google static void DumpStackTraceToFileAndExit() { string s; google::glog_internal_namespace_::DumpStackTraceToString(&s); LOG(ERROR) << "STACK TRACE:\n" << s; google::FlushLogFiles(google::GLOG_ERROR); abort(); } namespace et { void GoogleLogFatalHandler::handle() { google::InstallFailureFunction(&DumpStackTraceToFileAndExit); } } // namespace et <|endoftext|>
<commit_before> // XPNetPlugin.cpp #include "Platform.h" #include "XPNetPlugin.h" #include "xpnetclrhost.h" #include <stdint.h> #include <string> #if defined(WIN32) # include <experimental/filesystem> namespace fs = std::experimental::filesystem; #else # include <boost/filesystem.hpp> namespace fs = boost::filesystem; #endif // TODO: It would help with distribution if we had the macOS dotnet // path look in dotnet-macos or something like that. Then we could // also do dotnet-win and dotnet-linux. If we want backwards compat, // we could keep falling back to dotnet as well. With that change, // we could have private side-by-side .NET installs for all three // platforms. // Data - X-Plane API Function Pointer Types typedef XPLMDataRef(*PXPLMFindDataRef)(const char*); typedef XPLMDataTypeID(*PXPLMGetDataRefTypes)(XPLMDataRef); typedef int(*PXPLMGetDatai)(XPLMDataRef); typedef void(*PXPLMSetDatai)(XPLMDataRef, int); typedef int(*PXPLMGetDatavi)(XPLMDataRef, int*, int, int); typedef void(*PXPLMSetDatavi)(XPLMDataRef, int*, int, int); typedef float(*PXPLMGetDataf)(XPLMDataRef); typedef void(*PXPLMSetDataf)(XPLMDataRef, float); typedef int(*PXPLMGetDatavf)(XPLMDataRef, float*, int, int); typedef void(*PXPLMSetDatavf)(XPLMDataRef, float*, int, int); typedef double(*PXPLMGetDatad)(XPLMDataRef); typedef void(*PXPLMSetDatad)(XPLMDataRef, double); typedef int(*PXPLMGetDatab)(XPLMDataRef, void*, int, int); typedef void(*PXPLMSetDatab)(XPLMDataRef, void*, int, int); // Commands - X-Plane API Function Pointer Types typedef XPLMCommandRef(*PXPLMFindCommand)(const char*); typedef void(*PXPLMCommandBegin)(XPLMCommandRef); typedef void(*PXPLMCommandEnd)(XPLMCommandRef); typedef void(*PXPLMCommandOnce)(XPLMCommandRef); // Processing - X-Plane API Function Pointer Types typedef float(*PXPLMGetElapsedTime)(); typedef int(*PXPLMGetCycleNumber)(); typedef void(*PXPLMRegisterFlightLoopCallback)(XPLMFlightLoop_f, float, void*); typedef void(*PXPLMUnregisterFlightLoopCallback)(XPLMFlightLoop_f, void*); typedef void(*PXPLMSetFlightLoopCallbackInterval)(XPLMFlightLoop_f, float, int, void*); typedef XPLMFlightLoopID(*PXPLMCreateFlightLoop)(XPLMCreateFlightLoop_t*); typedef void(*PXPLMDestroyFlightLoop)(XPLMFlightLoopID); typedef void(*PXPLMScheduleFlightLoop)(XPLMFlightLoopID, float, int); // Function types for calling into XPNet.PluginBridge in the CLR. typedef int (STDMETHODCALLTYPE *PXPluginStart)(void*, void*); typedef void (STDMETHODCALLTYPE *PXPluginStop)(); typedef int (STDMETHODCALLTYPE *PXPluginEnable)(); typedef void (STDMETHODCALLTYPE *PXPluginDisable)(); typedef int (STDMETHODCALLTYPE *PXPluginReceiveMessage)(int, int, void*); static ClrToken s_clrToken; static PXPluginStart ClrPluginStart; static PXPluginStop ClrPluginStop; static PXPluginEnable ClrPluginEnable; static PXPluginDisable ClrPluginDisable; static PXPluginReceiveMessage ClrPluginReceiveMessage; static void* s_externalLoggingHandle = 0; typedef struct { // This type must be kept in sync with the version in C#. char name[256]; char sig[256]; char desc[256]; int64_t hLog; } StartParams; typedef struct { // This type must be kept in sync with the version in C#. // Data PXPLMFindDataRef XPLMFindDataRef; PXPLMGetDataRefTypes XPLMGetDataRefTypes; PXPLMGetDatai XPLMGetDatai; PXPLMSetDatai XPLMSetDatai; PXPLMGetDataf XPLMGetDataf; PXPLMSetDataf XPLMSetDataf; PXPLMGetDatad XPLMGetDatad; PXPLMSetDatad XPLMSetDatad; PXPLMGetDatavi XPLMGetDatavi; PXPLMSetDatavi XPLMSetDatavi; PXPLMGetDatavf XPLMGetDatavf; PXPLMSetDatavf XPLMSetDatavf; PXPLMGetDatab XPLMGetDatab; PXPLMSetDatab XPLMSetDatab; // Commands PXPLMFindCommand XPLMFindCommand; PXPLMCommandBegin XPLMCommandBegin; PXPLMCommandEnd XPLMCommandEnd; PXPLMCommandOnce XPLMCommandOnce; // Processing PXPLMGetElapsedTime XPLMGetElapsedTime; PXPLMGetCycleNumber XPLMGetCycleNumber; PXPLMRegisterFlightLoopCallback XPLMRegisterFlightLoopCallback; PXPLMUnregisterFlightLoopCallback XPLMUnregisterFlightLoopCallback; PXPLMSetFlightLoopCallbackInterval XPLMSetFlightLoopCallbackInterval; PXPLMCreateFlightLoop XPLMCreateFlightLoop; PXPLMDestroyFlightLoop XPLMDestroyFlightLoop; PXPLMScheduleFlightLoop XPLMScheduleFlightLoop; } ApiFunctions; std::wstring GetPluginDirectory() { char filePath[MAX_PATH]; XPLMGetPluginInfo(XPLMGetMyID(), NULL, filePath, NULL, NULL); fs::path fp = filePath; return fp.branch_path().generic_wstring(); } // This function is used for testing, to get logging to a different location // than the normal log file. XPNETPLUGIN_API void XPNetPluginSetExternalLoggingHandle(void* externalLoggingHandle) { s_externalLoggingHandle = externalLoggingHandle; } XPNETPLUGIN_API int XPluginStart(char* outName, char* outSig, char* outDesc) { if (!s_clrToken) { // The _very_ first thing to do is tell X-Plane to opt into Posix paths. // Otherwise, on macOS, it assumes the ancient Drive:Path:To:File convention. // We work entirely in Posix paths on all platforms. XPLMEnableFeature("XPLM_USE_NATIVE_PATHS", 1); fs::path pluginDir = GetPluginDirectory(); //#if defined(ARCH_32) // std::wstring archSubdir = L"32"; //#elif defined(ARCH_64) // std::wstring archSubdir = L"64"; //#else //# error "You must define either ARCH_32 or ARCH_64." //#endif XPLMDebugString(("XPNet: Loading plugins from " + pluginDir.generic_string() + "\n").c_str()); // In the Microsoft.NETCore.App folder, we expect to find exactly one directory, // whose name is the specific version number of Core. If there is more than one // directory, we just use the first one we find there - we expect an installation // to put exactly one version there. fs::path sharedAppPath = pluginDir / "dotnet" / "shared" / "Microsoft.NETCore.App"; fs::path dotnetPath = fs::directory_iterator(sharedAppPath)->path(); s_clrToken = LoadClr( dotnetPath.generic_wstring() + L"/", pluginDir.generic_wstring(), pluginDir.generic_wstring(), L"XPNet" ); if (!s_clrToken) { XPLMDebugString("XPNet: Failed to load CLR.\n"); return 0; } ClrPluginStart = GetClrMethod<PXPluginStart>(s_clrToken, L"XPNet.CLR", L"XPNet.PluginBridge", L"Start"); ClrPluginStop = GetClrMethod<PXPluginStop>(s_clrToken, L"XPNet.CLR", L"XPNet.PluginBridge", L"Stop"); ClrPluginEnable = GetClrMethod<PXPluginEnable>(s_clrToken, L"XPNet.CLR", L"XPNet.PluginBridge", L"Enable"); ClrPluginDisable = GetClrMethod<PXPluginDisable>(s_clrToken, L"XPNet.CLR", L"XPNet.PluginBridge", L"Disable"); ClrPluginReceiveMessage = GetClrMethod<PXPluginReceiveMessage>(s_clrToken, L"XPNet.CLR", L"XPNet.PluginBridge", L"ReceiveMessage"); } StartParams sp = { "", "", "", reinterpret_cast<int64_t>(s_externalLoggingHandle) }; ApiFunctions api = { // Data XPLMFindDataRef, XPLMGetDataRefTypes, XPLMGetDatai, XPLMSetDatai, XPLMGetDataf, XPLMSetDataf, XPLMGetDatad, XPLMSetDatad, XPLMGetDatavi, XPLMSetDatavi, XPLMGetDatavf, XPLMSetDatavf, XPLMGetDatab, XPLMSetDatab, // Commands XPLMFindCommand, XPLMCommandBegin, XPLMCommandEnd, XPLMCommandOnce, // Processing XPLMGetElapsedTime, XPLMGetCycleNumber, XPLMRegisterFlightLoopCallback, XPLMUnregisterFlightLoopCallback, XPLMSetFlightLoopCallbackInterval, XPLMCreateFlightLoop, XPLMDestroyFlightLoop, XPLMScheduleFlightLoop }; auto ret = ClrPluginStart(&sp, &api); if (ret) { strcp(outName, sp.name); strcp(outSig, sp.sig); strcp(outDesc, sp.desc); } XPLMDebugString(("XPNet: ClrPluginStart Result = " + std::to_string(ret) + ".\n").c_str()); return ret; } XPNETPLUGIN_API void XPluginStop(void) { if (!s_clrToken) return; ClrPluginStop(); // MAINT: .NET Core doesn't implement unloading yet, so don't even try. It would // return Success here but then fail when we try to load a new domain later. Instead, // we just make sure to clean up as best we can in our own C# code so that we're in // as clean an environment as possible when we start it back up again later. //UnloadClr(s_clrToken); //s_clrToken = 0; } XPNETPLUGIN_API int XPluginEnable(void) { if (!s_clrToken) return 0; return ClrPluginEnable(); } XPNETPLUGIN_API void XPluginDisable(void) { if (!s_clrToken) return; ClrPluginDisable(); } XPNETPLUGIN_API void XPluginReceiveMessage(XPLMPluginID inFrom, int inMsg, void * inParam) { if (!s_clrToken) return; ClrPluginReceiveMessage(inFrom, inMsg, inParam); } <commit_msg>Use parent_path instead of deprecated branch_path.<commit_after> // XPNetPlugin.cpp #include "Platform.h" #include "XPNetPlugin.h" #include "xpnetclrhost.h" #include <stdint.h> #include <string> #if defined(WIN32) # include <experimental/filesystem> namespace fs = std::experimental::filesystem; #else # include <boost/filesystem.hpp> namespace fs = boost::filesystem; #endif // TODO: It would help with distribution if we had the macOS dotnet // path look in dotnet-macos or something like that. Then we could // also do dotnet-win and dotnet-linux. If we want backwards compat, // we could keep falling back to dotnet as well. With that change, // we could have private side-by-side .NET installs for all three // platforms. // Data - X-Plane API Function Pointer Types typedef XPLMDataRef(*PXPLMFindDataRef)(const char*); typedef XPLMDataTypeID(*PXPLMGetDataRefTypes)(XPLMDataRef); typedef int(*PXPLMGetDatai)(XPLMDataRef); typedef void(*PXPLMSetDatai)(XPLMDataRef, int); typedef int(*PXPLMGetDatavi)(XPLMDataRef, int*, int, int); typedef void(*PXPLMSetDatavi)(XPLMDataRef, int*, int, int); typedef float(*PXPLMGetDataf)(XPLMDataRef); typedef void(*PXPLMSetDataf)(XPLMDataRef, float); typedef int(*PXPLMGetDatavf)(XPLMDataRef, float*, int, int); typedef void(*PXPLMSetDatavf)(XPLMDataRef, float*, int, int); typedef double(*PXPLMGetDatad)(XPLMDataRef); typedef void(*PXPLMSetDatad)(XPLMDataRef, double); typedef int(*PXPLMGetDatab)(XPLMDataRef, void*, int, int); typedef void(*PXPLMSetDatab)(XPLMDataRef, void*, int, int); // Commands - X-Plane API Function Pointer Types typedef XPLMCommandRef(*PXPLMFindCommand)(const char*); typedef void(*PXPLMCommandBegin)(XPLMCommandRef); typedef void(*PXPLMCommandEnd)(XPLMCommandRef); typedef void(*PXPLMCommandOnce)(XPLMCommandRef); // Processing - X-Plane API Function Pointer Types typedef float(*PXPLMGetElapsedTime)(); typedef int(*PXPLMGetCycleNumber)(); typedef void(*PXPLMRegisterFlightLoopCallback)(XPLMFlightLoop_f, float, void*); typedef void(*PXPLMUnregisterFlightLoopCallback)(XPLMFlightLoop_f, void*); typedef void(*PXPLMSetFlightLoopCallbackInterval)(XPLMFlightLoop_f, float, int, void*); typedef XPLMFlightLoopID(*PXPLMCreateFlightLoop)(XPLMCreateFlightLoop_t*); typedef void(*PXPLMDestroyFlightLoop)(XPLMFlightLoopID); typedef void(*PXPLMScheduleFlightLoop)(XPLMFlightLoopID, float, int); // Function types for calling into XPNet.PluginBridge in the CLR. typedef int (STDMETHODCALLTYPE *PXPluginStart)(void*, void*); typedef void (STDMETHODCALLTYPE *PXPluginStop)(); typedef int (STDMETHODCALLTYPE *PXPluginEnable)(); typedef void (STDMETHODCALLTYPE *PXPluginDisable)(); typedef int (STDMETHODCALLTYPE *PXPluginReceiveMessage)(int, int, void*); static ClrToken s_clrToken; static PXPluginStart ClrPluginStart; static PXPluginStop ClrPluginStop; static PXPluginEnable ClrPluginEnable; static PXPluginDisable ClrPluginDisable; static PXPluginReceiveMessage ClrPluginReceiveMessage; static void* s_externalLoggingHandle = 0; typedef struct { // This type must be kept in sync with the version in C#. char name[256]; char sig[256]; char desc[256]; int64_t hLog; } StartParams; typedef struct { // This type must be kept in sync with the version in C#. // Data PXPLMFindDataRef XPLMFindDataRef; PXPLMGetDataRefTypes XPLMGetDataRefTypes; PXPLMGetDatai XPLMGetDatai; PXPLMSetDatai XPLMSetDatai; PXPLMGetDataf XPLMGetDataf; PXPLMSetDataf XPLMSetDataf; PXPLMGetDatad XPLMGetDatad; PXPLMSetDatad XPLMSetDatad; PXPLMGetDatavi XPLMGetDatavi; PXPLMSetDatavi XPLMSetDatavi; PXPLMGetDatavf XPLMGetDatavf; PXPLMSetDatavf XPLMSetDatavf; PXPLMGetDatab XPLMGetDatab; PXPLMSetDatab XPLMSetDatab; // Commands PXPLMFindCommand XPLMFindCommand; PXPLMCommandBegin XPLMCommandBegin; PXPLMCommandEnd XPLMCommandEnd; PXPLMCommandOnce XPLMCommandOnce; // Processing PXPLMGetElapsedTime XPLMGetElapsedTime; PXPLMGetCycleNumber XPLMGetCycleNumber; PXPLMRegisterFlightLoopCallback XPLMRegisterFlightLoopCallback; PXPLMUnregisterFlightLoopCallback XPLMUnregisterFlightLoopCallback; PXPLMSetFlightLoopCallbackInterval XPLMSetFlightLoopCallbackInterval; PXPLMCreateFlightLoop XPLMCreateFlightLoop; PXPLMDestroyFlightLoop XPLMDestroyFlightLoop; PXPLMScheduleFlightLoop XPLMScheduleFlightLoop; } ApiFunctions; std::wstring GetPluginDirectory() { char filePath[MAX_PATH]; XPLMGetPluginInfo(XPLMGetMyID(), NULL, filePath, NULL, NULL); fs::path fp = filePath; return fp.parent_path().generic_wstring(); } // This function is used for testing, to get logging to a different location // than the normal log file. XPNETPLUGIN_API void XPNetPluginSetExternalLoggingHandle(void* externalLoggingHandle) { s_externalLoggingHandle = externalLoggingHandle; } XPNETPLUGIN_API int XPluginStart(char* outName, char* outSig, char* outDesc) { if (!s_clrToken) { // The _very_ first thing to do is tell X-Plane to opt into Posix paths. // Otherwise, on macOS, it assumes the ancient Drive:Path:To:File convention. // We work entirely in Posix paths on all platforms. XPLMEnableFeature("XPLM_USE_NATIVE_PATHS", 1); fs::path pluginDir = GetPluginDirectory(); //#if defined(ARCH_32) // std::wstring archSubdir = L"32"; //#elif defined(ARCH_64) // std::wstring archSubdir = L"64"; //#else //# error "You must define either ARCH_32 or ARCH_64." //#endif XPLMDebugString(("XPNet: Loading plugins from " + pluginDir.generic_string() + "\n").c_str()); // In the Microsoft.NETCore.App folder, we expect to find exactly one directory, // whose name is the specific version number of Core. If there is more than one // directory, we just use the first one we find there - we expect an installation // to put exactly one version there. fs::path sharedAppPath = pluginDir / "dotnet" / "shared" / "Microsoft.NETCore.App"; fs::path dotnetPath = fs::directory_iterator(sharedAppPath)->path(); s_clrToken = LoadClr( dotnetPath.generic_wstring() + L"/", pluginDir.generic_wstring(), pluginDir.generic_wstring(), L"XPNet" ); if (!s_clrToken) { XPLMDebugString("XPNet: Failed to load CLR.\n"); return 0; } ClrPluginStart = GetClrMethod<PXPluginStart>(s_clrToken, L"XPNet.CLR", L"XPNet.PluginBridge", L"Start"); ClrPluginStop = GetClrMethod<PXPluginStop>(s_clrToken, L"XPNet.CLR", L"XPNet.PluginBridge", L"Stop"); ClrPluginEnable = GetClrMethod<PXPluginEnable>(s_clrToken, L"XPNet.CLR", L"XPNet.PluginBridge", L"Enable"); ClrPluginDisable = GetClrMethod<PXPluginDisable>(s_clrToken, L"XPNet.CLR", L"XPNet.PluginBridge", L"Disable"); ClrPluginReceiveMessage = GetClrMethod<PXPluginReceiveMessage>(s_clrToken, L"XPNet.CLR", L"XPNet.PluginBridge", L"ReceiveMessage"); } StartParams sp = { "", "", "", reinterpret_cast<int64_t>(s_externalLoggingHandle) }; ApiFunctions api = { // Data XPLMFindDataRef, XPLMGetDataRefTypes, XPLMGetDatai, XPLMSetDatai, XPLMGetDataf, XPLMSetDataf, XPLMGetDatad, XPLMSetDatad, XPLMGetDatavi, XPLMSetDatavi, XPLMGetDatavf, XPLMSetDatavf, XPLMGetDatab, XPLMSetDatab, // Commands XPLMFindCommand, XPLMCommandBegin, XPLMCommandEnd, XPLMCommandOnce, // Processing XPLMGetElapsedTime, XPLMGetCycleNumber, XPLMRegisterFlightLoopCallback, XPLMUnregisterFlightLoopCallback, XPLMSetFlightLoopCallbackInterval, XPLMCreateFlightLoop, XPLMDestroyFlightLoop, XPLMScheduleFlightLoop }; auto ret = ClrPluginStart(&sp, &api); if (ret) { strcp(outName, sp.name); strcp(outSig, sp.sig); strcp(outDesc, sp.desc); } XPLMDebugString(("XPNet: ClrPluginStart Result = " + std::to_string(ret) + ".\n").c_str()); return ret; } XPNETPLUGIN_API void XPluginStop(void) { if (!s_clrToken) return; ClrPluginStop(); // MAINT: .NET Core doesn't implement unloading yet, so don't even try. It would // return Success here but then fail when we try to load a new domain later. Instead, // we just make sure to clean up as best we can in our own C# code so that we're in // as clean an environment as possible when we start it back up again later. //UnloadClr(s_clrToken); //s_clrToken = 0; } XPNETPLUGIN_API int XPluginEnable(void) { if (!s_clrToken) return 0; return ClrPluginEnable(); } XPNETPLUGIN_API void XPluginDisable(void) { if (!s_clrToken) return; ClrPluginDisable(); } XPNETPLUGIN_API void XPluginReceiveMessage(XPLMPluginID inFrom, int inMsg, void * inParam) { if (!s_clrToken) return; ClrPluginReceiveMessage(inFrom, inMsg, inParam); } <|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright (c) 2013-2020 Winlin * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SRS_CORE_PERFORMANCE_HPP #define SRS_CORE_PERFORMANCE_HPP #include <srs_core.hpp> /** * this file defines the perfromance options. */ /** * to improve read performance, merge some packets then read, * when it on and read small bytes, we sleep to wait more data., * that is, we merge some data to read together. * @see SrsConfig::get_mr_enabled() * @see SrsConfig::get_mr_sleep_ms() * @see https://github.com/ossrs/srs/issues/241 * @example, for the default settings, this algorithm will use: * that is, when got nread bytes smaller than 4KB, sleep(780ms). */ /** * https://github.com/ossrs/srs/issues/241#issuecomment-65554690 * The merged read algorithm is ok and can be simplified for: * 1. Suppose the client network is ok. All algorithm go wrong when netowrk is not ok. * 2. Suppose the client send each packet one by one. Although send some together, it's same. * 3. SRS MR algorithm will read all data then sleep. * So, the MR algorithm is: * while true: * read all data from socket. * sleep a while * For example, sleep 120ms. Then there is, and always 120ms data in buffer. * That is, the latency is 120ms(the sleep time). */ #define SRS_PERF_MERGED_READ // the default config of mr. #define SRS_PERF_MR_ENABLED false #define SRS_PERF_MR_SLEEP (350 * SRS_UTIME_MILLISECONDS) // For tcmalloc, set the default release rate. // @see https://gperftools.github.io/gperftools/tcmalloc.html #define SRS_PERF_TCMALLOC_RELEASE_RATE 0.8 /** * the MW(merged-write) send cache time in srs_utime_t. * the default value, user can override it in config. * to improve send performance, cache msgs and send in a time. * for example, cache 500ms videos and audios, then convert all these * msgs to iovecs, finally use writev to send. * @remark this largely improve performance, from 3.5k+ to 7.5k+. * the latency+ when cache+. * @remark the socket send buffer default to 185KB, it large enough. * @see https://github.com/ossrs/srs/issues/194 * @see SrsConfig::get_mw_sleep_ms() * @remark the mw sleep and msgs to send, maybe: * mw_sleep msgs iovs * 350 43 86 * 400 44 88 * 500 46 92 * 600 46 92 * 700 82 164 * 800 81 162 * 900 80 160 * 1000 88 176 * 1100 91 182 * 1200 89 178 * 1300 119 238 * 1400 120 240 * 1500 119 238 * 1600 131 262 * 1700 131 262 * 1800 133 266 * 1900 141 282 * 2000 150 300 */ // the default config of mw. #define SRS_PERF_MW_SLEEP (350 * SRS_UTIME_MILLISECONDS) /** * how many msgs can be send entirely. * for play clients to get msgs then totally send out. * for the mw sleep set to 1800, the msgs is about 133. * @remark, recomment to 128. */ #define SRS_PERF_MW_MSGS 128 /** * whether set the socket send buffer size. * @see https://github.com/ossrs/srs/issues/251 */ #define SRS_PERF_MW_SO_SNDBUF /** * whether set the socket recv buffer size. * @see https://github.com/ossrs/srs/issues/251 */ #undef SRS_PERF_MW_SO_RCVBUF /** * whether enable the fast vector for qeueue. * @see https://github.com/ossrs/srs/issues/251 */ #define SRS_PERF_QUEUE_FAST_VECTOR /** * whether use cond wait to send messages. * @remark this improve performance for large connectios. * @see https://github.com/ossrs/srs/issues/251 */ // TODO: FIXME: Should always enable it. #define SRS_PERF_QUEUE_COND_WAIT #ifdef SRS_PERF_QUEUE_COND_WAIT // For RTMP, use larger wait queue. #define SRS_PERF_MW_MIN_MSGS 8 // For RTC, use smaller wait queue. #define SRS_PERF_MW_MIN_MSGS_FOR_RTC 1 // For Real-Time, never wait messages. #define SRS_PERF_MW_MIN_MSGS_REALTIME 0 #endif /** * the default value of vhost for * SRS whether use the min latency mode. * for min latence mode: * 1. disable the mr for vhost. * 2. use timeout for cond wait for consumer queue. * @see https://github.com/ossrs/srs/issues/257 */ #define SRS_PERF_MIN_LATENCY_ENABLED false /** * how many chunk stream to cache, [0, N]. * to imporove about 10% performance when chunk size small, and 5% for large chunk. * @see https://github.com/ossrs/srs/issues/249 * @remark 0 to disable the chunk stream cache. */ #define SRS_PERF_CHUNK_STREAM_CACHE 16 /** * the gop cache and play cache queue. */ // whether gop cache is on. #define SRS_PERF_GOP_CACHE true // in srs_utime_t, the live queue length. #define SRS_PERF_PLAY_QUEUE (30 * SRS_UTIME_SECONDS) /** * whether always use complex send algorithm. * for some network does not support the complex send, * @see https://github.com/ossrs/srs/issues/320 */ //#undef SRS_PERF_COMPLEX_SEND #define SRS_PERF_COMPLEX_SEND /** * whether enable the TCP_NODELAY * user maybe need send small tcp packet for some network. * @see https://github.com/ossrs/srs/issues/320 */ #undef SRS_PERF_TCP_NODELAY #define SRS_PERF_TCP_NODELAY /** * set the socket send buffer, * to force the server to send smaller tcp packet. * @see https://github.com/ossrs/srs/issues/320 * @remark undef it to auto calc it by merged write sleep ms. * @remark only apply it when SRS_PERF_MW_SO_SNDBUF is defined. */ #ifdef SRS_PERF_MW_SO_SNDBUF //#define SRS_PERF_SO_SNDBUF_SIZE 1024 #undef SRS_PERF_SO_SNDBUF_SIZE #endif /** * whether ensure glibc memory check. */ #define SRS_PERF_GLIBC_MEMORY_CHECK #undef SRS_PERF_GLIBC_MEMORY_CHECK // For RTC, how many iovs we alloc for each mmsghdr for GSO. // Assume that there are 3300 clients, say, 10000 msgs in queue to send, the memory is: // 2 # We have two queue, cache and hotspot. // * 4 # We have reuseport, each have msg cache queue. // * (64 + 16*SRS_PERF_RTC_GSO_MAX + SRS_PERF_RTC_GSO_IOVS * 1500) # Each message size. // * 10000 # Total messages. // = 197MB # For SRS_PERF_RTC_GSO_IOVS = 1 // = 311MB # For SRS_PERF_RTC_GSO_IOVS = 2 // = 540MB # For SRS_PERF_RTC_GSO_IOVS = 4 // = 998MB # For SRS_PERF_RTC_GSO_IOVS = 8 #if defined(__linux__) #define SRS_PERF_RTC_GSO_IOVS 4 #else #define SRS_PERF_RTC_GSO_IOVS 1 #endif // For RTC, the max count of RTP packets we process in one loop. // TODO: FIXME: Remove it. #define SRS_PERF_RTC_RTP_PACKETS 1024 #endif <commit_msg>RTC: Remove dead macros<commit_after>/** * The MIT License (MIT) * * Copyright (c) 2013-2020 Winlin * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SRS_CORE_PERFORMANCE_HPP #define SRS_CORE_PERFORMANCE_HPP #include <srs_core.hpp> /** * this file defines the perfromance options. */ /** * to improve read performance, merge some packets then read, * when it on and read small bytes, we sleep to wait more data., * that is, we merge some data to read together. * @see SrsConfig::get_mr_enabled() * @see SrsConfig::get_mr_sleep_ms() * @see https://github.com/ossrs/srs/issues/241 * @example, for the default settings, this algorithm will use: * that is, when got nread bytes smaller than 4KB, sleep(780ms). */ /** * https://github.com/ossrs/srs/issues/241#issuecomment-65554690 * The merged read algorithm is ok and can be simplified for: * 1. Suppose the client network is ok. All algorithm go wrong when netowrk is not ok. * 2. Suppose the client send each packet one by one. Although send some together, it's same. * 3. SRS MR algorithm will read all data then sleep. * So, the MR algorithm is: * while true: * read all data from socket. * sleep a while * For example, sleep 120ms. Then there is, and always 120ms data in buffer. * That is, the latency is 120ms(the sleep time). */ #define SRS_PERF_MERGED_READ // the default config of mr. #define SRS_PERF_MR_ENABLED false #define SRS_PERF_MR_SLEEP (350 * SRS_UTIME_MILLISECONDS) // For tcmalloc, set the default release rate. // @see https://gperftools.github.io/gperftools/tcmalloc.html #define SRS_PERF_TCMALLOC_RELEASE_RATE 0.8 /** * the MW(merged-write) send cache time in srs_utime_t. * the default value, user can override it in config. * to improve send performance, cache msgs and send in a time. * for example, cache 500ms videos and audios, then convert all these * msgs to iovecs, finally use writev to send. * @remark this largely improve performance, from 3.5k+ to 7.5k+. * the latency+ when cache+. * @remark the socket send buffer default to 185KB, it large enough. * @see https://github.com/ossrs/srs/issues/194 * @see SrsConfig::get_mw_sleep_ms() * @remark the mw sleep and msgs to send, maybe: * mw_sleep msgs iovs * 350 43 86 * 400 44 88 * 500 46 92 * 600 46 92 * 700 82 164 * 800 81 162 * 900 80 160 * 1000 88 176 * 1100 91 182 * 1200 89 178 * 1300 119 238 * 1400 120 240 * 1500 119 238 * 1600 131 262 * 1700 131 262 * 1800 133 266 * 1900 141 282 * 2000 150 300 */ // the default config of mw. #define SRS_PERF_MW_SLEEP (350 * SRS_UTIME_MILLISECONDS) /** * how many msgs can be send entirely. * for play clients to get msgs then totally send out. * for the mw sleep set to 1800, the msgs is about 133. * @remark, recomment to 128. */ #define SRS_PERF_MW_MSGS 128 /** * whether set the socket send buffer size. * @see https://github.com/ossrs/srs/issues/251 */ #define SRS_PERF_MW_SO_SNDBUF /** * whether set the socket recv buffer size. * @see https://github.com/ossrs/srs/issues/251 */ #undef SRS_PERF_MW_SO_RCVBUF /** * whether enable the fast vector for qeueue. * @see https://github.com/ossrs/srs/issues/251 */ #define SRS_PERF_QUEUE_FAST_VECTOR /** * whether use cond wait to send messages. * @remark this improve performance for large connectios. * @see https://github.com/ossrs/srs/issues/251 */ // TODO: FIXME: Should always enable it. #define SRS_PERF_QUEUE_COND_WAIT #ifdef SRS_PERF_QUEUE_COND_WAIT // For RTMP, use larger wait queue. #define SRS_PERF_MW_MIN_MSGS 8 // For RTC, use smaller wait queue. #define SRS_PERF_MW_MIN_MSGS_FOR_RTC 1 // For Real-Time, never wait messages. #define SRS_PERF_MW_MIN_MSGS_REALTIME 0 #endif /** * the default value of vhost for * SRS whether use the min latency mode. * for min latence mode: * 1. disable the mr for vhost. * 2. use timeout for cond wait for consumer queue. * @see https://github.com/ossrs/srs/issues/257 */ #define SRS_PERF_MIN_LATENCY_ENABLED false /** * how many chunk stream to cache, [0, N]. * to imporove about 10% performance when chunk size small, and 5% for large chunk. * @see https://github.com/ossrs/srs/issues/249 * @remark 0 to disable the chunk stream cache. */ #define SRS_PERF_CHUNK_STREAM_CACHE 16 /** * the gop cache and play cache queue. */ // whether gop cache is on. #define SRS_PERF_GOP_CACHE true // in srs_utime_t, the live queue length. #define SRS_PERF_PLAY_QUEUE (30 * SRS_UTIME_SECONDS) /** * whether always use complex send algorithm. * for some network does not support the complex send, * @see https://github.com/ossrs/srs/issues/320 */ //#undef SRS_PERF_COMPLEX_SEND #define SRS_PERF_COMPLEX_SEND /** * whether enable the TCP_NODELAY * user maybe need send small tcp packet for some network. * @see https://github.com/ossrs/srs/issues/320 */ #undef SRS_PERF_TCP_NODELAY #define SRS_PERF_TCP_NODELAY /** * set the socket send buffer, * to force the server to send smaller tcp packet. * @see https://github.com/ossrs/srs/issues/320 * @remark undef it to auto calc it by merged write sleep ms. * @remark only apply it when SRS_PERF_MW_SO_SNDBUF is defined. */ #ifdef SRS_PERF_MW_SO_SNDBUF //#define SRS_PERF_SO_SNDBUF_SIZE 1024 #undef SRS_PERF_SO_SNDBUF_SIZE #endif /** * whether ensure glibc memory check. */ #define SRS_PERF_GLIBC_MEMORY_CHECK #undef SRS_PERF_GLIBC_MEMORY_CHECK #endif <|endoftext|>
<commit_before>/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | license@swoole.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <mikan.tenny@gmail.com> | +----------------------------------------------------------------------+ */ #include "static_handler.h" #include <string> #include <unordered_set> using namespace std; using swoole::http::StaticHandler; unordered_set<string> types; unordered_set<string> locations; bool StaticHandler::is_modified(const string &date_if_modified_since) { char date_tmp[64]; if (date_if_modified_since.empty() || date_if_modified_since.length() > sizeof(date_tmp) - 1) { return false; } struct tm tm3; memcpy(date_tmp, date_if_modified_since.c_str(), date_if_modified_since.length()); date_tmp[date_if_modified_since.length()] = 0; const char *date_format = nullptr; if (strptime(date_tmp, SW_HTTP_RFC1123_DATE_GMT, &tm3) != NULL) { date_format = SW_HTTP_RFC1123_DATE_GMT; } else if (strptime(date_tmp, SW_HTTP_RFC1123_DATE_UTC, &tm3) != NULL) { date_format = SW_HTTP_RFC1123_DATE_UTC; } else if (strptime(date_tmp, SW_HTTP_RFC850_DATE, &tm3) != NULL) { date_format = SW_HTTP_RFC850_DATE; } else if (strptime(date_tmp, SW_HTTP_ASCTIME_DATE, &tm3) != NULL) { date_format = SW_HTTP_ASCTIME_DATE; } if (date_format && mktime(&tm3) - (int) serv->timezone >= get_file_mtime()) { return true; } else { return false; } } std::string StaticHandler::get_date() { char date_[64]; struct tm *tm1 = gmtime(&serv->gs->now); strftime(date_, sizeof(date_), "%a, %d %b %Y %H:%M:%S %Z", tm1); return std::string(date_); } std::string StaticHandler::get_date_last_modified() { char date_last_modified[64]; time_t file_mtime = get_file_mtime(); struct tm *tm2 = gmtime(&file_mtime); strftime(date_last_modified, sizeof(date_last_modified), "%a, %d %b %Y %H:%M:%S %Z", tm2); return std::string(date_last_modified); } bool StaticHandler::hit() { char *p = task.filename; const char *url = request_url.c_str(); size_t url_length = request_url.length(); /** * discard the url parameter * [/test.jpg?version=1#position] -> [/test.jpg] */ char *params = (char*) memchr(url, '?', url_length); if (params == NULL) { params = (char*) memchr(url, '#', url_length); } size_t n = params ? params - url : url_length; memcpy(p, serv->document_root, serv->document_root_len); p += serv->document_root_len; if (locations.size() > 0) { for (auto i = locations.begin(); i != locations.end(); i++) { if (swoole_strcasect(url, url_length, i->c_str(), i->size())) { last = true; } } if (!last) { return false; } } if (serv->document_root_len + n >= PATH_MAX) { return false; } memcpy(p, url, n); p += n; *p = '\0'; l_filename = swHttp_url_decode(task.filename, p - task.filename); task.filename[l_filename] = '\0'; if (swoole_strnpos(url, n, SW_STRL("..")) == -1) { goto _detect_mime_type; } char real_path[PATH_MAX]; if (!realpath(task.filename, real_path)) { if (last) { status_code = SW_HTTP_NOT_FOUND; return true; } else { return false; } } if (real_path[serv->document_root_len] != '/') { return false; } if (swoole_streq(real_path, strlen(real_path), serv->document_root, serv->document_root_len) != 0) { return false; } /** * non-static file */ _detect_mime_type: if (!swoole_mime_type_exists(task.filename)) { return false; } /** * file does not exist */ if (lstat(task.filename, &file_stat) < 0) { if (last) { status_code = SW_HTTP_NOT_FOUND; return true; } else { return false; } } if (file_stat.st_size == 0) { return false; } if ((file_stat.st_mode & S_IFMT) != S_IFREG) { return false; } task.length = get_filesize(); return true; } int swHttp_static_handler_add_location(swServer *serv, const char *location, size_t length) { locations.insert(string(location, length)); return SW_OK; } <commit_msg>Code optimization<commit_after>/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | license@swoole.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <mikan.tenny@gmail.com> | +----------------------------------------------------------------------+ */ #include "static_handler.h" #include <string> #include <unordered_set> using namespace std; using swoole::http::StaticHandler; unordered_set<string> types; unordered_set<string> locations; bool StaticHandler::is_modified(const string &date_if_modified_since) { char date_tmp[64]; if (date_if_modified_since.empty() || date_if_modified_since.length() > sizeof(date_tmp) - 1) { return false; } struct tm tm3; memcpy(date_tmp, date_if_modified_since.c_str(), date_if_modified_since.length()); date_tmp[date_if_modified_since.length()] = 0; const char *date_format = nullptr; if (strptime(date_tmp, SW_HTTP_RFC1123_DATE_GMT, &tm3) != NULL) { date_format = SW_HTTP_RFC1123_DATE_GMT; } else if (strptime(date_tmp, SW_HTTP_RFC1123_DATE_UTC, &tm3) != NULL) { date_format = SW_HTTP_RFC1123_DATE_UTC; } else if (strptime(date_tmp, SW_HTTP_RFC850_DATE, &tm3) != NULL) { date_format = SW_HTTP_RFC850_DATE; } else if (strptime(date_tmp, SW_HTTP_ASCTIME_DATE, &tm3) != NULL) { date_format = SW_HTTP_ASCTIME_DATE; } return date_format && mktime(&tm3) - (int) serv->timezone >= get_file_mtime(); } std::string StaticHandler::get_date() { char date_[64]; struct tm *tm1 = gmtime(&serv->gs->now); strftime(date_, sizeof(date_), "%a, %d %b %Y %H:%M:%S %Z", tm1); return std::string(date_); } std::string StaticHandler::get_date_last_modified() { char date_last_modified[64]; time_t file_mtime = get_file_mtime(); struct tm *tm2 = gmtime(&file_mtime); strftime(date_last_modified, sizeof(date_last_modified), "%a, %d %b %Y %H:%M:%S %Z", tm2); return std::string(date_last_modified); } bool StaticHandler::hit() { char *p = task.filename; const char *url = request_url.c_str(); size_t url_length = request_url.length(); /** * discard the url parameter * [/test.jpg?version=1#position] -> [/test.jpg] */ char *params = (char*) memchr(url, '?', url_length); if (params == NULL) { params = (char*) memchr(url, '#', url_length); } size_t n = params ? params - url : url_length; memcpy(p, serv->document_root, serv->document_root_len); p += serv->document_root_len; if (locations.size() > 0) { for (auto i = locations.begin(); i != locations.end(); i++) { if (swoole_strcasect(url, url_length, i->c_str(), i->size())) { last = true; } } if (!last) { return false; } } if (serv->document_root_len + n >= PATH_MAX) { return false; } memcpy(p, url, n); p += n; *p = '\0'; l_filename = swHttp_url_decode(task.filename, p - task.filename); task.filename[l_filename] = '\0'; if (swoole_strnpos(url, n, SW_STRL("..")) == -1) { goto _detect_mime_type; } char real_path[PATH_MAX]; if (!realpath(task.filename, real_path)) { if (last) { status_code = SW_HTTP_NOT_FOUND; return true; } else { return false; } } if (real_path[serv->document_root_len] != '/') { return false; } if (swoole_streq(real_path, strlen(real_path), serv->document_root, serv->document_root_len) != 0) { return false; } /** * non-static file */ _detect_mime_type: if (!swoole_mime_type_exists(task.filename)) { return false; } /** * file does not exist */ if (lstat(task.filename, &file_stat) < 0) { if (last) { status_code = SW_HTTP_NOT_FOUND; return true; } else { return false; } } if (file_stat.st_size == 0) { return false; } if ((file_stat.st_mode & S_IFMT) != S_IFREG) { return false; } task.length = get_filesize(); return true; } int swHttp_static_handler_add_location(swServer *serv, const char *location, size_t length) { locations.insert(string(location, length)); return SW_OK; } <|endoftext|>
<commit_before>/** * \class ROT13 * @file ROT13.hpp * * @par Licence * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #ifndef ROT13_HPP #define ROT13_HPP #define ASCII_for_A 65 #define ASCII_for_Z 90 #define ASCII_for_a 97 #define ASCII_for_z 122 #include <iostream> #include <string> class ROT13{ private: /** * @brief parameters */ const std::size_t latin_alphabet=26; const std::size_t ROT13_shift=13; std::string Text; std::string New_text; public: /** * @brief Constructor of ROT13 code object * text is the text to either cypher or decypher * * @param[in] text */ ROT13(std::string Text, ); /** * @brief Default constructor of ROT13 code object * just to avoid errors if someone would like to * encrypt/decrypt without giving text * */ ROT13(); /** * @brief Encrypt the message using ROT13 method * to shift the letters * * @return nothing */ void encryptMessage(); /** * @brief Decrypt the message using ROT13 method * to shift the letters * * @return nothing */ void decryptMessage(); /** * @brief Setter for param Shift * * @return nothing */ void calculations(bool isEncryption); /** * @brief Setter for param Text * * @return nothing */ void setText(std::string Text); }; #endif // ROT13_HPP <commit_msg>Update ROT13.hpp<commit_after>/** * \class ROT13 * @file ROT13.hpp * * @par Licence * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ #ifndef ROT13_HPP #define ROT13_HPP #define ASCII_for_A 65 #define ASCII_for_Z 90 #define ASCII_for_a 97 #define ASCII_for_z 122 #include <iostream> #include <string> class ROT13{ private: /** * @brief parameters */ const std::size_t latin_alphabet=26; const std::size_t ROT13_shift=13; std::string Text; std::string New_text; public: /** * @brief Constructor of ROT13 code object * text is the text to either cypher or decypher * * @param[in] text */ ROT13(std::string Text); /** * @brief Default constructor of ROT13 code object * just to avoid errors if someone would like to * encrypt/decrypt without giving text * */ ROT13(); /** * @brief Encrypt the message using ROT13 method * to shift the letters * * @return nothing */ void encryptMessage(); /** * @brief Decrypt the message using ROT13 method * to shift the letters * * @return nothing */ void decryptMessage(); /** * @brief Setter for param Shift * * @return nothing */ void calculations(bool isEncryption); /** * @brief Setter for param Text * * @return nothing */ void setText(std::string Text); }; #endif // ROT13_HPP <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX64M グループ SDRAM 設定 @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "RX64M/system.hpp" namespace device { namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief SDRAM 種別 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class sdram_size { }; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief SDRAM 制御クラス */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <sdram_size size> class sdram { public: void init() { // SDRAM 初期化 128M/32bits bus device::MPC::PFAOE0 = 0xff; // A8 to A15 device::MPC::PFBCR0 = device::MPC::PFBCR0.ADRLE.b(1) | device::MPC::PFBCR0.DHE.b(1) | device::MPC::PFBCR0.DH32E.b(1); device::MPC::PFBCR1 = device::MPC::PFBCR1.MDSDE.b(1) | device::MPC::PFBCR1.DQM1E.b(1) | device::MPC::PFBCR1.SDCLKE.b(1); device::SYSTEM::SYSCR0 = device::SYSTEM::SYSCR0.KEY.b(0x5A) | device::SYSTEM::SYSCR0.ROME.b(1) | device::SYSTEM::SYSCR0.EXBE.b(1); while(device::SYSTEM::SYSCR0.EXBE() == 0) asm("nop"); device::BUS::SDIR = device::BUS::SDIR.ARFI.b(0) | device::BUS::SDIR.ARFC.b(1) | device::BUS::SDIR.PRC.b(0); device::BUS::SDICR = device::BUS::SDICR.INIRQ.b(1); // 初期化シーケンス開始 while(device::BUS::SDSR() != 0) asm("nop"); // 動作許可、32ビットアクセス device::BUS::SDCCR = device::BUS::SDCCR.BSIZE.b(1); // Burst read and burst write, CAS latency: 3, Burst type: Sequential, Burst length: 1 device::BUS::SDMOD = 0b00000000110000; // CAS latency: 3, Write recovery: 1, ROW prechage: 4, RAS latency: 3, RAS active: 4 device::BUS::SDTR = device::BUS::SDTR.CL.b(3) | device::BUS::SDTR.RP.b(3) | device::BUS::SDTR.RCD.b(2) | device::BUS::SDTR.RAS.b(3); // 128M/16 カラム9ビット、ロウ12ビット device::BUS::SDADR = device::BUS::SDADR.MXC.b(1); // Refresh cycle device::BUS::SDRFCR = device::BUS::SDRFCR.RFC.b(2048) | device::BUS::SDRFCR.REFW.b(7); device::BUS::SDRFEN = device::BUS::SDRFEN.RFEN.b(1); // SDRAM 動作開始 device::BUS::SDCCR.EXENB = 1; } }; } <commit_msg>update sdram class<commit_after>#pragma once //=====================================================================// /*! @file @brief RX64M グループ SDRAM 設定 @n Copyright 2017 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "RX64M/system.hpp" namespace utils { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief SDRAM 種別 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class sdram_type { M128, ///< 128 Mbits (16 Mbytes) M256, ///< 256 Mbits (32 Mbytes) M512, ///< 512 Mbits (64 Mbytes) }; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief バス幅 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// enum class sdram_width { W16, ///< 16 bits W32, ///< 32 bits }; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief SDRAM 制御クラス @param[in] mtype メモリータイプ @param[in] busw バス幅 */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <sdram_type mtype, sdram_width busw> class sdram { public: void operator() () { // SDRAM 初期化 128M/32bits bus device::MPC::PFAOE0 = 0xff; // A8 to A15 device::MPC::PFBCR0 = device::MPC::PFBCR0.ADRLE.b(1) | device::MPC::PFBCR0.DHE.b(1) | device::MPC::PFBCR0.DH32E.b(1); device::MPC::PFBCR1 = device::MPC::PFBCR1.MDSDE.b(1) | device::MPC::PFBCR1.DQM1E.b(1) | device::MPC::PFBCR1.SDCLKE.b(1); device::SYSTEM::SYSCR0 = device::SYSTEM::SYSCR0.KEY.b(0x5A) | device::SYSTEM::SYSCR0.ROME.b(1) | device::SYSTEM::SYSCR0.EXBE.b(1); while(device::SYSTEM::SYSCR0.EXBE() == 0) asm("nop"); device::BUS::SDIR = device::BUS::SDIR.ARFI.b(0) | device::BUS::SDIR.ARFC.b(1) | device::BUS::SDIR.PRC.b(0); device::BUS::SDICR = device::BUS::SDICR.INIRQ.b(1); // 初期化シーケンス開始 while(device::BUS::SDSR() != 0) asm("nop"); // 動作許可、32ビットアクセス device::BUS::SDCCR = device::BUS::SDCCR.BSIZE.b(1); // Burst read and burst write, CAS latency: 3, Burst type: Sequential, Burst length: 1 device::BUS::SDMOD = 0b00000000110000; // CAS latency: 3, Write recovery: 1, ROW prechage: 4, RAS latency: 3, RAS active: 4 device::BUS::SDTR = device::BUS::SDTR.CL.b(3) | device::BUS::SDTR.RP.b(3) | device::BUS::SDTR.RCD.b(2) | device::BUS::SDTR.RAS.b(3); // 128M/16 カラム9ビット、ロウ12ビット device::BUS::SDADR = device::BUS::SDADR.MXC.b(1); // Refresh cycle device::BUS::SDRFCR = device::BUS::SDRFCR.RFC.b(2048) | device::BUS::SDRFCR.REFW.b(7); device::BUS::SDRFEN = device::BUS::SDRFEN.RFEN.b(1); // SDRAM 動作開始 device::BUS::SDCCR.EXENB = 1; } }; typedef sdram<sdram_type::M128, sdram_width::W16> SDRAM_128M_16W; typedef sdram<sdram_type::M128, sdram_width::W32> SDRAM_128M_32W; typedef sdram<sdram_type::M256, sdram_width::W16> SDRAM_256M_16W; typedef sdram<sdram_type::M256, sdram_width::W32> SDRAM_256M_32W; typedef sdram<sdram_type::M512, sdram_width::W16> SDRAM_512M_16W; typedef sdram<sdram_type::M512, sdram_width::W32> SDRAM_512M_32W; } <|endoftext|>
<commit_before> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE libstorage #include <iostream> #include <boost/test/unit_test.hpp> #include "storage/Environment.h" #include "storage/Storage.h" #include "storage/DevicegraphImpl.h" #include "storage/UsedFeatures.h" #include "testsuite/helpers/TsCmp.h" using namespace std; using namespace storage; // TODO also check the check functions BOOST_AUTO_TEST_CASE(probe) { set_logger(get_stdout_logger()); Environment environment(true, ProbeMode::READ_MOCKUP, TargetMode::DIRECT); environment.set_mockup_filename("lvm-errors1-mockup.xml"); Storage storage(environment); storage.probe(); const Devicegraph* probed = storage.get_probed(); // probed->check(); Devicegraph* staging = storage.get_staging(); staging->load("lvm-errors1-devicegraph.xml"); // staging->check(); TsCmpDevicegraph cmp(*probed, *staging); BOOST_CHECK_MESSAGE(cmp.ok(), cmp); BOOST_CHECK_BITWISE_EQUAL(probed->used_features(), (uint64_t)(UF_LVM)); } <commit_msg>- extended unit test<commit_after> #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE libstorage #include <iostream> #include <boost/test/unit_test.hpp> #include "storage/Environment.h" #include "storage/Storage.h" #include "storage/DevicegraphImpl.h" #include "storage/UsedFeatures.h" #include "testsuite/helpers/TsCmp.h" #include "testsuite/helpers/CheckCallbacksRecorder.h" using namespace std; using namespace storage; BOOST_AUTO_TEST_CASE(probe) { set_logger(get_stdout_logger()); Environment environment(true, ProbeMode::READ_MOCKUP, TargetMode::DIRECT); environment.set_mockup_filename("lvm-errors1-mockup.xml"); Storage storage(environment); storage.probe(); vector<string> messages; CheckCallbacksRecorder check_callbacks_recorder(messages); const Devicegraph* probed = storage.get_probed(); probed->check(&check_callbacks_recorder); BOOST_CHECK_EQUAL(messages.size(), 2); BOOST_CHECK_EQUAL(messages[0], "Physical volume lv08LY-exMW-YKNh-GgX7-q0Ja-dW8H-lJ9Ejw is broken."); BOOST_CHECK_EQUAL(messages[1], "Physical volume u6c690-dm2j-IC7t-v8Lg-3Ylk-sUXY-BHsVmY is broken."); Devicegraph* staging = storage.get_staging(); staging->load("lvm-errors1-devicegraph.xml"); staging->check(); TsCmpDevicegraph cmp(*probed, *staging); BOOST_CHECK_MESSAGE(cmp.ok(), cmp); BOOST_CHECK_BITWISE_EQUAL(probed->used_features(), (uint64_t)(UF_LVM)); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qbluetoothsocket_p.h" #include "qbluetoothsocket.h" #include "symbian/utils_symbian_p.h" #include <QCoreApplication> #include <QDebug> #include <limits.h> #include <bt_sock.h> #include <es_sock.h> QTM_BEGIN_NAMESPACE Q_GLOBAL_STATIC(QSocketServerPrivate, getSocketServer) QBluetoothSocketPrivate::QBluetoothSocketPrivate() : socket(0) , socketType(QBluetoothSocket::UnknownSocketType) , state(QBluetoothSocket::UnconnectedState) , readNotifier(0) , connectWriteNotifier(0) , discoveryAgent(0) , iSocket(0) , iBlankSocket(0) , rxDescriptor(0, 0) , receiving(false) { } QBluetoothSocketPrivate::~QBluetoothSocketPrivate() { delete iBlankSocket; delete iSocket; } void QBluetoothSocketPrivate::connectToService(const QBluetoothAddress &address, quint16 port, QIODevice::OpenMode openMode) { Q_Q(QBluetoothSocket); TBTSockAddr a; a.SetBTAddr(TBTDevAddr(address.toUInt64())); a.SetPort(port); if (iSocket->Connect(a) == KErrNone) { q->setSocketState(QBluetoothSocket::ConnectingState); } else { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } bool QBluetoothSocketPrivate::ensureNativeSocket(QBluetoothSocket::SocketType type) { if (iSocket) { if (socketType == type) return true; else delete iSocket; } socketType = type; switch (type) { case QBluetoothSocket::L2capSocket: { TRAPD(err, iSocket = CBluetoothSocket::NewL(*this, getSocketServer()->socketServer, _L("L2CAP"))); Q_UNUSED(err); break; } case QBluetoothSocket::RfcommSocket: { TRAPD(err, iSocket = CBluetoothSocket::NewL(*this, getSocketServer()->socketServer, _L("RFCOMM"))); Q_UNUSED(err); break; } default: iSocket = 0; return false; } if (iSocket) return true; return false; } void QBluetoothSocketPrivate::ensureBlankNativeSocket() { if (iBlankSocket) { delete iBlankSocket; iBlankSocket = NULL; } TRAPD(err, iBlankSocket = CBluetoothSocket::NewL(*this, getSocketServer()->socketServer)); Q_UNUSED(err); } void QBluetoothSocketPrivate::startReceive() { if (receiving) return; Q_Q(QBluetoothSocket); if (!iSocket) { emit q->error(QBluetoothSocket::UnknownSocketError); return; } receiving = true; rxDescriptor.Set(reinterpret_cast<unsigned char *>(buffer.reserve(QBLUETOOTHDEVICE_BUFFERSIZE)), 0, QBLUETOOTHDEVICE_BUFFERSIZE); if (socketType == QBluetoothSocket::RfcommSocket) { if (iSocket->RecvOneOrMore(rxDescriptor, 0, rxLength) != KErrNone) { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } else if (socketType == QBluetoothSocket::L2capSocket) { if (iSocket->Recv(rxDescriptor, 0, rxLength) != KErrNone) { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } } void QBluetoothSocketPrivate::startServerSideReceive() { Q_Q(QBluetoothSocket); if (!iBlankSocket) { emit q->error(QBluetoothSocket::UnknownSocketError); return; } rxDescriptor.Set(reinterpret_cast<unsigned char *>(buffer.reserve(QBLUETOOTHDEVICE_BUFFERSIZE)), 0, QBLUETOOTHDEVICE_BUFFERSIZE); if (socketType == QBluetoothSocket::RfcommSocket) { if (iBlankSocket->RecvOneOrMore(rxDescriptor, 0, rxLength) != KErrNone) { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } else if (socketType == QBluetoothSocket::L2capSocket) { if (iBlankSocket->Recv(rxDescriptor, 0, rxLength) != KErrNone) { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } } void QBluetoothSocketPrivate::HandleAcceptCompleteL(TInt aErr) { qDebug() << __PRETTY_FUNCTION__; } void QBluetoothSocketPrivate::HandleActivateBasebandEventNotifierCompleteL(TInt aErr, TBTBasebandEventNotification &aEventNotification) { qDebug() << __PRETTY_FUNCTION__; } void QBluetoothSocketPrivate::HandleConnectCompleteL(TInt aErr) { Q_Q(QBluetoothSocket); if (aErr == KErrNone) { q->setSocketState(QBluetoothSocket::ConnectedState); emit q->connected(); startReceive(); } else { q->setSocketState(QBluetoothSocket::UnconnectedState); switch (aErr) { case KErrCouldNotConnect: socketError = QBluetoothSocket::ConnectionRefusedError; break; default: qDebug() << __PRETTY_FUNCTION__ << aErr; socketError = QBluetoothSocket::UnknownSocketError; } emit q->error(socketError); } } void QBluetoothSocketPrivate::HandleIoctlCompleteL(TInt aErr) { qDebug() << __PRETTY_FUNCTION__; } void QBluetoothSocketPrivate::HandleReceiveCompleteL(TInt aErr) { receiving = false; Q_Q(QBluetoothSocket); if (aErr == KErrNone) { if (rxDescriptor.Length() == 0) { emit q->readChannelFinished(); emit q->disconnected(); return; } buffer.chop(QBLUETOOTHDEVICE_BUFFERSIZE - (rxDescriptor.Length())); emit q->readyRead(); } else { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } void QBluetoothSocketPrivate::HandleSendCompleteL(TInt aErr) { Q_Q(QBluetoothSocket); if (aErr == KErrNone) { qint64 writeSize = txBuffer.length(); txBuffer.clear(); emit q->bytesWritten(writeSize); if (state == QBluetoothSocket::ClosingState) q->close(); } else { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } void QBluetoothSocketPrivate::HandleShutdownCompleteL(TInt aErr) { Q_Q(QBluetoothSocket); if (aErr == KErrNone) { q->setSocketState(QBluetoothSocket::UnconnectedState); emit q->disconnected(); } else { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } QSocketServerPrivate::QSocketServerPrivate() { /* connect to socket server */ TInt result = socketServer.Connect(); if (result != KErrNone) { qWarning("%s: RSocketServ.Connect() failed with error %d", __PRETTY_FUNCTION__, result); return; } } QSocketServerPrivate::~QSocketServerPrivate() { if (socketServer.Handle() != 0) socketServer.Close(); } QString QBluetoothSocketPrivate::localName() const { return localAddress().toString(); } QBluetoothAddress QBluetoothSocketPrivate::localAddress() const { TBTSockAddr address; iSocket->LocalName(address); return qTBTDevAddrToQBluetoothAddress(address.BTAddr()); } quint16 QBluetoothSocketPrivate::localPort() const { return iSocket->LocalPort(); } QString QBluetoothSocketPrivate::peerName() const { return peerAddress().toString(); } QBluetoothAddress QBluetoothSocketPrivate::peerAddress() const { TBTSockAddr address; iSocket->RemoteName(address); return qTBTDevAddrToQBluetoothAddress(address.BTAddr()); } quint16 QBluetoothSocketPrivate::peerPort() const { TBTSockAddr address; iSocket->RemoteName(address); return address.Port(); } void QBluetoothSocketPrivate::close() { if (state != QBluetoothSocket::ConnectedState && state != QBluetoothSocket::ListeningState) return; Q_Q(QBluetoothSocket); q->setSocketState(QBluetoothSocket::ClosingState); iSocket->Shutdown(RSocket::ENormal); } void QBluetoothSocketPrivate::abort() { iSocket->CancelWrite(); iSocket->Shutdown(RSocket::EImmediate); // force active object to run and shutdown socket. qApp->processEvents(QEventLoop::ExcludeUserInputEvents); } qint64 QBluetoothSocketPrivate::readData(char *data, qint64 maxSize) { qint64 size = buffer.read(data, maxSize); Q_Q(QBluetoothSocket); QMetaObject::invokeMethod(q, "_q_startReceive", Qt::QueuedConnection); return size; } qint64 QBluetoothSocketPrivate::writeData(const char *data, qint64 maxSize) { if (!txBuffer.isEmpty()) return 0; txBuffer = QByteArray(data, maxSize); if (iSocket->Send(TPtrC8(reinterpret_cast<const unsigned char *>(txBuffer.constData()), txBuffer.length()), 0) != KErrNone) { socketError = QBluetoothSocket::UnknownSocketError; Q_Q(QBluetoothSocket); emit q->error(socketError); } return maxSize; } void QBluetoothSocketPrivate::_q_readNotify() { } void QBluetoothSocketPrivate::_q_writeNotify() { } bool QBluetoothSocketPrivate::setSocketDescriptor(int socketDescriptor, QBluetoothSocket::SocketType socketType, QBluetoothSocket::SocketState socketState, QBluetoothSocket::OpenMode openMode) { return false; } void QBluetoothSocketPrivate::_q_startReceive() { startReceive(); } qint64 QBluetoothSocketPrivate::bytesAvailable() const { return rxDescriptor.Length(); } QTM_END_NAMESPACE <commit_msg>Symbian: QBluetoothSocketPrivate returns address as a name.<commit_after>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qbluetoothsocket_p.h" #include "qbluetoothsocket.h" #include "qbluetoothlocaldevice_p.h" #include "symbian/utils_symbian_p.h" #include <QCoreApplication> #include <QDebug> #include <limits.h> #include <bt_sock.h> #include <es_sock.h> QTM_BEGIN_NAMESPACE Q_GLOBAL_STATIC(QSocketServerPrivate, getSocketServer) QBluetoothSocketPrivate::QBluetoothSocketPrivate() : socket(0) , socketType(QBluetoothSocket::UnknownSocketType) , state(QBluetoothSocket::UnconnectedState) , readNotifier(0) , connectWriteNotifier(0) , discoveryAgent(0) , iSocket(0) , iBlankSocket(0) , rxDescriptor(0, 0) , receiving(false) { } QBluetoothSocketPrivate::~QBluetoothSocketPrivate() { delete iBlankSocket; delete iSocket; } void QBluetoothSocketPrivate::connectToService(const QBluetoothAddress &address, quint16 port, QIODevice::OpenMode openMode) { Q_Q(QBluetoothSocket); TBTSockAddr a; a.SetBTAddr(TBTDevAddr(address.toUInt64())); a.SetPort(port); if (iSocket->Connect(a) == KErrNone) { q->setSocketState(QBluetoothSocket::ConnectingState); } else { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } bool QBluetoothSocketPrivate::ensureNativeSocket(QBluetoothSocket::SocketType type) { if (iSocket) { if (socketType == type) return true; else delete iSocket; } socketType = type; switch (type) { case QBluetoothSocket::L2capSocket: { TRAPD(err, iSocket = CBluetoothSocket::NewL(*this, getSocketServer()->socketServer, _L("L2CAP"))); Q_UNUSED(err); break; } case QBluetoothSocket::RfcommSocket: { TRAPD(err, iSocket = CBluetoothSocket::NewL(*this, getSocketServer()->socketServer, _L("RFCOMM"))); Q_UNUSED(err); break; } default: iSocket = 0; return false; } if (iSocket) return true; return false; } void QBluetoothSocketPrivate::ensureBlankNativeSocket() { if (iBlankSocket) { delete iBlankSocket; iBlankSocket = NULL; } TRAPD(err, iBlankSocket = CBluetoothSocket::NewL(*this, getSocketServer()->socketServer)); Q_UNUSED(err); } void QBluetoothSocketPrivate::startReceive() { if (receiving) return; Q_Q(QBluetoothSocket); if (!iSocket) { emit q->error(QBluetoothSocket::UnknownSocketError); return; } receiving = true; rxDescriptor.Set(reinterpret_cast<unsigned char *>(buffer.reserve(QBLUETOOTHDEVICE_BUFFERSIZE)), 0, QBLUETOOTHDEVICE_BUFFERSIZE); if (socketType == QBluetoothSocket::RfcommSocket) { if (iSocket->RecvOneOrMore(rxDescriptor, 0, rxLength) != KErrNone) { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } else if (socketType == QBluetoothSocket::L2capSocket) { if (iSocket->Recv(rxDescriptor, 0, rxLength) != KErrNone) { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } } void QBluetoothSocketPrivate::startServerSideReceive() { Q_Q(QBluetoothSocket); if (!iBlankSocket) { emit q->error(QBluetoothSocket::UnknownSocketError); return; } rxDescriptor.Set(reinterpret_cast<unsigned char *>(buffer.reserve(QBLUETOOTHDEVICE_BUFFERSIZE)), 0, QBLUETOOTHDEVICE_BUFFERSIZE); if (socketType == QBluetoothSocket::RfcommSocket) { if (iBlankSocket->RecvOneOrMore(rxDescriptor, 0, rxLength) != KErrNone) { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } else if (socketType == QBluetoothSocket::L2capSocket) { if (iBlankSocket->Recv(rxDescriptor, 0, rxLength) != KErrNone) { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } } void QBluetoothSocketPrivate::HandleAcceptCompleteL(TInt aErr) { qDebug() << __PRETTY_FUNCTION__; } void QBluetoothSocketPrivate::HandleActivateBasebandEventNotifierCompleteL(TInt aErr, TBTBasebandEventNotification &aEventNotification) { qDebug() << __PRETTY_FUNCTION__; } void QBluetoothSocketPrivate::HandleConnectCompleteL(TInt aErr) { Q_Q(QBluetoothSocket); if (aErr == KErrNone) { q->setSocketState(QBluetoothSocket::ConnectedState); emit q->connected(); startReceive(); } else { q->setSocketState(QBluetoothSocket::UnconnectedState); switch (aErr) { case KErrCouldNotConnect: socketError = QBluetoothSocket::ConnectionRefusedError; break; default: qDebug() << __PRETTY_FUNCTION__ << aErr; socketError = QBluetoothSocket::UnknownSocketError; } emit q->error(socketError); } } void QBluetoothSocketPrivate::HandleIoctlCompleteL(TInt aErr) { qDebug() << __PRETTY_FUNCTION__; } void QBluetoothSocketPrivate::HandleReceiveCompleteL(TInt aErr) { receiving = false; Q_Q(QBluetoothSocket); if (aErr == KErrNone) { if (rxDescriptor.Length() == 0) { emit q->readChannelFinished(); emit q->disconnected(); return; } buffer.chop(QBLUETOOTHDEVICE_BUFFERSIZE - (rxDescriptor.Length())); emit q->readyRead(); } else { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } void QBluetoothSocketPrivate::HandleSendCompleteL(TInt aErr) { Q_Q(QBluetoothSocket); if (aErr == KErrNone) { qint64 writeSize = txBuffer.length(); txBuffer.clear(); emit q->bytesWritten(writeSize); if (state == QBluetoothSocket::ClosingState) q->close(); } else { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } void QBluetoothSocketPrivate::HandleShutdownCompleteL(TInt aErr) { Q_Q(QBluetoothSocket); if (aErr == KErrNone) { q->setSocketState(QBluetoothSocket::UnconnectedState); emit q->disconnected(); } else { socketError = QBluetoothSocket::UnknownSocketError; emit q->error(socketError); } } QSocketServerPrivate::QSocketServerPrivate() { /* connect to socket server */ TInt result = socketServer.Connect(); if (result != KErrNone) { qWarning("%s: RSocketServ.Connect() failed with error %d", __PRETTY_FUNCTION__, result); return; } } QSocketServerPrivate::~QSocketServerPrivate() { if (socketServer.Handle() != 0) socketServer.Close(); } QString QBluetoothSocketPrivate::localName() const { return QBluetoothLocalDevicePrivate::name(); } QBluetoothAddress QBluetoothSocketPrivate::localAddress() const { TBTSockAddr address; iSocket->LocalName(address); return qTBTDevAddrToQBluetoothAddress(address.BTAddr()); } quint16 QBluetoothSocketPrivate::localPort() const { return iSocket->LocalPort(); } QString QBluetoothSocketPrivate::peerName() const { return peerAddress().toString(); } QBluetoothAddress QBluetoothSocketPrivate::peerAddress() const { TBTSockAddr address; iSocket->RemoteName(address); return qTBTDevAddrToQBluetoothAddress(address.BTAddr()); } quint16 QBluetoothSocketPrivate::peerPort() const { TBTSockAddr address; iSocket->RemoteName(address); return address.Port(); } void QBluetoothSocketPrivate::close() { if (state != QBluetoothSocket::ConnectedState && state != QBluetoothSocket::ListeningState) return; Q_Q(QBluetoothSocket); q->setSocketState(QBluetoothSocket::ClosingState); iSocket->Shutdown(RSocket::ENormal); } void QBluetoothSocketPrivate::abort() { iSocket->CancelWrite(); iSocket->Shutdown(RSocket::EImmediate); // force active object to run and shutdown socket. qApp->processEvents(QEventLoop::ExcludeUserInputEvents); } qint64 QBluetoothSocketPrivate::readData(char *data, qint64 maxSize) { qint64 size = buffer.read(data, maxSize); Q_Q(QBluetoothSocket); QMetaObject::invokeMethod(q, "_q_startReceive", Qt::QueuedConnection); return size; } qint64 QBluetoothSocketPrivate::writeData(const char *data, qint64 maxSize) { if (!txBuffer.isEmpty()) return 0; txBuffer = QByteArray(data, maxSize); if (iSocket->Send(TPtrC8(reinterpret_cast<const unsigned char *>(txBuffer.constData()), txBuffer.length()), 0) != KErrNone) { socketError = QBluetoothSocket::UnknownSocketError; Q_Q(QBluetoothSocket); emit q->error(socketError); } return maxSize; } void QBluetoothSocketPrivate::_q_readNotify() { } void QBluetoothSocketPrivate::_q_writeNotify() { } bool QBluetoothSocketPrivate::setSocketDescriptor(int socketDescriptor, QBluetoothSocket::SocketType socketType, QBluetoothSocket::SocketState socketState, QBluetoothSocket::OpenMode openMode) { return false; } void QBluetoothSocketPrivate::_q_startReceive() { startReceive(); } qint64 QBluetoothSocketPrivate::bytesAvailable() const { return rxDescriptor.Length(); } QTM_END_NAMESPACE <|endoftext|>
<commit_before>/* * SessionRequest.hpp * * Copyright (C) 2009-16 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef SESSION_REQUEST_HPP #define SESSION_REQUEST_HPP #include <core/Error.hpp> #include <core/system/Environment.hpp> #include <session/http/SessionRequest.hpp> #if !defined(_WIN32) #include <core/http/TcpIpBlockingClient.hpp> #include <core/http/LocalStreamBlockingClient.hpp> #else #include <core/http/NamedPipeBlockingClient.hpp> #endif #if !defined(_WIN32) #include <session/SessionLocalStreams.hpp> #endif #include <session/SessionConstants.hpp> namespace rstudio { namespace session { namespace http { inline core::Error sendSessionRequest(const std::string& uri, const std::string& body, core::http::Response* pResponse) { // build request core::http::Request request; request.setMethod("POST"); request.setUri(uri); request.setHeader("Accept", "*/*"); request.setHeader("Connection", "close"); request.setBody(body); std::cerr << "request: " << request << std::endl; #ifdef _WIN32 // get local peer std::string pipeName = core::system::getenv("RS_LOCAL_PEER"); pRequest->setHeader("X-Shared-Secret", core::system::getenv("RS_SHARED_SECRET")); return core::http::sendRequest(pipeName, *pRequest, ConnectionRetryProfile( boost::posix_time::seconds(10), boost::posix_time::milliseconds(50)), pResponse); #else std::string tcpipPort = core::system::getenv(kRSessionStandalonePortNumber); if (!tcpipPort.empty()) { return core::http::sendRequest("127.0.0.1", tcpipPort, request, pResponse); } else { // determine stream path std::string stream = core::system::getenv(kRStudioSessionStream); core::FilePath streamPath = session::local_streams::streamPath(stream); return core::http::sendRequest(streamPath, request, pResponse); } #endif return core::Success(); } } // namespace http } // namespace session } // namespace rstudio #endif <commit_msg>remove debug log & add comments for session request<commit_after>/* * SessionRequest.hpp * * Copyright (C) 2009-16 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef SESSION_REQUEST_HPP #define SESSION_REQUEST_HPP #include <core/Error.hpp> #include <core/system/Environment.hpp> #include <session/http/SessionRequest.hpp> #if !defined(_WIN32) #include <core/http/TcpIpBlockingClient.hpp> #include <core/http/LocalStreamBlockingClient.hpp> #else #include <core/http/NamedPipeBlockingClient.hpp> #endif #if !defined(_WIN32) #include <session/SessionLocalStreams.hpp> #endif #include <session/SessionConstants.hpp> namespace rstudio { namespace session { namespace http { // this function sends an request directly to the session; it's inlined so that // it can be used both from the postback executable (which does not link with // rsession) and the session itself inline core::Error sendSessionRequest(const std::string& uri, const std::string& body, core::http::Response* pResponse) { // build request core::http::Request request; request.setMethod("POST"); request.setUri(uri); request.setHeader("Accept", "*/*"); request.setHeader("Connection", "close"); request.setBody(body); #ifdef _WIN32 // get local peer std::string pipeName = core::system::getenv("RS_LOCAL_PEER"); pRequest->setHeader("X-Shared-Secret", core::system::getenv("RS_SHARED_SECRET")); return core::http::sendRequest(pipeName, *pRequest, ConnectionRetryProfile( boost::posix_time::seconds(10), boost::posix_time::milliseconds(50)), pResponse); #else std::string tcpipPort = core::system::getenv(kRSessionStandalonePortNumber); if (!tcpipPort.empty()) { return core::http::sendRequest("127.0.0.1", tcpipPort, request, pResponse); } else { // determine stream path std::string stream = core::system::getenv(kRStudioSessionStream); core::FilePath streamPath = session::local_streams::streamPath(stream); return core::http::sendRequest(streamPath, request, pResponse); } #endif return core::Success(); } } // namespace http } // namespace session } // namespace rstudio #endif <|endoftext|>
<commit_before>// // NSolver_Forceintegrate_force.cpp // NSolver // // Created by 乔磊 on 15/5/10. // Copyright (c) 2015年 乔磊. All rights reserved. // #include <NSolver/solver/NSolver.h> namespace NSFEMSolver { using namespace dealii; template <int dim> void NSolver<dim>::integrate_force (WallForce &wall_force) const { const UpdateFlags face_update_flags = update_values | update_quadrature_points | update_JxW_values | update_normal_vectors; FEFaceValues<dim> fe_v_face (*mapping_ptr, fe, face_quadrature,face_update_flags); wall_force.clear(); std::vector<Vector<double> > solution_values; typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(), endc = dof_handler.end(); unsigned int cell_index (0); for (; cell!=endc; ++cell, ++cell_index) if (cell->is_locally_owned()) for (unsigned int face_no=0; face_no<GeometryInfo<dim>::faces_per_cell; ++face_no) if (cell->at_boundary (face_no)) if (parameters->sum_force[cell->face (face_no)->boundary_id()]) { fe_v_face.reinit (cell, face_no); unsigned int const n_q_points = fe_v_face.n_quadrature_points; solution_values.resize (n_q_points, Vector<double> (EquationComponents<dim>::n_components)); fe_v_face.get_function_values (current_solution, solution_values); for (unsigned int q=0; q<n_q_points; ++q) { Tensor<1,dim> const wall_norm = fe_v_face.normal_vector (q); Point<dim> const wall_position = fe_v_face.quadrature_point (q); double f_ds[3]; double moment_arm[3] = {0.,0.,0.}; for (unsigned int id=0; id<dim; ++id) { f_ds[id] = solution_values[q][EquationComponents<dim>::pressure_component] * wall_norm[id] * fe_v_face.JxW (q); wall_force.force[id] += f_ds[id]; moment_arm[id] = wall_position[id] - parameters->moment_center[id]; } { unsigned int const x=0; unsigned int const y=1; unsigned int const z=2; wall_force.moment[x] -= f_ds[y]*moment_arm[z]; wall_force.moment[x] += f_ds[z]*moment_arm[y]; wall_force.moment[y] -= f_ds[z]*moment_arm[x]; wall_force.moment[y] += f_ds[x]*moment_arm[z]; wall_force.moment[z] -= f_ds[x]*moment_arm[y]; wall_force.moment[z] += f_ds[y]*moment_arm[x]; } } } wall_force.mpi_sum (mpi_communicator); // Turn force into force coefficient double const force_to_coeff = 0.5 * parameters->Mach * parameters->Mach * parameters->reference_area; wall_force.force[0] /= force_to_coeff; wall_force.force[1] /= force_to_coeff; wall_force.force[2] /= force_to_coeff; // Roll moment coefficient wall_force.moment[0] /= force_to_coeff; wall_force.moment[0] /= parameters->reference_span; // Yaw mement coefficient wall_force.moment[1] /= force_to_coeff; wall_force.moment[1] /= parameters->reference_span; // Pitch momernt coefficient wall_force.moment[2] /= force_to_coeff; wall_force.moment[2] /= parameters->reference_chord; // Project force coefficient to lift and drag component double const sin_aoa = std::sin (parameters->angle_of_attack); double const cos_aoa = std::cos (parameters->angle_of_attack); wall_force.lift = cos_aoa*wall_force.force[1] - sin_aoa*wall_force.force[0]; wall_force.drag = cos_aoa*wall_force.force[0] + sin_aoa*wall_force.force[1]; return; } #include "NSolver.inst" } <commit_msg>output solution on quadrature points on force boundary<commit_after>// // NSolver_Forceintegrate_force.cpp // NSolver // // Created by 乔磊 on 15/5/10. // Copyright (c) 2015年 乔磊. All rights reserved. // #include <NSolver/solver/NSolver.h> namespace NSFEMSolver { using namespace dealii; template <int dim> void NSolver<dim>::integrate_force (WallForce &wall_force) const { const UpdateFlags face_update_flags = update_values | update_quadrature_points | update_JxW_values | update_normal_vectors; FEFaceValues<dim> fe_v_face (*mapping_ptr, fe, face_quadrature,face_update_flags); wall_force.clear(); const std::string file_name = "boundaryData.slot-" + Utilities::int_to_string (myid,4) + ".raw"; std::ofstream boundary_data_out (file_name.c_str()); boundary_data_out << std::setw (13) << parameters->Mach << std::endl; std::vector<Vector<double> > solution_values; typename DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active(), endc = dof_handler.end(); unsigned int cell_index (0); for (; cell!=endc; ++cell, ++cell_index) if (cell->is_locally_owned()) for (unsigned int face_no=0; face_no<GeometryInfo<dim>::faces_per_cell; ++face_no) if (cell->at_boundary (face_no)) if (parameters->sum_force[cell->face (face_no)->boundary_id()]) { fe_v_face.reinit (cell, face_no); unsigned int const n_q_points = fe_v_face.n_quadrature_points; solution_values.resize (n_q_points, Vector<double> (EquationComponents<dim>::n_components)); fe_v_face.get_function_values (current_solution, solution_values); for (unsigned int q=0; q<n_q_points; ++q) { Tensor<1,dim> const wall_norm = fe_v_face.normal_vector (q); Point<dim> const wall_position = fe_v_face.quadrature_point (q); double f_ds[3]; double moment_arm[3] = {0.,0.,0.}; for (unsigned int id=0; id<dim; ++id) { f_ds[id] = solution_values[q][EquationComponents<dim>::pressure_component] * wall_norm[id] * fe_v_face.JxW (q); wall_force.force[id] += f_ds[id]; moment_arm[id] = wall_position[id] - parameters->moment_center[id]; boundary_data_out << std::setw (13) << wall_position[id] << ' '; } for (unsigned int ic=0; ic<EquationComponents<dim>::n_components; ++ic) { boundary_data_out << std::setw (13) << solution_values[q][ic] << ' '; } { unsigned int const x=0; unsigned int const y=1; unsigned int const z=2; wall_force.moment[x] -= f_ds[y]*moment_arm[z]; wall_force.moment[x] += f_ds[z]*moment_arm[y]; wall_force.moment[y] -= f_ds[z]*moment_arm[x]; wall_force.moment[y] += f_ds[x]*moment_arm[z]; wall_force.moment[z] -= f_ds[x]*moment_arm[y]; wall_force.moment[z] += f_ds[y]*moment_arm[x]; } boundary_data_out << std::endl; } } wall_force.mpi_sum (mpi_communicator); // Turn force into force coefficient double const force_to_coeff = 0.5 * parameters->Mach * parameters->Mach * parameters->reference_area; wall_force.force[0] /= force_to_coeff; wall_force.force[1] /= force_to_coeff; wall_force.force[2] /= force_to_coeff; // Roll moment coefficient wall_force.moment[0] /= force_to_coeff; wall_force.moment[0] /= parameters->reference_span; // Yaw mement coefficient wall_force.moment[1] /= force_to_coeff; wall_force.moment[1] /= parameters->reference_span; // Pitch momernt coefficient wall_force.moment[2] /= force_to_coeff; wall_force.moment[2] /= parameters->reference_chord; // Project force coefficient to lift and drag component double const sin_aoa = std::sin (parameters->angle_of_attack); double const cos_aoa = std::cos (parameters->angle_of_attack); wall_force.lift = cos_aoa*wall_force.force[1] - sin_aoa*wall_force.force[0]; wall_force.drag = cos_aoa*wall_force.force[0] + sin_aoa*wall_force.force[1]; boundary_data_out.close(); return; } #include "NSolver.inst" } <|endoftext|>
<commit_before>#include "BodymovinParser.h" #include "FilepathHelper.h" #include <fstream> #include <assert.h> #include <string.h> namespace gum { BodymovinParser::BodymovinParser() : m_frame_rate(0) , m_width(0) , m_height(0) , m_start_frame(0) , m_end_frame(0) { } void BodymovinParser::Parse(const Json::Value& val, const std::string& dir) { Clear(); ParseHeader(val); ParseAssets(val["assets"], dir); ParseLayers(val["layers"], m_layers); } void BodymovinParser::Clear() { m_assets.clear(); m_layers.clear(); } void BodymovinParser::ParseHeader(const Json::Value& val) { m_version = val["v"].asString(); m_name = val["nm"].asString(); m_frame_rate = val["fr"].asInt(); m_width = val["w"].asInt(); m_height = val["h"].asInt(); m_start_frame = val["ip"].asInt(); m_end_frame = val["op"].asInt(); } void BodymovinParser::ParseAssets(const Json::Value& val, const std::string& dir) { for (int i = 0, n = val.size(); i < n; ++i) { const Json::Value& cval = val[i]; Asset a; a.id = cval["id"].asString(); if (cval.isMember("layers")) { ParseLayers(cval["layers"], a.layers); } else { a.w = cval["w"].asInt(); a.h = cval["h"].asInt(); a.filepath = dir + "\\" + cval["u"].asString() + cval["p"].asString(); } m_assets.push_back(a); } } void BodymovinParser::ParseLayers(const Json::Value& val, std::vector<Layer>& layers) { if (val.size() == 0) { return; } layers.reserve(val.size()); for (int i = val.size() - 1; i >= 0; --i) { Layer layer; if (layer.Load(val[i])) { layers.push_back(layer); } } } /************************************************************************/ /* class BodymovinParser::FloatVal::Float3 */ /************************************************************************/ BodymovinParser::FloatVal::Float3::Float3() { memset(data, 0, sizeof(data)); } BodymovinParser::FloatVal::Float3::Float3(const Json::Value& val) { memset(data, 0, sizeof(data)); if (val.isArray()) { assert(val.size() <= 3); int n = std::min(3, static_cast<int>(val.size())); for (int i = 0; i < n; ++i) { data[i] = val[i].asDouble(); } } else { data[0] = val.asDouble(); } } bool BodymovinParser::FloatVal::Float3::operator == (const Float3& f) const { for (int i = 0; i < 3; ++i) { if (fabs(data[i] - f.data[i]) > FLT_EPSILON) { return false; } } return true; } /************************************************************************/ /* class BodymovinParser::FloatVal */ /************************************************************************/ void BodymovinParser::FloatVal::Load(const Json::Value& val) { if (val.isMember("x") && val["x"].isString()) { expression = val["x"].asString(); } bool anim = val["a"].asInt() == 1; if (!anim) { KeyFrame kf; kf.s_val = Float3(val["k"]); frames.push_back(kf); return; } int n = val["k"].size(); frames.resize(n); for (int i = 0; i < n; ++i) { const Json::Value& src = val["k"][i]; KeyFrame& dst = frames[i]; dst.frame = src["t"].asInt(); if (src.isMember("s")) { dst.s_val = Float3(src["s"]); } if (src.isMember("e")) { dst.e_val = Float3(src["e"]); if (i != n - 1) { frames[i + 1].s_val = dst.e_val; } } if (src.isMember("i")) { assert(src["i"].isMember("x") && src["i"].isMember("y")); dst.ix = Float3(src["i"]["x"]); dst.iy = Float3(src["i"]["y"]); } if (src.isMember("o")) { assert(src["o"].isMember("x") && src["o"].isMember("y")); dst.ox = Float3(src["o"]["x"]); dst.oy = Float3(src["o"]["y"]); } if (src.isMember("ti")) { dst.ti = Float3(src["ti"]); } if (src.isMember("to")) { dst.to = Float3(src["to"]); } } #ifndef NDEBUG if (n > 1) { for (int i = 0; i < n - 1; ++i) { assert(frames[i].e_val == frames[i + 1].s_val); } } #endif // NDEBUG } /************************************************************************/ /* class BodymovinParser::Transform */ /************************************************************************/ BodymovinParser::Transform::Transform() { } void BodymovinParser::Transform::Load(const Json::Value& val) { if (val.isMember("a")) { anchor.Load(val["a"]); } if (val.isMember("o")) { opacity.Load(val["o"]); } if (val.isMember("p")) { position.Load(val["p"]); } if (val.isMember("r")) { rotate.Load(val["r"]); } if (val.isMember("s")) { scale.Load(val["s"]); } } /************************************************************************/ /* class BodymovinParser::Layer */ /************************************************************************/ BodymovinParser::Layer::Layer() { } bool BodymovinParser::Layer::Load(const Json::Value& val) { name = val["nm"].asString(); ref_id = val["refId"].asString(); layer_id = val["ind"].asInt(); layer_type = val["ty"].asInt(); switch (layer_type) { case LAYER_PRE_COMP: comp_width = val["w"].asInt(); comp_height = val["h"].asInt(); break; case LAYER_SOLID: // todo: not support mask now if (val.isMember("hasMask") && val["hasMask"].asBool()) { return false; } solid_width = val["sw"].asInt(); solid_height = val["sh"].asInt(); solid_color = val["sc"].asString(); break; } if (val.isMember("parent")) { parent_id = val["parent"].asInt(); } else { parent_id = -1; } cl = val["cl"].asString(); float time_stretch = 1; if (val.isMember("sr")) { time_stretch = val["sr"].asDouble(); } in_frame = val["ip"].asDouble() / time_stretch; out_frame = val["op"].asDouble() / time_stretch; start_frame = val["st"].asInt(); auto_ori = val["ao"].asInt(); blend_mode = val["bm"].asInt(); trans.Load(val["ks"]); return true; } }<commit_msg>fix compile<commit_after>#include "BodymovinParser.h" #include "FilepathHelper.h" #include <fstream> #include <algorithm> #include <assert.h> #include <string.h> namespace gum { BodymovinParser::BodymovinParser() : m_frame_rate(0) , m_width(0) , m_height(0) , m_start_frame(0) , m_end_frame(0) { } void BodymovinParser::Parse(const Json::Value& val, const std::string& dir) { Clear(); ParseHeader(val); ParseAssets(val["assets"], dir); ParseLayers(val["layers"], m_layers); } void BodymovinParser::Clear() { m_assets.clear(); m_layers.clear(); } void BodymovinParser::ParseHeader(const Json::Value& val) { m_version = val["v"].asString(); m_name = val["nm"].asString(); m_frame_rate = val["fr"].asInt(); m_width = val["w"].asInt(); m_height = val["h"].asInt(); m_start_frame = val["ip"].asInt(); m_end_frame = val["op"].asInt(); } void BodymovinParser::ParseAssets(const Json::Value& val, const std::string& dir) { for (int i = 0, n = val.size(); i < n; ++i) { const Json::Value& cval = val[i]; Asset a; a.id = cval["id"].asString(); if (cval.isMember("layers")) { ParseLayers(cval["layers"], a.layers); } else { a.w = cval["w"].asInt(); a.h = cval["h"].asInt(); a.filepath = dir + "\\" + cval["u"].asString() + cval["p"].asString(); } m_assets.push_back(a); } } void BodymovinParser::ParseLayers(const Json::Value& val, std::vector<Layer>& layers) { if (val.size() == 0) { return; } layers.reserve(val.size()); for (int i = val.size() - 1; i >= 0; --i) { Layer layer; if (layer.Load(val[i])) { layers.push_back(layer); } } } /************************************************************************/ /* class BodymovinParser::FloatVal::Float3 */ /************************************************************************/ BodymovinParser::FloatVal::Float3::Float3() { memset(data, 0, sizeof(data)); } BodymovinParser::FloatVal::Float3::Float3(const Json::Value& val) { memset(data, 0, sizeof(data)); if (val.isArray()) { assert(val.size() <= 3); int n = std::min(3, static_cast<int>(val.size())); for (int i = 0; i < n; ++i) { data[i] = val[i].asDouble(); } } else { data[0] = val.asDouble(); } } bool BodymovinParser::FloatVal::Float3::operator == (const Float3& f) const { for (int i = 0; i < 3; ++i) { if (fabs(data[i] - f.data[i]) > FLT_EPSILON) { return false; } } return true; } /************************************************************************/ /* class BodymovinParser::FloatVal */ /************************************************************************/ void BodymovinParser::FloatVal::Load(const Json::Value& val) { if (val.isMember("x") && val["x"].isString()) { expression = val["x"].asString(); } bool anim = val["a"].asInt() == 1; if (!anim) { KeyFrame kf; kf.s_val = Float3(val["k"]); frames.push_back(kf); return; } int n = val["k"].size(); frames.resize(n); for (int i = 0; i < n; ++i) { const Json::Value& src = val["k"][i]; KeyFrame& dst = frames[i]; dst.frame = src["t"].asInt(); if (src.isMember("s")) { dst.s_val = Float3(src["s"]); } if (src.isMember("e")) { dst.e_val = Float3(src["e"]); if (i != n - 1) { frames[i + 1].s_val = dst.e_val; } } if (src.isMember("i")) { assert(src["i"].isMember("x") && src["i"].isMember("y")); dst.ix = Float3(src["i"]["x"]); dst.iy = Float3(src["i"]["y"]); } if (src.isMember("o")) { assert(src["o"].isMember("x") && src["o"].isMember("y")); dst.ox = Float3(src["o"]["x"]); dst.oy = Float3(src["o"]["y"]); } if (src.isMember("ti")) { dst.ti = Float3(src["ti"]); } if (src.isMember("to")) { dst.to = Float3(src["to"]); } } #ifndef NDEBUG if (n > 1) { for (int i = 0; i < n - 1; ++i) { assert(frames[i].e_val == frames[i + 1].s_val); } } #endif // NDEBUG } /************************************************************************/ /* class BodymovinParser::Transform */ /************************************************************************/ BodymovinParser::Transform::Transform() { } void BodymovinParser::Transform::Load(const Json::Value& val) { if (val.isMember("a")) { anchor.Load(val["a"]); } if (val.isMember("o")) { opacity.Load(val["o"]); } if (val.isMember("p")) { position.Load(val["p"]); } if (val.isMember("r")) { rotate.Load(val["r"]); } if (val.isMember("s")) { scale.Load(val["s"]); } } /************************************************************************/ /* class BodymovinParser::Layer */ /************************************************************************/ BodymovinParser::Layer::Layer() { } bool BodymovinParser::Layer::Load(const Json::Value& val) { name = val["nm"].asString(); ref_id = val["refId"].asString(); layer_id = val["ind"].asInt(); layer_type = val["ty"].asInt(); switch (layer_type) { case LAYER_PRE_COMP: comp_width = val["w"].asInt(); comp_height = val["h"].asInt(); break; case LAYER_SOLID: // todo: not support mask now if (val.isMember("hasMask") && val["hasMask"].asBool()) { return false; } solid_width = val["sw"].asInt(); solid_height = val["sh"].asInt(); solid_color = val["sc"].asString(); break; } if (val.isMember("parent")) { parent_id = val["parent"].asInt(); } else { parent_id = -1; } cl = val["cl"].asString(); float time_stretch = 1; if (val.isMember("sr")) { time_stretch = val["sr"].asDouble(); } in_frame = val["ip"].asDouble() / time_stretch; out_frame = val["op"].asDouble() / time_stretch; start_frame = val["st"].asInt(); auto_ori = val["ao"].asInt(); blend_mode = val["bm"].asInt(); trans.Load(val["ks"]); return true; } }<|endoftext|>
<commit_before>/* Copyright (C) 2014-2017 Alexandr Akulich <akulichalexander@gmail.com> This file is a part of TelegramQt library. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. */ #ifndef CRYPTO_RSA_HPP #define CRYPTO_RSA_HPP #include <QByteArray> struct SRsaKey { QByteArray key; QByteArray exp; quint64 fingersprint; SRsaKey(const QByteArray &initialKey = QByteArray(), const QByteArray &initialExp = QByteArray(), const quint64 initialFingersprint = 0) : key(initialKey), exp(initialExp), fingersprint(initialFingersprint) { } SRsaKey &operator=(const SRsaKey &anotherKey) { key = anotherKey.key; exp = anotherKey.exp; fingersprint = anotherKey.fingersprint; return *this; } }; #endif // CRYPTO_RSA_HPP <commit_msg>Remove unused file<commit_after><|endoftext|>
<commit_before>// Programmed by jasonfish4 #include "stdafx.h" #include "exceptiondispatcher.h" #include "rvdbg.h" void dispatcher::raise_instr_av(std::uint8_t* ptr, std::uint8_t save, bool on) { std::uint32_t old_protect; VirtualProtect(ptr, 1, static_cast<unsigned long>(dbg_redef::page_protection::page_xrw), reinterpret_cast<unsigned long*>(&old_protect)); *const_cast<std::uint8_t*>(ptr) = on ? 0xFF : save; VirtualProtect(ptr, 1, old_protect, reinterpret_cast<unsigned long*>(&old_protect)); } void dispatcher::raise_page_av(std::uint8_t* ptr, std::uint32_t save, bool on) { std::uint32_t old_protect; on ? VirtualProtect(ptr, 1, static_cast<unsigned long>(dbg_redef::page_protection::page_ro), reinterpret_cast<unsigned long*>(&old_protect)) : VirtualProtect(ptr, 1, save, reinterpret_cast<unsigned long*>(&old_protect)); } void dispatcher::raise_breakpoint_excpt(std::uint8_t* ptr, std::uint8_t save, bool on) { std::uint32_t old_protect; VirtualProtect(ptr, 1, static_cast<unsigned long>(dbg_redef::page_protection::page_xrw), reinterpret_cast<unsigned long*>(&old_protect)); *const_cast<std::uint8_t*>(ptr) = on ? 0xCC : save; VirtualProtect(ptr, 1, old_protect, reinterpret_cast<unsigned long*>(&old_protect)); } void dispatcher::raise_priv_code_excpt(std::uint8_t* ptr, std::uint8_t save, bool on) { std::uint32_t old_protect; VirtualProtect(ptr, 1, static_cast<unsigned long>(dbg_redef::page_protection::page_xrw), reinterpret_cast<unsigned long*>(&old_protect)); *const_cast<std::uint8_t*>(ptr) = on ? 0xF4 : save; VirtualProtect(ptr, 1, old_protect, reinterpret_cast<unsigned long*>(&old_protect)); } void* dispatcher::handle_exception(dispatcher::pool_sect segment, std::string module_name, bool b_module) { segment.use_module = b_module; switch (segment.dbg_exception_code) { case static_cast<std::uint32_t>(dbg_redef::exception_status_code::access_violation): dispatcher::raise_instr_av(reinterpret_cast<std::uint8_t*>(segment.dbg_exception_address), segment.save_code, false); if (segment.use_module) { return reinterpret_cast<void*>(reinterpret_cast<std::uint32_t>(GetModuleHandleA(module_name.c_str())) + segment.dbg_exception_offset); } return reinterpret_cast<void*>(segment.dbg_exception_address); case static_cast<std::uint32_t>(dbg_redef::exception_status_code::breakpoint_exception): dispatcher::raise_breakpoint_excpt(reinterpret_cast<std::uint8_t*>(segment.dbg_exception_address), segment.save_code, false); if (segment.use_module) { return reinterpret_cast<void*>(reinterpret_cast<std::uint32_t>(GetModuleHandleA(module_name.c_str())) + segment.dbg_exception_offset); } return reinterpret_cast<void*>(segment.dbg_exception_address); case static_cast<std::uint32_t>(dbg_redef::exception_status_code::privileged_instruction): dispatcher::raise_priv_code_excpt(reinterpret_cast<std::uint8_t*>(segment.dbg_exception_address), segment.save_code, false); if (segment.use_module) { return reinterpret_cast<void*>(reinterpret_cast<std::uint32_t>(GetModuleHandleA(module_name.c_str())) + segment.dbg_exception_offset); } return reinterpret_cast<void*>(segment.dbg_exception_address); } return nullptr; } std::size_t dispatcher::check_sector(std::array<dispatcher::pool_sect, 128>& sector) { for (std::size_t iterator = 0; iterator < sector.size(); iterator++) { if (sector[iterator].used == false) { return iterator; } } return (sector.size() + 1); } std::size_t dispatcher::search_sector(std::array<dispatcher::pool_sect, 128>& sector, std::uint32_t address) { for (std::size_t iterator = 0; iterator < sector.size(); iterator++) { if (sector[iterator].used == true && sector[iterator].is_aeh_present == false && sector[iterator].dbg_exception_address == address) { return iterator; } } return (sector.size() + 1); } void dispatcher::unlock_sector(std::array<dispatcher::pool_sect, 128>& sector, std::size_t index) { dispatcher::pool_sect filled_segment = { 0 }; std::fill_n(stdext::checked_array_iterator<dispatcher::pool_sect*>(&sector[index], sizeof(dispatcher::pool_sect)), sizeof(dispatcher::pool_sect), filled_segment); } void dispatcher::lock_sector(std::array<dispatcher::pool_sect, 128>& sector, std::size_t index) { sector[index].used = true; sector[index].is_aeh_present = false; } void dispatcher::add_exception(std::array<dispatcher::pool_sect, 128>& sector, std::size_t index, dispatcher::exception_type type, std::uint32_t dbg_exception_address) { sector[index].dbg_exception_address = dbg_exception_address; sector[index].save_code = *reinterpret_cast<std::uint32_t*>(dbg_exception_address); sector[index].dbg_exception_type = type; sector[index].index = index; dispatcher::lock_sector(sector, index); switch (type) { case dispatcher::exception_type::immediate_exception: dispatcher::raise_priv_code_excpt(reinterpret_cast<std::uint8_t*>(sector[index].dbg_exception_address), 0, true); return; case dispatcher::exception_type::page_exception: dispatcher::raise_page_av(reinterpret_cast<std::uint8_t*>(sector[index].dbg_exception_address), 0, true); return; } } <commit_msg>Update exceptiondispatcher.cpp<commit_after>// Programmed by jasonfish4 #include "stdafx.h" #include "exceptiondispatcher.h" #include "rvdbg.h" void dispatcher::raise_instr_av(std::uint8_t* ptr, std::uint8_t save, bool on) { std::uint32_t old_protect; VirtualProtect(ptr, 1, static_cast<unsigned long>(dbg_redef::page_protection::page_rwx), reinterpret_cast<unsigned long*>(&old_protect)); *const_cast<std::uint8_t*>(ptr) = on ? 0xFF : save; VirtualProtect(ptr, 1, old_protect, reinterpret_cast<unsigned long*>(&old_protect)); } void dispatcher::raise_page_av(std::uint8_t* ptr, std::uint32_t save, bool on) { std::uint32_t old_protect; on ? VirtualProtect(ptr, 1, static_cast<unsigned long>(dbg_redef::page_protection::page_ro), reinterpret_cast<unsigned long*>(&old_protect)) : VirtualProtect(ptr, 1, save, reinterpret_cast<unsigned long*>(&old_protect)); } void dispatcher::raise_breakpoint_excpt(std::uint8_t* ptr, std::uint8_t save, bool on) { std::uint32_t old_protect; VirtualProtect(ptr, 1, static_cast<unsigned long>(dbg_redef::page_protection::page_rwx), reinterpret_cast<unsigned long*>(&old_protect)); *const_cast<std::uint8_t*>(ptr) = on ? 0xCC : save; VirtualProtect(ptr, 1, old_protect, reinterpret_cast<unsigned long*>(&old_protect)); } void dispatcher::raise_priv_code_excpt(std::uint8_t* ptr, std::uint8_t save, bool on) { std::uint32_t old_protect; VirtualProtect(ptr, 1, static_cast<unsigned long>(dbg_redef::page_protection::page_rwx), reinterpret_cast<unsigned long*>(&old_protect)); *const_cast<std::uint8_t*>(ptr) = on ? 0xF4 : save; VirtualProtect(ptr, 1, old_protect, reinterpret_cast<unsigned long*>(&old_protect)); } void* dispatcher::handle_exception(dispatcher::pool_sect& segment, std::string& module_name, bool b_module) { segment.use_module = b_module; switch (segment.dbg_exception_code) { case static_cast<std::uint32_t>(dbg_redef::exception_status_code::access_violation): dispatcher::raise_instr_av(reinterpret_cast<std::uint8_t*>(segment.dbg_exception_address), segment.save_code, false); if (segment.use_module) { return reinterpret_cast<void*>(reinterpret_cast<std::uint32_t>(GetModuleHandleA(module_name.c_str())) + segment.dbg_exception_offset); } return reinterpret_cast<void*>(segment.dbg_exception_address); case static_cast<std::uint32_t>(dbg_redef::exception_status_code::breakpoint_exception): dispatcher::raise_breakpoint_excpt(reinterpret_cast<std::uint8_t*>(segment.dbg_exception_address), segment.save_code, false); if (segment.use_module) { return reinterpret_cast<void*>(reinterpret_cast<std::uint32_t>(GetModuleHandleA(module_name.c_str())) + segment.dbg_exception_offset); } return reinterpret_cast<void*>(segment.dbg_exception_address); case static_cast<std::uint32_t>(dbg_redef::exception_status_code::privileged_instruction) : dispatcher::raise_priv_code_excpt(reinterpret_cast<std::uint8_t*>(segment.dbg_exception_address), segment.save_code, false); if (segment.use_module) { return reinterpret_cast<void*>(reinterpret_cast<std::uint32_t>(GetModuleHandleA(module_name.c_str())) + segment.dbg_exception_offset); } return reinterpret_cast<void*>(segment.dbg_exception_address); } return nullptr; } std::size_t dispatcher::check_sector(std::array<dispatcher::pool_sect, 128>& sector, std::uint32_t address) { for (std::size_t iterator = 0; iterator < sector.size(); iterator++) { if (sector[iterator].dbg_exception_address == address) { return (sector.size() + 1); } } for (std::size_t iterator = 0; iterator < sector.size(); iterator++) { if (sector[iterator].used == false) { return iterator; } } return (sector.size() + 1); } std::size_t dispatcher::search_sector(std::array<dispatcher::pool_sect, 128>& sector, std::uint32_t address) { for (std::size_t iterator = 0; iterator < sector.size(); iterator++) { if (sector[iterator].used == true && sector[iterator].is_aeh_present == false && sector[iterator].dbg_exception_address == address) { return iterator; } } return (sector.size() + 1); } void dispatcher::unlock_sector(std::array<dispatcher::pool_sect, 128>& sector, std::size_t index) { sector[index].used = false; sector[index].is_aeh_present = false; sector[index].dbg_exception_address = dbg_redef::nullval; sector[index].save_code = dbg_redef::nullval; } void dispatcher::lock_sector(std::array<dispatcher::pool_sect, 128>& sector, std::size_t index) { sector[index].used = true; sector[index].is_aeh_present = false; } void dispatcher::add_exception(std::array<dispatcher::pool_sect, 128>& sector, std::size_t index, dispatcher::exception_type type, std::uint32_t dbg_exception_address) { sector[index].dbg_exception_address = dbg_exception_address; sector[index].save_code = *reinterpret_cast<std::uint32_t*>(dbg_exception_address); sector[index].dbg_exception_type = type; sector[index].index = index; dispatcher::lock_sector(sector, index); // will later add other types of exceptions/conditions switch (type) { case dispatcher::exception_type::immediate_exception: dispatcher::raise_priv_code_excpt(reinterpret_cast<std::uint8_t*>(sector[index].dbg_exception_address), 0, true); return; case dispatcher::exception_type::page_exception: dispatcher::raise_page_av(reinterpret_cast<std::uint8_t*>(sector[index].dbg_exception_address), 0, true); return; } } <|endoftext|>
<commit_before> #include "Expr.h" #include <stdio.h> #include <string.h> namespace hsql { char* substr(const char* source, int from, int to) { int len = to-from; char* copy = new char[len+1]; strncpy(copy, source+from, len); copy[len] = '\0'; return copy; } Expr* Expr::makeOpUnary(OperatorType op, Expr* expr) { ALLOC_EXPR(e, kExprOperator); e->op_type = op; e->expr = expr; e->expr2 = NULL; return e; } Expr* Expr::makeOpBinary(Expr* expr1, OperatorType op, Expr* expr2) { ALLOC_EXPR(e, kExprOperator); e->op_type = op; e->op_char = 0; e->expr = expr1; e->expr2 = expr2; return e; } Expr* Expr::makeOpBinary(Expr* expr1, char op, Expr* expr2) { ALLOC_EXPR(e, kExprOperator); e->op_type = SIMPLE_OP; e->op_char = op; e->expr = expr1; e->expr2 = expr2; return e; } Expr* Expr::makeLiteral(int64_t val) { ALLOC_EXPR(e, kExprLiteralInt); e->ival = val; return e; } Expr* Expr::makeLiteral(double value) { ALLOC_EXPR(e, kExprLiteralFloat); e->fval = value; return e; } Expr* Expr::makeLiteral(char* string) { ALLOC_EXPR(e, kExprLiteralString); e->name = string; return e; } Expr* Expr::makeColumnRef(char* name) { ALLOC_EXPR(e, kExprColumnRef); e->name = name; return e; } Expr* Expr::makeColumnRef(char* table, char* name) { ALLOC_EXPR(e, kExprTableColumnRef); e->name = name; e->table = table; return e; } Expr* Expr::makeFunctionRef(char* func_name, Expr* expr) { ALLOC_EXPR(e, kExprFunctionRef); e->name = func_name; e->expr = expr; return e; } Expr::~Expr() { // delete expr; // delete expr2; // delete name; // delete table; } } // namespace hsql<commit_msg>uncommented destructor of expr<commit_after> #include "Expr.h" #include <stdio.h> #include <string.h> namespace hsql { char* substr(const char* source, int from, int to) { int len = to-from; char* copy = new char[len+1]; strncpy(copy, source+from, len); copy[len] = '\0'; return copy; } Expr* Expr::makeOpUnary(OperatorType op, Expr* expr) { ALLOC_EXPR(e, kExprOperator); e->op_type = op; e->expr = expr; e->expr2 = NULL; return e; } Expr* Expr::makeOpBinary(Expr* expr1, OperatorType op, Expr* expr2) { ALLOC_EXPR(e, kExprOperator); e->op_type = op; e->op_char = 0; e->expr = expr1; e->expr2 = expr2; return e; } Expr* Expr::makeOpBinary(Expr* expr1, char op, Expr* expr2) { ALLOC_EXPR(e, kExprOperator); e->op_type = SIMPLE_OP; e->op_char = op; e->expr = expr1; e->expr2 = expr2; return e; } Expr* Expr::makeLiteral(int64_t val) { ALLOC_EXPR(e, kExprLiteralInt); e->ival = val; return e; } Expr* Expr::makeLiteral(double value) { ALLOC_EXPR(e, kExprLiteralFloat); e->fval = value; return e; } Expr* Expr::makeLiteral(char* string) { ALLOC_EXPR(e, kExprLiteralString); e->name = string; return e; } Expr* Expr::makeColumnRef(char* name) { ALLOC_EXPR(e, kExprColumnRef); e->name = name; return e; } Expr* Expr::makeColumnRef(char* table, char* name) { ALLOC_EXPR(e, kExprTableColumnRef); e->name = name; e->table = table; return e; } Expr* Expr::makeFunctionRef(char* func_name, Expr* expr) { ALLOC_EXPR(e, kExprFunctionRef); e->name = func_name; e->expr = expr; return e; } Expr::~Expr() { delete expr; delete expr2; delete name; delete table; } } // namespace hsql<|endoftext|>
<commit_before>#include "builtin/object.hpp" #include "util/thread.hpp" #include "objectmemory.hpp" #include "capi/capi.hpp" #include "capi/18/include/ruby.h" using namespace rubinius; using namespace rubinius::capi; static utilities::thread::ThreadData<ObjectMark*> _current_mark; namespace rubinius { namespace capi { void set_current_mark(ObjectMark* mark) { _current_mark.set(mark); } ObjectMark* current_mark() { return _current_mark.get(); } } } extern "C" { VALUE rb_gc_start() { VALUE gc_class_handle = rb_const_get(rb_cObject, rb_intern("GC")); rb_funcall(gc_class_handle, rb_intern("start"), 0); return Qnil; } void rb_gc() { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); // Normally ignore this. It's almost always a hack. if(getenv("RBX_RESPECT_RB_GC")) { env->state()->vm()->om->collect_young_now = true; env->state()->vm()->om->collect_mature_now = true; env->state()->shared().gc_soon(); } } void rb_gc_force_recycle(VALUE val) { // NOTHING. We don't support this and never will. } void rb_gc_mark(VALUE ptr) { Handle* handle = Handle::from(ptr); if(REFERENCE_P(handle) && handle->object()->reference_p()) { Object* res = capi::current_mark()->call(handle->object()); if(res) { handle->set_object(res); } } } void rb_gc_mark_locations(VALUE *start, VALUE *end) { VALUE *v = start; while (v < end) { rb_gc_mark(*v++); } } /* In MRI, this function marks an object if it can be determined * to be in the heap. */ void rb_gc_mark_maybe(VALUE ptr) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); Handle* handle = Handle::from(ptr); if(capi::Handle::valid_handle_p(env->state(), handle)) { rb_gc_mark(ptr); } } void rb_memerror() { // MRI raises a NoMemError here, but we're going to just // print out and error and exit. std::cerr << "[FATAL] Out of memory. Game Over." << std::endl; exit(EXIT_FAILURE); } VALUE rb_gc_enable() { VALUE gc_class_handle = rb_const_get(rb_cObject, rb_intern("GC")); return rb_funcall(gc_class_handle, rb_intern("enable"), 0); } VALUE rb_gc_disable() { VALUE gc_class_handle = rb_const_get(rb_cObject, rb_intern("GC")); return rb_funcall(gc_class_handle, rb_intern("disable"), 0); } } <commit_msg>Use run_gc_soon method<commit_after>#include "builtin/object.hpp" #include "util/thread.hpp" #include "objectmemory.hpp" #include "capi/capi.hpp" #include "capi/18/include/ruby.h" using namespace rubinius; using namespace rubinius::capi; static utilities::thread::ThreadData<ObjectMark*> _current_mark; namespace rubinius { namespace capi { void set_current_mark(ObjectMark* mark) { _current_mark.set(mark); } ObjectMark* current_mark() { return _current_mark.get(); } } } extern "C" { VALUE rb_gc_start() { VALUE gc_class_handle = rb_const_get(rb_cObject, rb_intern("GC")); rb_funcall(gc_class_handle, rb_intern("start"), 0); return Qnil; } void rb_gc() { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); // Normally ignore this. It's almost always a hack. if(getenv("RBX_RESPECT_RB_GC")) { env->state()->vm()->run_gc_soon(); } } void rb_gc_force_recycle(VALUE val) { // NOTHING. We don't support this and never will. } void rb_gc_mark(VALUE ptr) { Handle* handle = Handle::from(ptr); if(REFERENCE_P(handle) && handle->object()->reference_p()) { Object* res = capi::current_mark()->call(handle->object()); if(res) { handle->set_object(res); } } } void rb_gc_mark_locations(VALUE *start, VALUE *end) { VALUE *v = start; while (v < end) { rb_gc_mark(*v++); } } /* In MRI, this function marks an object if it can be determined * to be in the heap. */ void rb_gc_mark_maybe(VALUE ptr) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); Handle* handle = Handle::from(ptr); if(capi::Handle::valid_handle_p(env->state(), handle)) { rb_gc_mark(ptr); } } void rb_memerror() { // MRI raises a NoMemError here, but we're going to just // print out and error and exit. std::cerr << "[FATAL] Out of memory. Game Over." << std::endl; exit(EXIT_FAILURE); } VALUE rb_gc_enable() { VALUE gc_class_handle = rb_const_get(rb_cObject, rb_intern("GC")); return rb_funcall(gc_class_handle, rb_intern("enable"), 0); } VALUE rb_gc_disable() { VALUE gc_class_handle = rb_const_get(rb_cObject, rb_intern("GC")); return rb_funcall(gc_class_handle, rb_intern("disable"), 0); } } <|endoftext|>
<commit_before>#include "gc/root.hpp" #include "vm.hpp" namespace rubinius { /* Roots */ Root* Roots::front() { return static_cast<Root*>(head()); } /* Root */ Root::Root(STATE): LinkedList::Node(), object(NULL), roots(&state->globals.roots) { } Root::Root(STATE, Object* obj): LinkedList::Node(), object(NULL), roots(NULL) { set(obj, &state->globals.roots); } void Root::set(Object* obj, Roots* r) { // Still in the same set, no problem, just repoint // object. if(roots == r) { // We don't add the root until it's got an object. if(!object) roots->add(this); object = obj; // Moving to a new set. Remove ourselves from // the current set if we added ourself (we have an // object) } else { if(object) roots->remove(this); object = obj; roots = r; if(object) roots->add(this); } } } <commit_msg>Check that roots aren't null.<commit_after>#include "gc/root.hpp" #include "vm.hpp" namespace rubinius { /* Roots */ Root* Roots::front() { return static_cast<Root*>(head()); } /* Root */ Root::Root(STATE): LinkedList::Node(), object(NULL), roots(&state->globals.roots) { } Root::Root(STATE, Object* obj): LinkedList::Node(), object(NULL), roots(NULL) { set(obj, &state->globals.roots); } void Root::set(Object* obj, Roots* r) { // Still in the same set, no problem, just repoint // object. if(roots == r) { // We don't add the root until it's got an object. if(!object && obj) roots->add(this); object = obj; // Moving to a new set. Remove ourselves from // the current set if we added ourself (we have an // object) } else { if(object) roots->remove(this); object = obj; roots = r; if(object) roots->add(this); } } } <|endoftext|>
<commit_before> #include "builtin/object.hpp" #include "call_frame.hpp" #include "builtin/autoload.hpp" #include "builtin/symbol.hpp" #include "builtin/module.hpp" #include "builtin/compiledcode.hpp" #include "builtin/class.hpp" #include "builtin/constantscope.hpp" #include "builtin/lookuptable.hpp" #include "global_cache.hpp" #include "objectmemory.hpp" #include "builtin/tuple.hpp" #include "builtin/system.hpp" #include "builtin/thread.hpp" #include "builtin/channel.hpp" #include "builtin/global_cache_entry.hpp" #include "builtin/methodtable.hpp" #include "builtin/location.hpp" #include "vm.hpp" #include "object_utils.hpp" #include "arguments.hpp" #include "call_frame.hpp" #include "lookup_data.hpp" #include "on_stack.hpp" #include "helpers.hpp" namespace rubinius { namespace Helpers { Object* const_get_under(STATE, Module* mod, Symbol* name, bool* found, Object* filter) { Object* result; *found = false; while(!mod->nil_p()) { result = mod->get_const(state, name, found); if(*found) { if(result != filter) return result; *found = false; } // Don't stop when you see Object, because we need to check any // includes into Object as well, and they're found via superclass mod = mod->superclass(); } return cNil; } Object* const_get(STATE, CallFrame* call_frame, Symbol* name, bool* found, Object* filter) { ConstantScope *cur; Object* result; *found = false; call_frame = call_frame->top_ruby_frame(); // Ok, this has to be explained or it will be considered black magic. // The scope chain always ends with an entry at the top that contains // a parent of nil, and a module of Object. This entry is put in // regardless of lexical scoping, it's the fallback scope (the default // scope). This is not case when deriving from BasicObject, which is // explained later. // // When looking up a constant, we don't want to consider the fallback // scope (ie, Object) initially because we need to lookup up // the superclass chain first, because falling back on the default. // // The rub comes from the fact that if a user explicitly opens up // Object in their code, we DO consider it. Like: // // class Idiot // A = 2 // end // // class ::Object // A = 1 // class Stupid < Idiot // def foo // p A // end // end // end // // In this code, when A is looked up, Object must be considering during // the scope walk, NOT during the superclass walk. // // So, in this case, foo would print "1", not "2". // // As indicated above, the fallback scope isn't used when the superclass // chain directly rooted from BasicObject. To determine this is the // case, we record whether Object is seen when looking up the superclass // chain. If Object isn't seen, this means we are directly deriving from // BasicObject. cur = call_frame->constant_scope(); while(!cur->nil_p()) { // Detect the toplevel scope (the default) and get outta dodge. if(cur->top_level_p(state)) break; result = cur->module()->get_const(state, name, found); if(*found) { if(result != filter) return result; *found = false; } cur = cur->parent(); } // Now look up the superclass chain. Module *fallback = G(object); bool object_seen = false; cur = call_frame->constant_scope(); if(!cur->nil_p()) { Module* mod = cur->module(); while(!mod->nil_p()) { if(mod == G(object)) { object_seen = true; } if(!object_seen && mod == G(basicobject)) { fallback = NULL; } result = mod->get_const(state, name, found); if(*found) { if(result != filter) return result; *found = false; } mod = mod->superclass(); } } // Lastly, check the fallback scope (=Object) specifically if needed if(fallback) { result = fallback->get_const(state, name, found, true); if(*found) { if(result != filter) return result; *found = false; } } return cNil; } Object* const_missing_under(STATE, Module* under, Symbol* sym, CallFrame* call_frame) { Array* args = Array::create(state, 1); args->set(state, 0, sym); return under->send(state, call_frame, G(sym_const_missing), args); } Object* const_missing(STATE, Symbol* sym, CallFrame* call_frame) { Module* under; call_frame = call_frame->top_ruby_frame(); ConstantScope* scope = call_frame->constant_scope(); if(scope->nil_p()) { under = G(object); } else { under = scope->module(); } Array* args = Array::create(state, 1); args->set(state, 0, sym); return under->send(state, call_frame, G(sym_const_missing), args); } /** @todo Remove redundancy between this and sends. --rue */ Tuple* locate_method_on(STATE, CallFrame* call_frame, Object* recv, Symbol* name, Object* priv) { LookupData lookup(recv, recv->lookup_begin(state), CBOOL(priv) ? G(sym_private) : G(sym_protected)); Dispatch dis(name); if(!GlobalCache::resolve(state, dis.name, dis, lookup)) { return nil<Tuple>(); } return Tuple::from(state, 2, dis.method, dis.module); } Class* open_class(STATE, GCToken gct, CallFrame* call_frame, Object* super, Symbol* name, bool* created) { Module* under; call_frame = call_frame->top_ruby_frame(); if(call_frame->constant_scope()->nil_p()) { under = G(object); } else { under = call_frame->constant_scope()->module(); } return open_class(state, gct, call_frame, under, super, name, created); } static Class* add_class(STATE, Module* under, Object* super, Symbol* name) { if(super->nil_p()) super = G(object); Class* cls = Class::create(state, as<Class>(super)); cls->set_name(state, name, under); under->set_const(state, name, cls); return cls; } static Class* check_superclass(STATE, CallFrame* call_frame, Class* cls, Object* super) { if(super->nil_p()) return cls; if(cls->true_superclass(state) != super) { std::ostringstream message; message << "Superclass mismatch: given " << as<Module>(super)->debug_str(state) << " but previously set to " << cls->true_superclass(state)->debug_str(state); Exception* exc = Exception::make_type_error(state, Class::type, super, message.str().c_str()); exc->locations(state, Location::from_call_stack(state, call_frame)); state->raise_exception(exc); return NULL; } return cls; } Class* open_class(STATE, GCToken gct, CallFrame* call_frame, Module* under, Object* super, Symbol* name, bool* created) { bool found; *created = false; Object* obj = under->get_const(state, name, &found); OnStack<4> os(state, under, super, name, obj); if(found) { TypedRoot<Object*> sup(state, super); if(Autoload* autoload = try_as<Autoload>(obj)) { obj = autoload->resolve(state, gct, call_frame, true); // Check if an exception occurred if(!obj) return NULL; } // Autoload::resolve will return nil if code loading failed, in which // case we ignore the autoload. if(!obj->nil_p()) { return check_superclass(state, call_frame, as<Class>(obj), sup.get()); } } *created = true; return add_class(state, under, super, name); } Module* open_module(STATE, GCToken gct, CallFrame* call_frame, Symbol* name) { Module* under = G(object); call_frame = call_frame->top_ruby_frame(); if(!call_frame->constant_scope()->nil_p()) { under = call_frame->constant_scope()->module(); } return open_module(state, gct, call_frame, under, name); } Module* open_module(STATE, GCToken gct, CallFrame* call_frame, Module* under, Symbol* name) { Module* module; bool found; Object* obj = under->get_const(state, name, &found); OnStack<3> os(state, under, name, obj); if(found) { if(Autoload* autoload = try_as<Autoload>(obj)) { obj = autoload->resolve(state, gct, call_frame, true); } // Check if an exception occurred if(!obj) return NULL; // Autoload::resolve will return nil if code loading failed, in which // case we ignore the autoload. if(!obj->nil_p()) { return as<Module>(obj); } } module = Module::create(state); module->set_name(state, name, under); under->set_const(state, name, module); return module; } bool yield_debugger(STATE, GCToken gct, CallFrame* call_frame, Object* bp) { Thread* cur = Thread::current(state); Thread* debugger = cur->debugger_thread(); // No debugger, bail. if(debugger->nil_p()) { std::cout << "no debugger\n"; return true; } Channel* debugger_chan = debugger->control_channel(); // Debugger not initialized? bail. if(debugger_chan->nil_p()) { std::cout << "no debugger channel\n"; return true; } // No one waiting on it? Well, nevermind then. if(!debugger_chan->has_readers_p()) { std::cout << "no waiters\n"; return true; } // If we're hitting here, clear any chance that step would be used // without being explicitly requested. state->vm()->clear_thread_step(); state->set_call_frame(call_frame); Channel* my_control = cur->control_channel(); // Lazily create our own control channel. if(my_control->nil_p()) { my_control = Channel::create(state); cur->control_channel(state, my_control); } Array* locs = Location::from_call_stack(state, call_frame, true, true); OnStack<1> os(state, my_control); debugger_chan->send(state, gct, Tuple::from(state, 4, bp, cur, my_control, locs)); // Block until the debugger wakes us back up. Object* ret = my_control->receive(state, gct, call_frame); // Do not access any locals other than ret beyond here unless you add OnStack<> // to them! The GC has probably run and moved things. // if ret is null, then receive was interrupted and there is an exception // to propagate. if(!ret) return false; // Process a few commands... if(ret == state->symbol("step")) { state->vm()->get_attention(); state->vm()->set_thread_step(); } // All done! return true; } } } <commit_msg>Pass down enclosing module when resolving autoload<commit_after> #include "builtin/object.hpp" #include "call_frame.hpp" #include "builtin/autoload.hpp" #include "builtin/symbol.hpp" #include "builtin/module.hpp" #include "builtin/compiledcode.hpp" #include "builtin/class.hpp" #include "builtin/constantscope.hpp" #include "builtin/lookuptable.hpp" #include "global_cache.hpp" #include "objectmemory.hpp" #include "builtin/tuple.hpp" #include "builtin/system.hpp" #include "builtin/thread.hpp" #include "builtin/channel.hpp" #include "builtin/global_cache_entry.hpp" #include "builtin/methodtable.hpp" #include "builtin/location.hpp" #include "vm.hpp" #include "object_utils.hpp" #include "arguments.hpp" #include "call_frame.hpp" #include "lookup_data.hpp" #include "on_stack.hpp" #include "helpers.hpp" namespace rubinius { namespace Helpers { Object* const_get_under(STATE, Module* mod, Symbol* name, bool* found, Object* filter) { Object* result; *found = false; while(!mod->nil_p()) { result = mod->get_const(state, name, found); if(*found) { if(result != filter) return result; *found = false; } // Don't stop when you see Object, because we need to check any // includes into Object as well, and they're found via superclass mod = mod->superclass(); } return cNil; } Object* const_get(STATE, CallFrame* call_frame, Symbol* name, bool* found, Object* filter) { ConstantScope *cur; Object* result; *found = false; call_frame = call_frame->top_ruby_frame(); // Ok, this has to be explained or it will be considered black magic. // The scope chain always ends with an entry at the top that contains // a parent of nil, and a module of Object. This entry is put in // regardless of lexical scoping, it's the fallback scope (the default // scope). This is not case when deriving from BasicObject, which is // explained later. // // When looking up a constant, we don't want to consider the fallback // scope (ie, Object) initially because we need to lookup up // the superclass chain first, because falling back on the default. // // The rub comes from the fact that if a user explicitly opens up // Object in their code, we DO consider it. Like: // // class Idiot // A = 2 // end // // class ::Object // A = 1 // class Stupid < Idiot // def foo // p A // end // end // end // // In this code, when A is looked up, Object must be considering during // the scope walk, NOT during the superclass walk. // // So, in this case, foo would print "1", not "2". // // As indicated above, the fallback scope isn't used when the superclass // chain directly rooted from BasicObject. To determine this is the // case, we record whether Object is seen when looking up the superclass // chain. If Object isn't seen, this means we are directly deriving from // BasicObject. cur = call_frame->constant_scope(); while(!cur->nil_p()) { // Detect the toplevel scope (the default) and get outta dodge. if(cur->top_level_p(state)) break; result = cur->module()->get_const(state, name, found); if(*found) { if(result != filter) return result; *found = false; } cur = cur->parent(); } // Now look up the superclass chain. Module *fallback = G(object); bool object_seen = false; cur = call_frame->constant_scope(); if(!cur->nil_p()) { Module* mod = cur->module(); while(!mod->nil_p()) { if(mod == G(object)) { object_seen = true; } if(!object_seen && mod == G(basicobject)) { fallback = NULL; } result = mod->get_const(state, name, found); if(*found) { if(result != filter) return result; *found = false; } mod = mod->superclass(); } } // Lastly, check the fallback scope (=Object) specifically if needed if(fallback) { result = fallback->get_const(state, name, found, true); if(*found) { if(result != filter) return result; *found = false; } } return cNil; } Object* const_missing_under(STATE, Module* under, Symbol* sym, CallFrame* call_frame) { Array* args = Array::create(state, 1); args->set(state, 0, sym); return under->send(state, call_frame, G(sym_const_missing), args); } Object* const_missing(STATE, Symbol* sym, CallFrame* call_frame) { Module* under; call_frame = call_frame->top_ruby_frame(); ConstantScope* scope = call_frame->constant_scope(); if(scope->nil_p()) { under = G(object); } else { under = scope->module(); } Array* args = Array::create(state, 1); args->set(state, 0, sym); return under->send(state, call_frame, G(sym_const_missing), args); } /** @todo Remove redundancy between this and sends. --rue */ Tuple* locate_method_on(STATE, CallFrame* call_frame, Object* recv, Symbol* name, Object* priv) { LookupData lookup(recv, recv->lookup_begin(state), CBOOL(priv) ? G(sym_private) : G(sym_protected)); Dispatch dis(name); if(!GlobalCache::resolve(state, dis.name, dis, lookup)) { return nil<Tuple>(); } return Tuple::from(state, 2, dis.method, dis.module); } Class* open_class(STATE, GCToken gct, CallFrame* call_frame, Object* super, Symbol* name, bool* created) { Module* under; call_frame = call_frame->top_ruby_frame(); if(call_frame->constant_scope()->nil_p()) { under = G(object); } else { under = call_frame->constant_scope()->module(); } return open_class(state, gct, call_frame, under, super, name, created); } static Class* add_class(STATE, Module* under, Object* super, Symbol* name) { if(super->nil_p()) super = G(object); Class* cls = Class::create(state, as<Class>(super)); cls->set_name(state, name, under); under->set_const(state, name, cls); return cls; } static Class* check_superclass(STATE, CallFrame* call_frame, Class* cls, Object* super) { if(super->nil_p()) return cls; if(cls->true_superclass(state) != super) { std::ostringstream message; message << "Superclass mismatch: given " << as<Module>(super)->debug_str(state) << " but previously set to " << cls->true_superclass(state)->debug_str(state); Exception* exc = Exception::make_type_error(state, Class::type, super, message.str().c_str()); exc->locations(state, Location::from_call_stack(state, call_frame)); state->raise_exception(exc); return NULL; } return cls; } Class* open_class(STATE, GCToken gct, CallFrame* call_frame, Module* under, Object* super, Symbol* name, bool* created) { bool found; *created = false; Object* obj = under->get_const(state, name, &found); OnStack<4> os(state, under, super, name, obj); if(found) { TypedRoot<Object*> sup(state, super); if(Autoload* autoload = try_as<Autoload>(obj)) { obj = autoload->resolve(state, gct, call_frame, under, true); // Check if an exception occurred if(!obj) return NULL; } // Autoload::resolve will return nil if code loading failed, in which // case we ignore the autoload. if(!obj->nil_p()) { return check_superclass(state, call_frame, as<Class>(obj), sup.get()); } } *created = true; return add_class(state, under, super, name); } Module* open_module(STATE, GCToken gct, CallFrame* call_frame, Symbol* name) { Module* under = G(object); call_frame = call_frame->top_ruby_frame(); if(!call_frame->constant_scope()->nil_p()) { under = call_frame->constant_scope()->module(); } return open_module(state, gct, call_frame, under, name); } Module* open_module(STATE, GCToken gct, CallFrame* call_frame, Module* under, Symbol* name) { Module* module; bool found; Object* obj = under->get_const(state, name, &found); OnStack<3> os(state, under, name, obj); if(found) { if(Autoload* autoload = try_as<Autoload>(obj)) { obj = autoload->resolve(state, gct, call_frame, under, true); } // Check if an exception occurred if(!obj) return NULL; // Autoload::resolve will return nil if code loading failed, in which // case we ignore the autoload. if(!obj->nil_p()) { return as<Module>(obj); } } module = Module::create(state); module->set_name(state, name, under); under->set_const(state, name, module); return module; } bool yield_debugger(STATE, GCToken gct, CallFrame* call_frame, Object* bp) { Thread* cur = Thread::current(state); Thread* debugger = cur->debugger_thread(); // No debugger, bail. if(debugger->nil_p()) { std::cout << "no debugger\n"; return true; } Channel* debugger_chan = debugger->control_channel(); // Debugger not initialized? bail. if(debugger_chan->nil_p()) { std::cout << "no debugger channel\n"; return true; } // No one waiting on it? Well, nevermind then. if(!debugger_chan->has_readers_p()) { std::cout << "no waiters\n"; return true; } // If we're hitting here, clear any chance that step would be used // without being explicitly requested. state->vm()->clear_thread_step(); state->set_call_frame(call_frame); Channel* my_control = cur->control_channel(); // Lazily create our own control channel. if(my_control->nil_p()) { my_control = Channel::create(state); cur->control_channel(state, my_control); } Array* locs = Location::from_call_stack(state, call_frame, true, true); OnStack<1> os(state, my_control); debugger_chan->send(state, gct, Tuple::from(state, 4, bp, cur, my_control, locs)); // Block until the debugger wakes us back up. Object* ret = my_control->receive(state, gct, call_frame); // Do not access any locals other than ret beyond here unless you add OnStack<> // to them! The GC has probably run and moved things. // if ret is null, then receive was interrupted and there is an exception // to propagate. if(!ret) return false; // Process a few commands... if(ret == state->symbol("step")) { state->vm()->get_attention(); state->vm()->set_thread_step(); } // All done! return true; } } } <|endoftext|>
<commit_before>#include "objectmemory.hpp" #include "marshal.hpp" #include "builtin/sendsite.hpp" #include "builtin/array.hpp" #include "builtin/compiledmethod.hpp" #include "builtin/fixnum.hpp" #include "builtin/float.hpp" #include "builtin/iseq.hpp" #include "builtin/string.hpp" #include "builtin/symbol.hpp" #include "builtin/tuple.hpp" namespace rubinius { using std::endl; void Marshaller::set_int(OBJECT obj) { stream << "I" << endl << as<Integer>(obj)->to_native() << endl; } void Marshaller::set_bignum(Bignum* big) { char buf[1024]; memset(buf, 0, 1024); big->into_string(state, 10, buf, 1023); stream << "I" << endl << buf << endl; } OBJECT UnMarshaller::get_int() { char data[1024]; memset(data, 0, 1024); stream >> data; return Bignum::from_string(state, data, 10); } void Marshaller::set_string(String* str) { stream << "s" << endl << str->size() << endl; stream.write(str->byte_address(), str->size()) << endl; } String* UnMarshaller::get_string() { size_t count; stream >> count; // String::create adds room for a trailing null on its own String* str = String::create(state, NULL, count); stream.get(); // read off newline stream.read(str->byte_address(), count); stream.get(); // read off newline return str; } void Marshaller::set_symbol(SYMBOL sym) { String* str = sym->to_str(state); stream << "x" << endl << str->size() << endl; stream.write(str->byte_address(), str->size()) << endl; } SYMBOL UnMarshaller::get_symbol() { char data[1024]; size_t count; stream >> count; stream.get(); stream.read(data, count + 1); data[count] = 0; // clamp return state->symbol(data); } void Marshaller::set_sendsite(SendSite* ss) { String* str = ss->name()->to_str(state); stream << "S" << endl << str->size() << endl; stream.write(str->c_str(), str->size()) << endl; } SendSite* UnMarshaller::get_sendsite() { char data[1024]; size_t count; stream >> count; stream.get(); stream.read(data, count + 1); data[count] = 0; // clamp SYMBOL sym = state->symbol(data); return SendSite::create(state, sym); } void Marshaller::set_array(Array* ary) { size_t count = ary->size(); stream << "A" << endl << count << endl; for(size_t i = 0; i < count; i++) { marshal(ary->get(state, i)); } } Array* UnMarshaller::get_array() { size_t count; stream >> count; Array* ary = Array::create(state, count); for(size_t i = 0; i < count; i++) { ary->set(state, i, unmarshal()); } return ary; } void Marshaller::set_tuple(Tuple* tup) { stream << "p" << endl << tup->num_fields() << endl; for(size_t i = 0; i < tup->num_fields(); i++) { marshal(tup->at(i)); } } Tuple* UnMarshaller::get_tuple() { size_t count; stream >> count; Tuple* tup = Tuple::create(state, count); for(size_t i = 0; i < count; i++) { tup->put(state, i, unmarshal()); } return tup; } void Marshaller::set_float(Float* flt) { stream << "d" << endl << flt->val << endl; } Float* UnMarshaller::get_float() { double val; stream >> val; return Float::create(state, val); } void Marshaller::set_iseq(InstructionSequence* iseq) { Tuple* ops = iseq->opcodes(); stream << "i" << endl << ops->num_fields() << endl; for(size_t i = 0; i < ops->num_fields(); i++) { stream << as<Fixnum>(ops->at(i))->to_native() << endl; } } InstructionSequence* UnMarshaller::get_iseq() { size_t count; long op; stream >> count; InstructionSequence* iseq = InstructionSequence::create(state, count); Tuple* ops = iseq->opcodes(); for(size_t i = 0; i < count; i++) { stream >> op; ops->put(state, i, Fixnum::from(op)); } iseq->post_marshal(state); return iseq; } void Marshaller::set_cmethod(CompiledMethod* cm) { assert(0); } CompiledMethod* UnMarshaller::get_cmethod() { size_t ver; stream >> ver; CompiledMethod* cm = CompiledMethod::create(state); cm->ivars(state, unmarshal()); cm->primitive(state, (SYMBOL)unmarshal()); cm->name(state, (SYMBOL)unmarshal()); cm->iseq(state, (InstructionSequence*)unmarshal()); cm->stack_size(state, (FIXNUM)unmarshal()); cm->local_count(state, (FIXNUM)unmarshal()); cm->required_args(state, (FIXNUM)unmarshal()); cm->total_args(state, (FIXNUM)unmarshal()); cm->splat(state, unmarshal()); cm->literals(state, (Tuple*)unmarshal()); cm->exceptions(state, (Tuple*)unmarshal()); cm->lines(state, (Tuple*)unmarshal()); cm->file(state, (SYMBOL)unmarshal()); cm->local_names(state, (Tuple*)unmarshal()); cm->post_marshal(state); return cm; } OBJECT UnMarshaller::unmarshal() { char code; stream >> code; switch(code) { case 'n': return Qnil; case 't': return Qtrue; case 'f': return Qfalse; case 'I': return get_int(); case 's': return get_string(); case 'x': return get_symbol(); case 'S': return get_sendsite(); case 'A': return get_array(); case 'p': return get_tuple(); case 'd': return get_float(); case 'i': return get_iseq(); case 'M': return get_cmethod(); default: std::string str = "unknown marshal code: "; str.append( 1, code ); throw std::runtime_error(str); } } void Marshaller::marshal(OBJECT obj) { if(obj == Qnil) { stream << "n" << endl; } else if(obj == Qtrue) { stream << "t" << endl; } else if(obj == Qfalse) { stream << "f" << endl; } else if(obj->fixnum_p()) { set_int(obj); } else if(obj->symbol_p()) { set_symbol((SYMBOL)obj); } else if(kind_of<Bignum>(obj)) { set_bignum(as<Bignum>(obj)); } else if(kind_of<String>(obj)) { set_string(as<String>(obj)); } else if(kind_of<SendSite>(obj)) { set_sendsite(as<SendSite>(obj)); } else if(kind_of<Array>(obj)) { set_array(as<Array>(obj)); } else if(kind_of<Tuple>(obj)) { set_tuple(as<Tuple>(obj)); } else if(kind_of<Float>(obj)) { set_float(as<Float>(obj)); } else if(kind_of<InstructionSequence>(obj)) { set_iseq(as<InstructionSequence>(obj)); } else if(kind_of<CompiledMethod>(obj)) { set_cmethod(as<CompiledMethod>(obj)); } else { throw std::runtime_error("unknown object"); } } } <commit_msg>Handle unmarshalling literals for Infinity, etc.<commit_after>#include "objectmemory.hpp" #include "marshal.hpp" #include "builtin/sendsite.hpp" #include "builtin/array.hpp" #include "builtin/compiledmethod.hpp" #include "builtin/fixnum.hpp" #include "builtin/float.hpp" #include "builtin/iseq.hpp" #include "builtin/string.hpp" #include "builtin/symbol.hpp" #include "builtin/tuple.hpp" #include <cctype> #include <cstring> namespace rubinius { using std::endl; void Marshaller::set_int(OBJECT obj) { stream << "I" << endl << as<Integer>(obj)->to_native() << endl; } void Marshaller::set_bignum(Bignum* big) { char buf[1024]; memset(buf, 0, 1024); big->into_string(state, 10, buf, 1023); stream << "I" << endl << buf << endl; } OBJECT UnMarshaller::get_int() { char data[1024]; memset(data, 0, 1024); stream >> data; return Bignum::from_string(state, data, 10); } void Marshaller::set_string(String* str) { stream << "s" << endl << str->size() << endl; stream.write(str->byte_address(), str->size()) << endl; } String* UnMarshaller::get_string() { size_t count; stream >> count; // String::create adds room for a trailing null on its own String* str = String::create(state, NULL, count); stream.get(); // read off newline stream.read(str->byte_address(), count); stream.get(); // read off newline return str; } void Marshaller::set_symbol(SYMBOL sym) { String* str = sym->to_str(state); stream << "x" << endl << str->size() << endl; stream.write(str->byte_address(), str->size()) << endl; } SYMBOL UnMarshaller::get_symbol() { char data[1024]; size_t count; stream >> count; stream.get(); stream.read(data, count + 1); data[count] = 0; // clamp return state->symbol(data); } void Marshaller::set_sendsite(SendSite* ss) { String* str = ss->name()->to_str(state); stream << "S" << endl << str->size() << endl; stream.write(str->c_str(), str->size()) << endl; } SendSite* UnMarshaller::get_sendsite() { char data[1024]; size_t count; stream >> count; stream.get(); stream.read(data, count + 1); data[count] = 0; // clamp SYMBOL sym = state->symbol(data); return SendSite::create(state, sym); } void Marshaller::set_array(Array* ary) { size_t count = ary->size(); stream << "A" << endl << count << endl; for(size_t i = 0; i < count; i++) { marshal(ary->get(state, i)); } } Array* UnMarshaller::get_array() { size_t count; stream >> count; Array* ary = Array::create(state, count); for(size_t i = 0; i < count; i++) { ary->set(state, i, unmarshal()); } return ary; } void Marshaller::set_tuple(Tuple* tup) { stream << "p" << endl << tup->num_fields() << endl; for(size_t i = 0; i < tup->num_fields(); i++) { marshal(tup->at(i)); } } Tuple* UnMarshaller::get_tuple() { size_t count; stream >> count; Tuple* tup = Tuple::create(state, count); for(size_t i = 0; i < count; i++) { tup->put(state, i, unmarshal()); } return tup; } void Marshaller::set_float(Float* flt) { stream << "d" << endl << flt->val << endl; } Float* UnMarshaller::get_float() { char data[1024]; // discard the delimiter stream.get(); stream.getline(data, 1024); if(stream.fail()) { TypeError::raise("Unable to unmarshal Float: failed to read value"); } char c = data[0]; if(c == '-') c = data[1]; if(std::isdigit(c)) { // TODO: use ruby_strtod return Float::create(state, strtod(data, NULL)); } else { // avoid compiler warning double zero = 0.0; double val; if(!strncasecmp(data, "Infinity", 8U)) { val = 1.0; } else if(!strncmp(data, "-Infinity", 9U)) { val = -1.0; } else if(!strncmp(data, "NaN", 3U)) { val = zero; } else { TypeError::raise("Unable to unmarshal Float: invalid format"); } return Float::create(state, val / zero); } } void Marshaller::set_iseq(InstructionSequence* iseq) { Tuple* ops = iseq->opcodes(); stream << "i" << endl << ops->num_fields() << endl; for(size_t i = 0; i < ops->num_fields(); i++) { stream << as<Fixnum>(ops->at(i))->to_native() << endl; } } InstructionSequence* UnMarshaller::get_iseq() { size_t count; long op; stream >> count; InstructionSequence* iseq = InstructionSequence::create(state, count); Tuple* ops = iseq->opcodes(); for(size_t i = 0; i < count; i++) { stream >> op; ops->put(state, i, Fixnum::from(op)); } iseq->post_marshal(state); return iseq; } void Marshaller::set_cmethod(CompiledMethod* cm) { assert(0); } CompiledMethod* UnMarshaller::get_cmethod() { size_t ver; stream >> ver; CompiledMethod* cm = CompiledMethod::create(state); cm->ivars(state, unmarshal()); cm->primitive(state, (SYMBOL)unmarshal()); cm->name(state, (SYMBOL)unmarshal()); cm->iseq(state, (InstructionSequence*)unmarshal()); cm->stack_size(state, (FIXNUM)unmarshal()); cm->local_count(state, (FIXNUM)unmarshal()); cm->required_args(state, (FIXNUM)unmarshal()); cm->total_args(state, (FIXNUM)unmarshal()); cm->splat(state, unmarshal()); cm->literals(state, (Tuple*)unmarshal()); cm->exceptions(state, (Tuple*)unmarshal()); cm->lines(state, (Tuple*)unmarshal()); cm->file(state, (SYMBOL)unmarshal()); cm->local_names(state, (Tuple*)unmarshal()); cm->post_marshal(state); return cm; } OBJECT UnMarshaller::unmarshal() { char code; stream >> code; switch(code) { case 'n': return Qnil; case 't': return Qtrue; case 'f': return Qfalse; case 'I': return get_int(); case 's': return get_string(); case 'x': return get_symbol(); case 'S': return get_sendsite(); case 'A': return get_array(); case 'p': return get_tuple(); case 'd': return get_float(); case 'i': return get_iseq(); case 'M': return get_cmethod(); default: std::string str = "unknown marshal code: "; str.append( 1, code ); throw std::runtime_error(str); } } void Marshaller::marshal(OBJECT obj) { if(obj == Qnil) { stream << "n" << endl; } else if(obj == Qtrue) { stream << "t" << endl; } else if(obj == Qfalse) { stream << "f" << endl; } else if(obj->fixnum_p()) { set_int(obj); } else if(obj->symbol_p()) { set_symbol((SYMBOL)obj); } else if(kind_of<Bignum>(obj)) { set_bignum(as<Bignum>(obj)); } else if(kind_of<String>(obj)) { set_string(as<String>(obj)); } else if(kind_of<SendSite>(obj)) { set_sendsite(as<SendSite>(obj)); } else if(kind_of<Array>(obj)) { set_array(as<Array>(obj)); } else if(kind_of<Tuple>(obj)) { set_tuple(as<Tuple>(obj)); } else if(kind_of<Float>(obj)) { set_float(as<Float>(obj)); } else if(kind_of<InstructionSequence>(obj)) { set_iseq(as<InstructionSequence>(obj)); } else if(kind_of<CompiledMethod>(obj)) { set_cmethod(as<CompiledMethod>(obj)); } else { throw std::runtime_error("unknown object"); } } } <|endoftext|>
<commit_before>#include "FILE.H" #include "CD.H" #include "SPECIFIC.H" #include <sys/types.h> #include <libcd.h> #include <stdio.h> #include <libsn.h> int FILE_Load(char* szFileName, void* pDest)//5E528, 5E5D8(<) (F) { CdlFILE fp; char buf[10]; unsigned long dwFileSize = -1; DEL_ChangeCDMode(0); sprintf(buf, "\\%s;1", szFileName); CdSearchFile(&fp, buf); cdCurrentSector = CdPosToInt(&fp.pos); DEL_CDFS_Read((char*)pDest, fp.size); return fp.size; } int FILE_Read(char* pDest, int nItemSize, int nItems, int nHandle)//5E6A8(<), ? (F) { int nAmount = nItems * nItemSize; return PCread(nHandle, pDest, nAmount); } unsigned long FILE_Length(char* szFileName)//5E60C, 5E578(<) (F) { CdlFILE fp; char buf[10]; unsigned long dwFileSize = -1; DEL_ChangeCDMode(0); sprintf(buf, "\\%s;1", szFileName); if (CdSearchFile(&fp, buf)) { dwFileSize = fp.size; } return dwFileSize; } void RelocateModule(unsigned long Module, unsigned long* RelocData)//5E6D4(<), 5F430(<) (F) { //TODO check param ptrs on PSX, untested! unsigned long* pModule; unsigned long RelocationType; //loc_5E700 while (*RelocData != -1) { RelocationType = *RelocData & 3; pModule = (unsigned long*) (Module + (*RelocData++ & -4)); if (RelocationType == 0) { *(unsigned long*) pModule += Module; } else if (RelocationType == 1) { *(unsigned short*) pModule = (*RelocData++ + Module + 0x8000) / 65536; } else if (RelocationType == 2) { *(unsigned short*) pModule += Module; } else if (RelocationType == 3) { *(unsigned long*) pModule += Module / sizeof(unsigned long); } } }<commit_msg>Add FILE_Load/FILE_Length (INT)<commit_after>#include "FILE.H" #include "CD.H" #include "SPECIFIC.H" #include <sys/types.h> #include <libcd.h> #include <stdio.h> #include <libsn.h> int FILE_Load(char* szFileName, void* pDest)//5E528, 5E5D8(<) (F) { #if DISC_VERSION CdlFILE fp; char buf[10]; unsigned long dwFileSize = -1; DEL_ChangeCDMode(0); sprintf(buf, "\\%s;1", szFileName); CdSearchFile(&fp, buf); cdCurrentSector = CdPosToInt(&fp.pos); DEL_CDFS_Read((char*)pDest, fp.size); return fp.size; #else int nHandle; unsigned long dwFileSize; unsigned long dwBytesRead; printf("Open\n"); nHandle = PCopen(szFileName, 0, 0); if (nHandle < 0) { printf("FILE_Load: '%s' Could not open!\n", szFileName); S_ExitSystem("Can't open file"); } printf("Seek\n"); dwFileSize = PClseek(nHandle, 0, 2); PClseek(nHandle, 0, 0); printf("Read\n"); dwBytesRead = PCread(nHandle, (char*)pDest, dwFileSize); printf("Close\n"); PCclose(nHandle); return dwFileSize ^ dwBytesRead;//== ? 1 : 0 #endif } int FILE_Read(char* pDest, int nItemSize, int nItems, int nHandle)//5E6A8(<), ? (F) { int nAmount = nItems * nItemSize; return PCread(nHandle, pDest, nAmount); } unsigned long FILE_Length(char* szFileName)//5E60C, 5E578(<) (F) { #if DISC_VERSION CdlFILE fp; char buf[10]; unsigned long dwFileSize = -1; DEL_ChangeCDMode(0); sprintf(buf, "\\%s;1", szFileName); if (CdSearchFile(&fp, buf)) { dwFileSize = fp.size; } return dwFileSize; #else int nHandle; unsigned long dwFileSize; printf("Open\n"); nHandle = PCopen(szFileName, 0, 0); if (nHandle < 0) { printf("FILE_Length: '%s' Could not find!\n", szFileName); return -1; } else { printf("Seek\n"); dwFileSize = PClseek(nHandle, 0, 2); printf("Close\n"); PCclose(nHandle); return dwFileSize; } #endif } void RelocateModule(unsigned long Module, unsigned long* RelocData)//5E6D4(<), 5F430(<) (F) { //TODO check param ptrs on PSX, untested! unsigned long* pModule; unsigned long RelocationType; //loc_5E700 while (*RelocData != -1) { RelocationType = *RelocData & 3; pModule = (unsigned long*) (Module + (*RelocData++ & -4)); if (RelocationType == 0) { *(unsigned long*) pModule += Module; } else if (RelocationType == 1) { *(unsigned short*) pModule = (*RelocData++ + Module + 0x8000) / 65536; } else if (RelocationType == 2) { *(unsigned short*) pModule += Module; } else if (RelocationType == 3) { *(unsigned long*) pModule += Module / sizeof(unsigned long); } } }<|endoftext|>
<commit_before>/* * Copyright (c) 2001 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #if !defined(WINNT) #ident "$Id: symbols.cc,v 1.3 2001/05/09 04:23:19 steve Exp $" #endif # include "symbols.h" # include <string.h> # include <assert.h> struct symbol_table_s { struct tree_node_*root; }; /* * This is a B-Tree data structure, where there are nodes and * leaves. * * Nodes have a bunch of pointers to children. Each child pointer has * associated with it a key that is the largest key referenced by that * child. So, if the key being searched for has a value <= the first * key of a node, then the value is in the first child. * * leaves have a sorted table of key-value pairs. The search can use a * simple binary search to find an item. Each key represents an item. */ const unsigned leaf_width = 511; const unsigned node_width = 511; struct tree_node_ { bool leaf_flag; unsigned count; struct tree_node_*parent; union { struct { char*key; symbol_value_t val; } leaf[leaf_width]; struct tree_node_*child[node_width]; }; }; static inline char* node_last_key(struct tree_node_*node) { while (node->leaf_flag == false) node = node->child[node->count-1]; return node->leaf[node->count-1].key; } /* * Allocate a new symbol table means creating the table structure and * a root node, and initializing the pointers and members of the root * node. */ symbol_table_t new_symbol_table(void) { symbol_table_t tbl = new struct symbol_table_s; tbl->root = new struct tree_node_; tbl->root->leaf_flag = false; tbl->root->count = 0; tbl->root->parent = 0; return tbl; } static void split_node_(struct tree_node_*cur) { assert(0); } /* * This function takes a leaf node and splits in into two. Move half * the leaf keys into the new node, and add the new leaf into the * parent node. */ static struct tree_node_* split_leaf_(struct tree_node_*cur) { assert(cur->leaf_flag); assert(cur->parent); assert(! cur->parent->leaf_flag); /* Create a new leaf to hold half the data from the old leaf. */ struct tree_node_*new_leaf = new struct tree_node_; new_leaf->leaf_flag = true; new_leaf->count = cur->count / 2; new_leaf->parent = cur->parent; /* Move the last half of the data from the end of the old leaf to the beggining of the new leaf. At the same time, reduce the size of the old leaf. */ unsigned idx1 = new_leaf->count; unsigned idx2 = cur->count; while (idx1 > 0) { idx1 -= 1; idx2 -= 1; new_leaf->leaf[idx1] = cur->leaf[idx2]; cur->count -= 1; } assert(new_leaf->count > 0); assert(cur->count > 0); unsigned idx = 0; while (cur->parent->child[idx] != cur) { assert(idx < cur->parent->count); idx += 1; } idx += 1; for (unsigned tmp = cur->parent->count ; tmp > idx ; tmp -= 1) cur->parent->child[tmp] = cur->parent->child[tmp-1]; cur->parent->child[idx] = new_leaf; cur->parent->count += 1; if (cur->parent->count == node_width) split_node_(cur->parent); return new_leaf; } /* * This function searches tree recursively for the key. If the value * is not found (and we are at a leaf) then set the key with the given * value. If the key is found, set the value only if the force_flag is * true. */ static symbol_value_t find_value_(symbol_table_t tbl, struct tree_node_*cur, const char*key, symbol_value_t val, bool force_flag) { if (cur->leaf_flag) { unsigned idx = 0; for (;;) { /* If we run out of keys in the leaf, then add this at the end of the leaf. */ if (idx == cur->count) { cur->leaf[idx].key = strdup(key); cur->leaf[idx].val = val; cur->count += 1; if (cur->count == leaf_width) split_leaf_(cur); return val; } int rc = strcmp(key, cur->leaf[idx].key); /* If we found the key already in the table, then set the new value and break. */ if (rc == 0) { if (force_flag) cur->leaf[idx].val = val; return cur->leaf[idx].val; } /* If this key goes before the current key, then push all the following entries back and add this key here. */ if (rc < 0) { for (unsigned tmp = cur->count; tmp > idx; tmp -= 1) cur->leaf[tmp] = cur->leaf[tmp-1]; cur->leaf[idx].key = strdup(key); cur->leaf[idx].val = val; cur->count += 1; if (cur->count == leaf_width) split_leaf_(cur); return val; } idx += 1; } } else { unsigned idx = 0; for (;;) { if (idx == cur->count) { idx -= 1; return find_value_(tbl, cur->child[idx], key, val, force_flag); } int rc = strcmp(key, node_last_key(cur->child[idx])); if (rc <= 0) { return find_value_(tbl, cur->child[idx], key, val, force_flag); } idx += 1; } } assert(0); { symbol_value_t tmp; tmp.num = 0; return tmp; } } void sym_set_value(symbol_table_t tbl, const char*key, symbol_value_t val) { if (tbl->root->count == 0) { /* Handle the special case that this is the very first value in the symbol table. Create the first leaf node and initialize the pointers. */ struct tree_node_*cur = new struct tree_node_; cur->leaf_flag = true; cur->parent = tbl->root; cur->count = 1; cur->leaf[0].key = strdup(key); cur->leaf[0].val = val; tbl->root->count = 1; tbl->root->child[0] = cur; } else { find_value_(tbl, tbl->root, key, val, true); } } symbol_value_t sym_get_value(symbol_table_t tbl, const char*key) { symbol_value_t def; def.num = 0; if (tbl->root->count == 0) { /* Handle the special case that this is the very first value in the symbol table. Create the first leaf node and initialize the pointers. */ struct tree_node_*cur = new struct tree_node_; cur->leaf_flag = true; cur->parent = tbl->root; cur->count = 1; cur->leaf[0].key = strdup(key); cur->leaf[0].val = def; tbl->root->count = 1; tbl->root->child[0] = cur; return cur->leaf[0].val; } else { return find_value_(tbl, tbl->root, key, def, false); } } /* * $Log: symbols.cc,v $ * Revision 1.3 2001/05/09 04:23:19 steve * Now that the interactive debugger exists, * there is no use for the output dump. * * Revision 1.2 2001/03/18 00:37:55 steve * Add support for vpi scopes. * * Revision 1.1 2001/03/11 00:29:39 steve * Add the vvp engine to cvs. * */ <commit_msg> Implement split_node for symbol table (hendrik)<commit_after>/* * Copyright (c) 2001 Stephen Williams (steve@icarus.com) * * This source code is free software; you can redistribute it * and/or modify it in source code form under the terms of the GNU * General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #if !defined(WINNT) #ident "$Id: symbols.cc,v 1.4 2001/11/02 04:48:03 steve Exp $" #endif # include "symbols.h" # include <string.h> # include <assert.h> struct symbol_table_s { struct tree_node_*root; }; /* * This is a B-Tree data structure, where there are nodes and * leaves. * * Nodes have a bunch of pointers to children. Each child pointer has * associated with it a key that is the largest key referenced by that * child. So, if the key being searched for has a value <= the first * key of a node, then the value is in the first child. * * leaves have a sorted table of key-value pairs. The search can use a * simple binary search to find an item. Each key represents an item. */ const unsigned leaf_width = 511; const unsigned node_width = 511; struct tree_node_ { bool leaf_flag; unsigned count; struct tree_node_*parent; union { struct { char*key; symbol_value_t val; } leaf[leaf_width]; struct tree_node_*child[node_width]; }; }; static inline char* node_last_key(struct tree_node_*node) { while (node->leaf_flag == false) node = node->child[node->count-1]; return node->leaf[node->count-1].key; } /* * Allocate a new symbol table means creating the table structure and * a root node, and initializing the pointers and members of the root * node. */ symbol_table_t new_symbol_table(void) { symbol_table_t tbl = new struct symbol_table_s; tbl->root = new struct tree_node_; tbl->root->leaf_flag = false; tbl->root->count = 0; tbl->root->parent = 0; return tbl; } /* Do as split_leaf_ do, but for nodes. */ static void split_node_(struct tree_node_*cur) { unsigned int idx, idx1, idx2, tmp; struct tree_node_ *new_node; assert(!cur->leaf_flag); if (cur->parent) assert(! cur->parent->leaf_flag); while (cur->count == node_width) { /* Create a new node to hold half the data from the old node. */ new_node = new struct tree_node_; new_node->leaf_flag = false; new_node->count = cur->count / 2; if (cur->parent) /* cur is not root; new_node becomes sibling. */ new_node->parent = cur->parent; else /* cur is root; new_node becomes child. */ /* And. move the first half of child to another new node later */ new_node->parent = cur; /* Move the last half of the data from the end of the old node to the beggining of the new node. At the same time, reduce the size of the old node. */ idx1 = new_node->count; idx2 = cur->count; while (idx1 > 0) { idx1 -= 1; idx2 -= 1; new_node->child[idx1] = cur->child[idx2]; new_node->child[idx1]->parent = new_node; cur->count -= 1; } assert(new_node->count > 0); assert(cur->count > 0); if (cur->parent == 0) { /* cur is root. Move first half of children to another new node, and put the two new nodes in cur. */ cur->child[cur->count] /* used as tmep var */ = new_node; new_node = new struct tree_node_; new_node->leaf_flag = false; new_node->count = cur->count; for (idx = 0; idx < cur->count; idx ++) { new_node->child[idx] = cur->child[idx]; new_node->child[idx]->parent = new_node; } cur->child[0] = new_node; cur->child[1] = cur->child[cur->count]; cur->count = 2; /* no more ancestors, stop the while loop */ break; } /* cur is not root. hook new_node to cur->parent. */ idx = 0; while (cur->parent->child[idx] != cur) { assert(idx < cur->parent->count); idx += 1; } idx += 1; for (tmp = cur->parent->count ; tmp > idx ; tmp -= 1) cur->parent->child[tmp] = cur->parent->child[tmp-1]; cur->parent->child[idx] = new_node; cur->parent->count += 1; /* check the ancestor */ cur = cur->parent; } } /* * This function takes a leaf node and splits in into two. Move half * the leaf keys into the new node, and add the new leaf into the * parent node. */ static struct tree_node_* split_leaf_(struct tree_node_*cur) { assert(cur->leaf_flag); assert(cur->parent); assert(! cur->parent->leaf_flag); /* Create a new leaf to hold half the data from the old leaf. */ struct tree_node_*new_leaf = new struct tree_node_; new_leaf->leaf_flag = true; new_leaf->count = cur->count / 2; new_leaf->parent = cur->parent; /* Move the last half of the data from the end of the old leaf to the beggining of the new leaf. At the same time, reduce the size of the old leaf. */ unsigned idx1 = new_leaf->count; unsigned idx2 = cur->count; while (idx1 > 0) { idx1 -= 1; idx2 -= 1; new_leaf->leaf[idx1] = cur->leaf[idx2]; cur->count -= 1; } assert(new_leaf->count > 0); assert(cur->count > 0); unsigned idx = 0; while (cur->parent->child[idx] != cur) { assert(idx < cur->parent->count); idx += 1; } idx += 1; for (unsigned tmp = cur->parent->count ; tmp > idx ; tmp -= 1) cur->parent->child[tmp] = cur->parent->child[tmp-1]; cur->parent->child[idx] = new_leaf; cur->parent->count += 1; if (cur->parent->count == node_width) split_node_(cur->parent); return new_leaf; } /* * This function searches tree recursively for the key. If the value * is not found (and we are at a leaf) then set the key with the given * value. If the key is found, set the value only if the force_flag is * true. */ static symbol_value_t find_value_(symbol_table_t tbl, struct tree_node_*cur, const char*key, symbol_value_t val, bool force_flag) { if (cur->leaf_flag) { unsigned idx = 0; for (;;) { /* If we run out of keys in the leaf, then add this at the end of the leaf. */ if (idx == cur->count) { cur->leaf[idx].key = strdup(key); cur->leaf[idx].val = val; cur->count += 1; if (cur->count == leaf_width) split_leaf_(cur); return val; } int rc = strcmp(key, cur->leaf[idx].key); /* If we found the key already in the table, then set the new value and break. */ if (rc == 0) { if (force_flag) cur->leaf[idx].val = val; return cur->leaf[idx].val; } /* If this key goes before the current key, then push all the following entries back and add this key here. */ if (rc < 0) { for (unsigned tmp = cur->count; tmp > idx; tmp -= 1) cur->leaf[tmp] = cur->leaf[tmp-1]; cur->leaf[idx].key = strdup(key); cur->leaf[idx].val = val; cur->count += 1; if (cur->count == leaf_width) split_leaf_(cur); return val; } idx += 1; } } else { unsigned idx = 0; for (;;) { if (idx == cur->count) { idx -= 1; return find_value_(tbl, cur->child[idx], key, val, force_flag); } int rc = strcmp(key, node_last_key(cur->child[idx])); if (rc <= 0) { return find_value_(tbl, cur->child[idx], key, val, force_flag); } idx += 1; } } assert(0); { symbol_value_t tmp; tmp.num = 0; return tmp; } } void sym_set_value(symbol_table_t tbl, const char*key, symbol_value_t val) { if (tbl->root->count == 0) { /* Handle the special case that this is the very first value in the symbol table. Create the first leaf node and initialize the pointers. */ struct tree_node_*cur = new struct tree_node_; cur->leaf_flag = true; cur->parent = tbl->root; cur->count = 1; cur->leaf[0].key = strdup(key); cur->leaf[0].val = val; tbl->root->count = 1; tbl->root->child[0] = cur; } else { find_value_(tbl, tbl->root, key, val, true); } } symbol_value_t sym_get_value(symbol_table_t tbl, const char*key) { symbol_value_t def; def.num = 0; if (tbl->root->count == 0) { /* Handle the special case that this is the very first value in the symbol table. Create the first leaf node and initialize the pointers. */ struct tree_node_*cur = new struct tree_node_; cur->leaf_flag = true; cur->parent = tbl->root; cur->count = 1; cur->leaf[0].key = strdup(key); cur->leaf[0].val = def; tbl->root->count = 1; tbl->root->child[0] = cur; return cur->leaf[0].val; } else { return find_value_(tbl, tbl->root, key, def, false); } } /* * $Log: symbols.cc,v $ * Revision 1.4 2001/11/02 04:48:03 steve * Implement split_node for symbol table (hendrik) * * Revision 1.3 2001/05/09 04:23:19 steve * Now that the interactive debugger exists, * there is no use for the output dump. * * Revision 1.2 2001/03/18 00:37:55 steve * Add support for vpi scopes. * * Revision 1.1 2001/03/11 00:29:39 steve * Add the vvp engine to cvs. * */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLTextFrameHyperlinkContext.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: hr $ $Date: 2007-06-27 16:08:40 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLTEXTFRAMECONTEXT_HXX #include "XMLTextFrameContext.hxx" #endif #ifndef _XMLTEXTFRAMEHYPERLINKCONTEXT_HXX #include "XMLTextFrameHyperlinkContext.hxx" #endif // OD 2004-04-21 #i26791# #ifndef _XMLOFF_TXTPARAIMPHINT_HXX #include <txtparaimphint.hxx> #endif using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::text; using namespace ::com::sun::star::xml::sax; using namespace ::com::sun::star::beans; using namespace ::xmloff::token; TYPEINIT1( XMLTextFrameHyperlinkContext, SvXMLImportContext ); XMLTextFrameHyperlinkContext::XMLTextFrameHyperlinkContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const Reference< XAttributeList > & xAttrList, TextContentAnchorType eATyp ) : SvXMLImportContext( rImport, nPrfx, rLName ), eDefaultAnchorType( eATyp ), bMap( sal_False ) { OUString sShow; const SvXMLTokenMap& rTokenMap = GetImport().GetTextImport()->GetTextHyperlinkAttrTokenMap(); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; i++ ) { const OUString& rAttrName = xAttrList->getNameByIndex( i ); const OUString& rValue = xAttrList->getValueByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName ); switch( rTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_TEXT_HYPERLINK_HREF: sHRef = GetImport().GetAbsoluteReference( rValue ); break; case XML_TOK_TEXT_HYPERLINK_NAME: sName = rValue; break; case XML_TOK_TEXT_HYPERLINK_TARGET_FRAME: sTargetFrameName = rValue; break; case XML_TOK_TEXT_HYPERLINK_SHOW: sShow = rValue; break; case XML_TOK_TEXT_HYPERLINK_SERVER_MAP: { sal_Bool bTmp; if( rImport.GetMM100UnitConverter().convertBool( bTmp, rValue ) ) { bMap = bTmp; } } break; } } if( sShow.getLength() && !sTargetFrameName.getLength() ) { if( IsXMLToken( sShow, XML_NEW ) ) sTargetFrameName = OUString( RTL_CONSTASCII_USTRINGPARAM("_blank" ) ); else if( IsXMLToken( sShow, XML_REPLACE ) ) sTargetFrameName = OUString( RTL_CONSTASCII_USTRINGPARAM("_self" ) ); } } XMLTextFrameHyperlinkContext::~XMLTextFrameHyperlinkContext() { } void XMLTextFrameHyperlinkContext::EndElement() { } SvXMLImportContext *XMLTextFrameHyperlinkContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; XMLTextFrameContext *pTextFrameContext = 0; if( XML_NAMESPACE_DRAW == nPrefix ) { if( IsXMLToken( rLocalName, XML_FRAME ) ) pTextFrameContext = new XMLTextFrameContext( GetImport(), nPrefix, rLocalName, xAttrList, eDefaultAnchorType ); } if( pTextFrameContext ) { pTextFrameContext->SetHyperlink( sHRef, sName, sTargetFrameName, bMap ); pContext = pTextFrameContext; xFrameContext = pContext; } else pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); return pContext; } TextContentAnchorType XMLTextFrameHyperlinkContext::GetAnchorType() const { if( xFrameContext.Is() ) { SvXMLImportContext *pContext = &xFrameContext; return PTR_CAST( XMLTextFrameContext, pContext ) ->GetAnchorType(); } else return eDefaultAnchorType; } Reference < XTextContent > XMLTextFrameHyperlinkContext::GetTextContent() const { Reference <XTextContent > xTxt; if( xFrameContext.Is() ) { SvXMLImportContext *pContext = &xFrameContext; xTxt = PTR_CAST( XMLTextFrameContext, pContext )->GetTextContent(); } return xTxt; } // --> OD 2004-08-24 #33242# Reference < drawing::XShape > XMLTextFrameHyperlinkContext::GetShape() const { Reference < drawing::XShape > xShape; if( xFrameContext.Is() ) { SvXMLImportContext *pContext = &xFrameContext; xShape = PTR_CAST( XMLTextFrameContext, pContext )->GetShape(); } return xShape; } // <-- <commit_msg>INTEGRATION: CWS impresstables2 (1.11.80); FILE MERGED 2007/08/01 14:49:34 cl 1.11.80.2: RESYNC: (1.11-1.12); FILE MERGED 2007/07/27 09:09:56 cl 1.11.80.1: fixed build issues due to pch and namespace ::rtl<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLTextFrameHyperlinkContext.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: rt $ $Date: 2008-03-12 11:02:20 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #ifndef _XMLOFF_XMLIMP_HXX #include <xmloff/xmlimp.hxx> #endif #ifndef _XMLOFF_NMSPMAP_HXX #include <xmloff/nmspmap.hxx> #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include <xmloff/xmltoken.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include <xmloff/xmluconv.hxx> #endif #ifndef _XMLTEXTFRAMECONTEXT_HXX #include "XMLTextFrameContext.hxx" #endif #ifndef _XMLTEXTFRAMEHYPERLINKCONTEXT_HXX #include "XMLTextFrameHyperlinkContext.hxx" #endif // OD 2004-04-21 #i26791# #ifndef _XMLOFF_TXTPARAIMPHINT_HXX #include <txtparaimphint.hxx> #endif using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::text; using namespace ::com::sun::star::xml::sax; using namespace ::com::sun::star::beans; using namespace ::xmloff::token; TYPEINIT1( XMLTextFrameHyperlinkContext, SvXMLImportContext ); XMLTextFrameHyperlinkContext::XMLTextFrameHyperlinkContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const Reference< XAttributeList > & xAttrList, TextContentAnchorType eATyp ) : SvXMLImportContext( rImport, nPrfx, rLName ), eDefaultAnchorType( eATyp ), bMap( sal_False ) { OUString sShow; const SvXMLTokenMap& rTokenMap = GetImport().GetTextImport()->GetTextHyperlinkAttrTokenMap(); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; i++ ) { const OUString& rAttrName = xAttrList->getNameByIndex( i ); const OUString& rValue = xAttrList->getValueByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName ); switch( rTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_TEXT_HYPERLINK_HREF: sHRef = GetImport().GetAbsoluteReference( rValue ); break; case XML_TOK_TEXT_HYPERLINK_NAME: sName = rValue; break; case XML_TOK_TEXT_HYPERLINK_TARGET_FRAME: sTargetFrameName = rValue; break; case XML_TOK_TEXT_HYPERLINK_SHOW: sShow = rValue; break; case XML_TOK_TEXT_HYPERLINK_SERVER_MAP: { sal_Bool bTmp; if( rImport.GetMM100UnitConverter().convertBool( bTmp, rValue ) ) { bMap = bTmp; } } break; } } if( sShow.getLength() && !sTargetFrameName.getLength() ) { if( IsXMLToken( sShow, XML_NEW ) ) sTargetFrameName = OUString( RTL_CONSTASCII_USTRINGPARAM("_blank" ) ); else if( IsXMLToken( sShow, XML_REPLACE ) ) sTargetFrameName = OUString( RTL_CONSTASCII_USTRINGPARAM("_self" ) ); } } XMLTextFrameHyperlinkContext::~XMLTextFrameHyperlinkContext() { } void XMLTextFrameHyperlinkContext::EndElement() { } SvXMLImportContext *XMLTextFrameHyperlinkContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; XMLTextFrameContext *pTextFrameContext = 0; if( XML_NAMESPACE_DRAW == nPrefix ) { if( IsXMLToken( rLocalName, XML_FRAME ) ) pTextFrameContext = new XMLTextFrameContext( GetImport(), nPrefix, rLocalName, xAttrList, eDefaultAnchorType ); } if( pTextFrameContext ) { pTextFrameContext->SetHyperlink( sHRef, sName, sTargetFrameName, bMap ); pContext = pTextFrameContext; xFrameContext = pContext; } else pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); return pContext; } TextContentAnchorType XMLTextFrameHyperlinkContext::GetAnchorType() const { if( xFrameContext.Is() ) { SvXMLImportContext *pContext = &xFrameContext; return PTR_CAST( XMLTextFrameContext, pContext ) ->GetAnchorType(); } else return eDefaultAnchorType; } Reference < XTextContent > XMLTextFrameHyperlinkContext::GetTextContent() const { Reference <XTextContent > xTxt; if( xFrameContext.Is() ) { SvXMLImportContext *pContext = &xFrameContext; xTxt = PTR_CAST( XMLTextFrameContext, pContext )->GetTextContent(); } return xTxt; } // --> OD 2004-08-24 #33242# Reference < drawing::XShape > XMLTextFrameHyperlinkContext::GetShape() const { Reference < drawing::XShape > xShape; if( xFrameContext.Is() ) { SvXMLImportContext *pContext = &xFrameContext; xShape = PTR_CAST( XMLTextFrameContext, pContext )->GetShape(); } return xShape; } // <-- <|endoftext|>
<commit_before>//===---------------------- SymbolicRangeAnalysis.cpp ---------------------===// //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sra" #include "SymbolicRangeAnalysis.h" #include "llvm/IR/Constants.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" raw_ostream& operator<<(raw_ostream& OS, const SymbolicRangeAnalysis& SRR) { SRR.print(OS, nullptr); return OS; } using namespace llvm; static RegisterPass<SymbolicRangeAnalysis> X("sra", "Symbolic range analysis with SAGE and QEPCAD"); char SymbolicRangeAnalysis::ID = 0; static cl::opt<bool> ShouldUseSymBounds("sra-use-sym-bounds", cl::init(false), cl::Hidden, cl::desc("Use symbolic mins & maxes for integer bounds")); const unsigned CHANGED_LOWER = 1 << 0; const unsigned CHANGED_UPPER = 1 << 1; static SAGERange GetBoundsForTy(Type *Ty, SAGEInterface *SI) { unsigned Width = Ty->getIntegerBitWidth(); if (ShouldUseSymBounds) { switch (Width) { case 8: return SAGERange(SAGEExpr(*SI, "UCHAR_MAX"), SAGEExpr(*SI, "CHAR_MIN")); case 16: return SAGERange(SAGEExpr(*SI, "USHRT_MAX"), SAGEExpr(*SI, "SHRT_MIN")); case 32: return SAGERange(SAGEExpr(*SI, "UINT_MAX"), SAGEExpr(*SI, "INT_MIN")); case 64: return SAGERange(SAGEExpr(*SI, "ULONG_MAX"), SAGEExpr(*SI, "LONG_MIN")); } } uint64_t Upper = APInt::getMaxValue(Width).getZExtValue(); int64_t Lower = APInt::getSignedMinValue(Width).getSExtValue(); return SAGERange(SAGEExpr(*SI, Upper), SAGEExpr(*SI, Lower)); } static SAGERange GetBoundsForValue(Value *V, SAGEInterface *SI) { return GetBoundsForTy(V->getType(), SI); } static SAGERange BinaryOp(BinaryOperator *BO, SymbolicRangeAnalysis *SRA) { DEBUG(dbgs() << "SRA: BinaryOp: " << *BO << "\n"); auto LHS = SRA->getStateOrInf(BO->getOperand(0)), RHS = SRA->getStateOrInf(BO->getOperand(1)); switch (BO->getOpcode()) { case Instruction::Add: return LHS + RHS; case Instruction::Sub: return LHS - RHS; case Instruction::Mul: return LHS * RHS; case Instruction::SDiv: case Instruction::UDiv: return LHS/RHS; default: return GetBoundsForValue(BO, &SRA->getSI()); } } static SAGERange Narrow(PHINode *Phi, Value *V, ICmpInst::Predicate Pred, SymbolicRangeAnalysis *SRA) { DEBUG(dbgs() << "SRA: Narrow: " << *Phi << ", " << *V << "\n"); auto Ret = SRA->getStateOrInf(Phi->getIncomingValue(0)), Bound = SRA->getState(V); std::set<SAGEExpr> Set; switch (Pred) { case CmpInst::ICMP_SLT: case CmpInst::ICMP_ULT: Ret.setUpper(Bound.getUpper() - 1); break; case CmpInst::ICMP_SLE: case CmpInst::ICMP_ULE: Ret.setUpper(Bound.getUpper()); break; case CmpInst::ICMP_SGT: case CmpInst::ICMP_UGT: Ret.setLower(Bound.getLower() + 1); break; case CmpInst::ICMP_SGE: case CmpInst::ICMP_UGE: Ret.setLower(Bound.getLower()); break; case CmpInst::ICMP_EQ: Ret = Bound; break; default: break; } return Ret; } static SAGERange Meet(PHINode *Phi, SymbolicRangeAnalysis *SRA) { DEBUG(dbgs() << "SRA: Meet: " << *Phi << "\n"); SAGERange Ret = SRA->getState(Phi->getIncomingValue(0)); auto OI = Phi->op_begin(), OE = Phi->op_end(); for (; Ret == SRA->getBottom() && OI != OE; ++OI) Ret = SRA->getState(*OI); for (; OI != OE; ++OI) { SAGERange Incoming = SRA->getState(*OI); if (Incoming == SRA->getBottom()) continue; Ret.setLower(Ret.getLower().min(Incoming.getLower())); Ret.setUpper(Ret.getUpper().max(Incoming.getUpper())); } return Ret; } void SymbolicRangeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<SAGEInterface>(); AU.addRequired<Redefinition>(); AU.setPreservesAll(); } bool SymbolicRangeAnalysis::runOnFunction(Function& F) { Module_ = F.getParent(); SI_ = &getAnalysis<SAGEInterface>(); dbgs() << "SRA: runOnModule: " << F.getName() << "\n"; RDF_ = &getAnalysis<Redefinition>(); initialize(&F); reset(&F); iterate(&F); reset(&F); iterate(&F); reset(&F); iterate(&F); widen(&F); DEBUG(dbgs() << *this << "\n"); return false; } SAGEExpr SymbolicRangeAnalysis::getBottomExpr() const { static SAGEExpr BottomExpr(*SI_, "_BOT_"); return BottomExpr; } SAGERange SymbolicRangeAnalysis::getBottom() const { static SAGERange BottomRange(getBottomExpr()); return BottomRange; } std::string SymbolicRangeAnalysis::makeName(Function *F, Value *V) { static unsigned Temp = 1; if (V->hasName()) { auto Name = (F->getName() + Twine("_") + V->getName()).str(); std::replace(Name.begin(), Name.end(), '.', '_'); return Name; } else { auto Name = F->getName() + Twine("_") + Twine(Temp++); return Name.str(); } } void SymbolicRangeAnalysis::setName(Value *V, std::string Name) { Name_[V] = Name; Value_[Name] = V; } std::string SymbolicRangeAnalysis::getName(Value *V) const { auto It = Name_.find(V); assert(It != Name_.end() && "Requested value is not in map"); return It->second; } void SymbolicRangeAnalysis::setState(Value *V, SAGERange Range) { DEBUG(dbgs() << "SRA: setState(" << *V << "," << Range << ")\n"); auto It = State_.insert(std::make_pair(V, Range)); if (!It.second) { if (It.first->second != Range) setChanged(V, It.first->second, Range); It.first->second = Range; } else if (isa<Instruction>(V)) { Changed_[V] = CHANGED_LOWER | CHANGED_UPPER; } } void SymbolicRangeAnalysis::setChanged(Value *V, SAGERange &Prev, SAGERange &New) { Changed_[V] = (Prev.getLower().isNE(New.getLower()) ? CHANGED_LOWER : 0) | (Prev.getUpper().isNE(New.getUpper()) ? CHANGED_UPPER : 0); } SAGERange SymbolicRangeAnalysis::getState(Value *V) const { // TODO: Handle ptrtoint. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) return SAGEExpr(*SI_, CI->getValue().getSExtValue()); if (isa<UndefValue>(V) || isa<Constant>(V)) return GetBoundsForValue(V, SI_); auto It = State_.find(V); assert(It != State_.end() && "Requested value is not in map"); return It->second; } SAGERange SymbolicRangeAnalysis::getStateOrInf(Value *V) const { auto State = getState(V); return State != getBottom() ? State : GetBoundsForTy(cast<IntegerType>(V->getType()), SI_); } std::pair<Value*, Value*> SymbolicRangeAnalysis::getRangeValuesFor(Value *V, IRBuilder<> IRB) const { SAGERange Range = getStateOrInf(V); IntegerType *Ty = cast<IntegerType>(V->getType()); Value *Lower = Range.getLower().toValue(Ty, IRB, Value_, Module_), *Upper = Range.getUpper().toValue(Ty, IRB, Value_, Module_); return std::make_pair(Lower, Upper); } void SymbolicRangeAnalysis::createNarrowingFn(Value *LHS, Value *RHS, CmpInst::Predicate Pred, BasicBlock *BB) { if (auto Redef = RDF_->getRedef(LHS, BB)) Fn_[Redef] = [Redef, RHS, Pred, this] () { return Narrow(Redef, RHS, Pred, this); }; } void SymbolicRangeAnalysis::handleBranch(BranchInst *BI, ICmpInst *ICI) { Value *LHS = ICI->getOperand(0), *RHS = ICI->getOperand(1); BasicBlock *TB = BI->getSuccessor(0), *FB = BI->getSuccessor(1); CmpInst::Predicate Pred = ICI->getPredicate(), SwapPred = ICI->getSwappedPredicate(), InvPred = ICI->getInversePredicate(), EqPred; // For (i < j) branching to cond.true and cond.false, for example: // 1) i < j at cond.true; createNarrowingFn(LHS, RHS, Pred, TB); // 2) j > i at cond.true; createNarrowingFn(RHS, LHS, SwapPred, TB); // 3) i >= j at cond.false; createNarrowingFn(LHS, RHS, InvPred, FB); if (ICI->isEquality()) EqPred = Pred; else if (ICI->isTrueWhenEqual()) EqPred = (ICmpInst::Predicate)(Pred - 1); else if (ICI->isFalseWhenEqual()) EqPred = (ICmpInst::Predicate)(Pred + 1); // 4) j <= i at cond.false; createNarrowingFn(RHS, LHS, EqPred, FB); } void SymbolicRangeAnalysis::handleIntInst(Instruction *I) { setName(I, makeName(I->getParent()->getParent(), I)); if (isa<LoadInst>(I)) setState(I, GetBoundsForValue(I, SI_)); else setState(I, getBottom()); switch (I->getOpcode()) { case Instruction::Add: case Instruction::Sub: case Instruction::Mul: case Instruction::SDiv: case Instruction::UDiv: Fn_[I] = [I, this] () { return BinaryOp(cast<BinaryOperator>(I), this); }; break; case Instruction::PHI: if (!Fn_.count(I)) Fn_[I] = [I, this] () { return Meet(cast<PHINode>(I), this); }; break; case Instruction::Trunc: case Instruction::ZExt: case Instruction::SExt: Fn_[I] = [I, this] () { return this->getState(*I->op_begin()); }; break; default: return; } } void SymbolicRangeAnalysis::initialize(Function *F) { // Create symbols for the function's integer arguments. for (auto AI = F->arg_begin(), AE = F->arg_end(); AI != AE; ++AI) if (AI->getType()->isIntegerTy()) { std::string Name = makeName(F, &(*AI)); setName(&(*AI), Name); SAGEExpr Arg(*SI_, Name.c_str()); // Range is symbolic - [Arg, Arg]. setState(&(*AI), SAGERange(Arg)); } // Create a closure for each instruction. for (auto &BB : *F) { // Handle sigma nodes. TerminatorInst *TI = BB.getTerminator(); if (BranchInst *BI = dyn_cast<BranchInst>(TI)) if (BI->isConditional()) if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) handleBranch(BI, ICI); // Handle everything that's not a sigma node. for (auto &I : BB) if (I.getType()->isIntegerTy()) { Mapping_[&I] = Mapping_.size() + 1; handleIntInst(&I); } } } void SymbolicRangeAnalysis::reset(Function *F) { for (auto &BB : *F) for (auto &I : BB) if (Changed_.count(&I) && Changed_[&I]) Worklist_.insert(std::make_pair(Mapping_[&I], &I)); Evaled_.clear(); Changed_.clear(); } void SymbolicRangeAnalysis::iterate(Function *F) { DEBUG(dbgs() << "SRA: Iterate\n"); while (!Worklist_.empty()) { auto Next = Worklist_.begin(); Worklist_.erase(Next); Instruction *I = Next->second; if (Fn_.count(I) && !Evaled_.count(I)) { Evaled_.insert(I); setState(I, Fn_[I]()); for (auto UI = I->use_begin(), UE = I->use_end(); UI != UE; ++UI) if (Instruction *Use = dyn_cast<Instruction>(*UI)) if (!Evaled_.count(Use)) Worklist_.insert(std::make_pair(Mapping_[Use], Use)); } } } void SymbolicRangeAnalysis::widen(Function *F) { DEBUG(dbgs() << "SRA: Widen\n"); for (auto &BB : *F) for (auto &I : BB) if (I.getType()->isIntegerTy()) if (Changed_.count(&I) && Changed_[&I]) { auto State = getStateOrInf(&I); auto Bounds = GetBoundsForValue(&I, SI_); if (Changed_[&I] & CHANGED_LOWER) State.setLower(Bounds.getLower()); if (Changed_[&I] & CHANGED_UPPER) State.setUpper(Bounds.getUpper()); setState(&I, State); } } void SymbolicRangeAnalysis::print(raw_ostream &OS, const Module*) const { for (auto P : State_) OS << "[[" << getName(P.first) << "]] = " << P.second << "\n"; } <commit_msg>Add sra-max-phi-eval-size CL flag<commit_after>//===---------------------- SymbolicRangeAnalysis.cpp ---------------------===// //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sra" #include "SymbolicRangeAnalysis.h" #include "llvm/IR/Constants.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" raw_ostream& operator<<(raw_ostream& OS, const SymbolicRangeAnalysis& SRR) { SRR.print(OS, nullptr); return OS; } using namespace llvm; static RegisterPass<SymbolicRangeAnalysis> X("sra", "Symbolic range analysis with SAGE and QEPCAD"); char SymbolicRangeAnalysis::ID = 0; static cl::opt<bool> ShouldUseSymBounds("sra-use-sym-bounds", cl::init(false), cl::Hidden, cl::desc("Use symbolic mins & maxes for integer bounds")); static cl::opt<int> MaxPhiEvalSize("sra-max-phi-eval-size", cl::init(-1), cl::Hidden, cl::desc("Maximum number of operands on phi nodes, phi nodes which" "have more will not be evaluated")); const unsigned CHANGED_LOWER = 1 << 0; const unsigned CHANGED_UPPER = 1 << 1; static SAGERange GetBoundsForTy(Type *Ty, SAGEInterface *SI) { unsigned Width = Ty->getIntegerBitWidth(); if (ShouldUseSymBounds) { switch (Width) { case 8: return SAGERange(SAGEExpr(*SI, "UCHAR_MAX"), SAGEExpr(*SI, "CHAR_MIN")); case 16: return SAGERange(SAGEExpr(*SI, "USHRT_MAX"), SAGEExpr(*SI, "SHRT_MIN")); case 32: return SAGERange(SAGEExpr(*SI, "UINT_MAX"), SAGEExpr(*SI, "INT_MIN")); case 64: return SAGERange(SAGEExpr(*SI, "ULONG_MAX"), SAGEExpr(*SI, "LONG_MIN")); } } uint64_t Upper = APInt::getMaxValue(Width).getZExtValue(); int64_t Lower = APInt::getSignedMinValue(Width).getSExtValue(); return SAGERange(SAGEExpr(*SI, Upper), SAGEExpr(*SI, Lower)); } static SAGERange GetBoundsForValue(Value *V, SAGEInterface *SI) { return GetBoundsForTy(V->getType(), SI); } static SAGERange BinaryOp(BinaryOperator *BO, SymbolicRangeAnalysis *SRA) { DEBUG(dbgs() << "SRA: BinaryOp: " << *BO << "\n"); auto LHS = SRA->getStateOrInf(BO->getOperand(0)), RHS = SRA->getStateOrInf(BO->getOperand(1)); switch (BO->getOpcode()) { case Instruction::Add: return LHS + RHS; case Instruction::Sub: return LHS - RHS; case Instruction::Mul: return LHS * RHS; case Instruction::SDiv: case Instruction::UDiv: return LHS/RHS; default: return GetBoundsForValue(BO, &SRA->getSI()); } } static SAGERange Narrow(PHINode *Phi, Value *V, ICmpInst::Predicate Pred, SymbolicRangeAnalysis *SRA) { DEBUG(dbgs() << "SRA: Narrow: " << *Phi << ", " << *V << "\n"); auto Ret = SRA->getStateOrInf(Phi->getIncomingValue(0)), Bound = SRA->getState(V); std::set<SAGEExpr> Set; switch (Pred) { case CmpInst::ICMP_SLT: case CmpInst::ICMP_ULT: Ret.setUpper(Bound.getUpper() - 1); break; case CmpInst::ICMP_SLE: case CmpInst::ICMP_ULE: Ret.setUpper(Bound.getUpper()); break; case CmpInst::ICMP_SGT: case CmpInst::ICMP_UGT: Ret.setLower(Bound.getLower() + 1); break; case CmpInst::ICMP_SGE: case CmpInst::ICMP_UGE: Ret.setLower(Bound.getLower()); break; case CmpInst::ICMP_EQ: Ret = Bound; break; default: break; } return Ret; } static SAGERange Meet(PHINode *Phi, SymbolicRangeAnalysis *SRA) { DEBUG(dbgs() << "SRA: Meet: " << *Phi << "\n"); if (MaxPhiEvalSize > 0 && Phi->getNumOperands() > (unsigned) MaxPhiEvalSize) { SAGERange Ret = GetBoundsForTy(cast<IntegerType>(Phi->getType()), &SRA->getSI()); Ret.setLower(Ret.getLower()); Ret.setUpper(Ret.getUpper()); return Ret; } SAGERange Ret = SRA->getState(Phi->getIncomingValue(0)); auto OI = Phi->op_begin(), OE = Phi->op_end(); for (; Ret == SRA->getBottom() && OI != OE; ++OI) Ret = SRA->getState(*OI); for (; OI != OE; ++OI) { SAGERange Incoming = SRA->getState(*OI); if (Incoming == SRA->getBottom()) continue; Ret.setLower(Ret.getLower().min(Incoming.getLower())); Ret.setUpper(Ret.getUpper().max(Incoming.getUpper())); } return Ret; } void SymbolicRangeAnalysis::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<SAGEInterface>(); AU.addRequired<Redefinition>(); AU.setPreservesAll(); } bool SymbolicRangeAnalysis::runOnFunction(Function& F) { Module_ = F.getParent(); SI_ = &getAnalysis<SAGEInterface>(); dbgs() << "SRA: runOnModule: " << F.getName() << "\n"; RDF_ = &getAnalysis<Redefinition>(); initialize(&F); reset(&F); iterate(&F); reset(&F); iterate(&F); reset(&F); iterate(&F); widen(&F); DEBUG(dbgs() << *this << "\n"); return false; } SAGEExpr SymbolicRangeAnalysis::getBottomExpr() const { static SAGEExpr BottomExpr(*SI_, "_BOT_"); return BottomExpr; } SAGERange SymbolicRangeAnalysis::getBottom() const { static SAGERange BottomRange(getBottomExpr()); return BottomRange; } std::string SymbolicRangeAnalysis::makeName(Function *F, Value *V) { static unsigned Temp = 1; if (V->hasName()) { auto Name = (F->getName() + Twine("_") + V->getName()).str(); std::replace(Name.begin(), Name.end(), '.', '_'); return Name; } else { auto Name = F->getName() + Twine("_") + Twine(Temp++); return Name.str(); } } void SymbolicRangeAnalysis::setName(Value *V, std::string Name) { Name_[V] = Name; Value_[Name] = V; } std::string SymbolicRangeAnalysis::getName(Value *V) const { auto It = Name_.find(V); assert(It != Name_.end() && "Requested value is not in map"); return It->second; } void SymbolicRangeAnalysis::setState(Value *V, SAGERange Range) { DEBUG(dbgs() << "SRA: setState(" << *V << "," << Range << ")\n"); auto It = State_.insert(std::make_pair(V, Range)); if (!It.second) { if (It.first->second != Range) setChanged(V, It.first->second, Range); It.first->second = Range; } else if (isa<Instruction>(V)) { Changed_[V] = CHANGED_LOWER | CHANGED_UPPER; } } void SymbolicRangeAnalysis::setChanged(Value *V, SAGERange &Prev, SAGERange &New) { Changed_[V] = (Prev.getLower().isNE(New.getLower()) ? CHANGED_LOWER : 0) | (Prev.getUpper().isNE(New.getUpper()) ? CHANGED_UPPER : 0); } SAGERange SymbolicRangeAnalysis::getState(Value *V) const { // TODO: Handle ptrtoint. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) return SAGEExpr(*SI_, CI->getValue().getSExtValue()); if (isa<UndefValue>(V) || isa<Constant>(V)) return GetBoundsForValue(V, SI_); auto It = State_.find(V); assert(It != State_.end() && "Requested value is not in map"); return It->second; } SAGERange SymbolicRangeAnalysis::getStateOrInf(Value *V) const { auto State = getState(V); return State != getBottom() ? State : GetBoundsForTy(cast<IntegerType>(V->getType()), SI_); } std::pair<Value*, Value*> SymbolicRangeAnalysis::getRangeValuesFor(Value *V, IRBuilder<> IRB) const { SAGERange Range = getStateOrInf(V); IntegerType *Ty = cast<IntegerType>(V->getType()); Value *Lower = Range.getLower().toValue(Ty, IRB, Value_, Module_), *Upper = Range.getUpper().toValue(Ty, IRB, Value_, Module_); return std::make_pair(Lower, Upper); } void SymbolicRangeAnalysis::createNarrowingFn(Value *LHS, Value *RHS, CmpInst::Predicate Pred, BasicBlock *BB) { if (auto Redef = RDF_->getRedef(LHS, BB)) Fn_[Redef] = [Redef, RHS, Pred, this] () { return Narrow(Redef, RHS, Pred, this); }; } void SymbolicRangeAnalysis::handleBranch(BranchInst *BI, ICmpInst *ICI) { Value *LHS = ICI->getOperand(0), *RHS = ICI->getOperand(1); BasicBlock *TB = BI->getSuccessor(0), *FB = BI->getSuccessor(1); CmpInst::Predicate Pred = ICI->getPredicate(), SwapPred = ICI->getSwappedPredicate(), InvPred = ICI->getInversePredicate(), EqPred; // For (i < j) branching to cond.true and cond.false, for example: // 1) i < j at cond.true; createNarrowingFn(LHS, RHS, Pred, TB); // 2) j > i at cond.true; createNarrowingFn(RHS, LHS, SwapPred, TB); // 3) i >= j at cond.false; createNarrowingFn(LHS, RHS, InvPred, FB); if (ICI->isEquality()) EqPred = Pred; else if (ICI->isTrueWhenEqual()) EqPred = (ICmpInst::Predicate)(Pred - 1); else if (ICI->isFalseWhenEqual()) EqPred = (ICmpInst::Predicate)(Pred + 1); // 4) j <= i at cond.false; createNarrowingFn(RHS, LHS, EqPred, FB); } void SymbolicRangeAnalysis::handleIntInst(Instruction *I) { setName(I, makeName(I->getParent()->getParent(), I)); if (isa<LoadInst>(I)) setState(I, GetBoundsForValue(I, SI_)); else setState(I, getBottom()); switch (I->getOpcode()) { case Instruction::Add: case Instruction::Sub: case Instruction::Mul: case Instruction::SDiv: case Instruction::UDiv: Fn_[I] = [I, this] () { return BinaryOp(cast<BinaryOperator>(I), this); }; break; case Instruction::PHI: if (!Fn_.count(I)) Fn_[I] = [I, this] () { return Meet(cast<PHINode>(I), this); }; break; case Instruction::Trunc: case Instruction::ZExt: case Instruction::SExt: Fn_[I] = [I, this] () { return this->getState(*I->op_begin()); }; break; default: return; } } void SymbolicRangeAnalysis::initialize(Function *F) { // Create symbols for the function's integer arguments. for (auto AI = F->arg_begin(), AE = F->arg_end(); AI != AE; ++AI) if (AI->getType()->isIntegerTy()) { std::string Name = makeName(F, &(*AI)); setName(&(*AI), Name); SAGEExpr Arg(*SI_, Name.c_str()); // Range is symbolic - [Arg, Arg]. setState(&(*AI), SAGERange(Arg)); } // Create a closure for each instruction. for (auto &BB : *F) { // Handle sigma nodes. TerminatorInst *TI = BB.getTerminator(); if (BranchInst *BI = dyn_cast<BranchInst>(TI)) if (BI->isConditional()) if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) handleBranch(BI, ICI); // Handle everything that's not a sigma node. for (auto &I : BB) if (I.getType()->isIntegerTy()) { Mapping_[&I] = Mapping_.size() + 1; handleIntInst(&I); } } } void SymbolicRangeAnalysis::reset(Function *F) { for (auto &BB : *F) for (auto &I : BB) if (Changed_.count(&I) && Changed_[&I]) Worklist_.insert(std::make_pair(Mapping_[&I], &I)); Evaled_.clear(); Changed_.clear(); } void SymbolicRangeAnalysis::iterate(Function *F) { DEBUG(dbgs() << "SRA: Iterate\n"); while (!Worklist_.empty()) { auto Next = Worklist_.begin(); Worklist_.erase(Next); Instruction *I = Next->second; if (Fn_.count(I) && !Evaled_.count(I)) { Evaled_.insert(I); setState(I, Fn_[I]()); for (auto UI = I->use_begin(), UE = I->use_end(); UI != UE; ++UI) if (Instruction *Use = dyn_cast<Instruction>(*UI)) if (!Evaled_.count(Use)) Worklist_.insert(std::make_pair(Mapping_[Use], Use)); } } } void SymbolicRangeAnalysis::widen(Function *F) { DEBUG(dbgs() << "SRA: Widen\n"); for (auto &BB : *F) for (auto &I : BB) if (I.getType()->isIntegerTy()) if (Changed_.count(&I) && Changed_[&I]) { auto State = getStateOrInf(&I); auto Bounds = GetBoundsForValue(&I, SI_); if (Changed_[&I] & CHANGED_LOWER) State.setLower(Bounds.getLower()); if (Changed_[&I] & CHANGED_UPPER) State.setUpper(Bounds.getUpper()); setState(&I, State); } } void SymbolicRangeAnalysis::print(raw_ostream &OS, const Module*) const { for (auto P : State_) OS << "[[" << getName(P.first) << "]] = " << P.second << "\n"; } <|endoftext|>
<commit_before>// weather_file.C #include "weather.h" #include "syntax.h" #include "alist.h" #include "common.h" #include "log.h" #include "filter.h" #include <algobase.h> #include <fstream.h> class WeatherFile : public Weather { Time date; const string file_name; ifstream file; const double T1; const double T2; const vector<double>& A; const vector<double>& B; double precipitation; double reference_evapotranspiration; double global_radiation; double air_temperature; double Prain; double Psnow; int line; // Simulation. public: void tick (); void output (const string, Log&, const Filter&) const; double AirTemperature () const; double GlobalRadiation () const; double ReferenceEvapotranspiration () const; double Precipitation () const; double Rain () const; double Snow () const; // Create and Destroy. private: friend class WeatherFileSyntax; static Weather& make (const Time&, const AttributeList&); WeatherFile (const Time&, const AttributeList&); public: ~WeatherFile (); }; void WeatherFile::tick () { if (!file.good ()) { cerr << file_name << ":" << line << ": file error"; THROW ("read error"); } int year; int month; int day; char end; while (date < time) { file >> year >> month >> day >> global_radiation >> air_temperature >> precipitation >> end; if (year < 100) year += 1900; while (file.good () && strchr ("\n \t", end)) file >> end; if (end == '\n') reference_evapotranspiration = -42.42e42; else { file >> reference_evapotranspiration; while (file.good () && file.get () != '\n') /* do nothing */; } date = Time (year, month, day, 23); } if (AirTemperature () < T1) Psnow = Precipitation (); else if (T2 < AirTemperature ()) Psnow = 0.0; else Psnow = Precipitation () * (T2 - AirTemperature ()) / (T2 - T1); Prain = Precipitation () - Snow (); } void WeatherFile::output (const string name, Log& log, const Filter& filter) const { if (filter.check (name)) { const Filter& f1 = filter.lookup (name); if (f1.check ("file")) { const Filter& f2 = f1.lookup ("file"); log.open (name, "file"); log.output ("Prain", f2, Prain, true); log.output ("Psnow", f2, Psnow, true); log.close (); } } } double WeatherFile::AirTemperature (void) const // [C] { // BUG: No variation over the day? double t = 2.0 * M_PI / 365.0 * time.yday (); return (7.7 - 7.7 * cos (t) - 3.6 * sin (t)); } double WeatherFile::GlobalRadiation () const // [W/m^2] { /*a function of the weather*/ static const double A0[] = { 17.0, 44.0, 94.0, 159.0, 214.0, 247.0, 214.0, 184.0, 115.0, 58.0, 25.0, 13.0 }; static const double A1[] = { -31.0, -74.0, -148.0, -232.0, -291.0, -320.0, -279.0, -261.0, -177.0, -96.0, -45.0, -24.0 }; static const double B1[] = { -7.0, -20.0, -34.0, -45.0, -53.0, -63.0, -67.0, -52.0, -30.0, -13.0, -6.0, -4.0 }; static const double A2[] = { 21.0, 42.0, 68.0, 77.0, 67.0, 0.0, 0.0, 75.0, 73.0, 54.0, 32.0, 18.0 }; static const double B2[] = { 11.0, 25.0, 32.0, 29.0, 23.0, 0.0, 0.0, 29.0, 25.0, 15.0, 8.0, 7.0 }; double t = 2.0 * M_PI / 24.0 * time.hour (); int m = time.month () - 1; double Si = ( A0[m] + A1[m] * cos (t) + B1[m] * sin (t) + A2[m] * cos (2 * t) + B2[m] * sin (2 * t)); return max (0.0, Si * (global_radiation / A0[m])); } double WeatherFile::ReferenceEvapotranspiration () const // [mm/h] { if (reference_evapotranspiration < 0) { const double T = 273.16 + AirTemperature (); const double Delta = 5362.7 / pow (T, 2) * exp (26.042 - 5362.7 / T); return 1.05e-3 * Delta / (Delta + 66.7) * GlobalRadiation (); } int m = time.month () - 1; int h = time.hour (); return reference_evapotranspiration * (1.0 + A[m] * cos (2.0 * M_PI / 24.0 * h) + B[m] * sin (2.0 * M_PI / 24.0 * h)); } double WeatherFile::Precipitation () const { return precipitation / 24.0; } double WeatherFile::Rain () const { return Prain; } double WeatherFile::Snow () const { return Psnow; } WeatherFile::WeatherFile (const Time& t, const AttributeList& al) : Weather (t, al.number ("Latitude")), date (42, 1, 1, 0), file_name (al.name ("file")), file (al.name ("file").c_str()), T1 (al.number ("T1")), T2 (al.number ("T2")), A (al.number_sequence ("A")), B (al.number_sequence ("B")), precipitation (-42.42e42), reference_evapotranspiration (-42.42e42), global_radiation (-42.42e42), Prain (-42.42e42), Psnow (-42.42e42) { } WeatherFile::~WeatherFile () { } // Add the WeatherFile syntax to the syntax table. Weather& WeatherFile::make (const Time& t, const AttributeList& al) { return *new WeatherFile (t, al); } static struct WeatherFileSyntax { WeatherFileSyntax (); } WeatherFile_syntax; WeatherFileSyntax::WeatherFileSyntax () { static const double A[] = { -0.916667, -1.687500, -1.681818, -1.468085, -1.387324, -1.377246, -1.389937, -1.518519, -1.629630, -1.631579, -1.333333, -0.900000 }; static const double B[] = { -0.166667, -0.437500, -0.454545, -0.382979, -0.338028, -0.335329, -0.389937, -0.407407, -0.358025, -0.236842, -0.166667, -0.200000 }; Syntax& syntax = *new Syntax (); AttributeList& alist = *new AttributeList (); syntax.add ("Latitude", Syntax::Number, Syntax::Const); alist.add ("Latitude", 56.0); syntax.add ("file", Syntax::String, Syntax::Const); syntax.add ("T1", Syntax::Number, Syntax::Const); alist.add ("T1", -2.0); syntax.add ("T2", Syntax::Number, Syntax::Const); alist.add ("T2", 2.0); syntax.add ("A", Syntax::Number, Syntax::Const, 12); syntax.add ("B", Syntax::Number, Syntax::Const, 12); vector<double>& a = *new vector<double>; vector<double>& b = *new vector<double>; for (int i = 0; i < 12; i++) { a.push_back (A[i]); b.push_back (B[i]); } alist.add ("A", a); alist.add ("B", b); syntax.add ("Prain", Syntax::Number, Syntax::LogOnly); syntax.add ("Psnow", Syntax::Number, Syntax::LogOnly); syntax.order ("file"); Weather::add_type ("file", alist, syntax, &WeatherFile::make); } <commit_msg>Runs test.dai<commit_after>// weather_file.C #include "weather.h" #include "syntax.h" #include "alist.h" #include "common.h" #include "log.h" #include "filter.h" #include <algobase.h> #include <fstream.h> class WeatherFile : public Weather { Time date; const string file_name; ifstream file; const double T1; const double T2; const vector<double>& A; const vector<double>& B; double precipitation; double reference_evapotranspiration; double global_radiation; double air_temperature; double Prain; double Psnow; int line; // Simulation. public: void tick (); void output (const string, Log&, const Filter&) const; double AirTemperature () const; double GlobalRadiation () const; double ReferenceEvapotranspiration () const; double Precipitation () const; double Rain () const; double Snow () const; // Create and Destroy. private: friend class WeatherFileSyntax; static Weather& make (const Time&, const AttributeList&); WeatherFile (const Time&, const AttributeList&); public: ~WeatherFile (); }; void WeatherFile::tick () { if (!file.good ()) { cerr << file_name << ":" << line << ": file error"; THROW ("read error"); } int year; int month; int day; char end; while (date < time) { file >> year >> month >> day >> global_radiation >> air_temperature >> precipitation >> end; if (year < 100) year += 1900; while (file.good () && strchr ("\n \t", end)) file >> end; if (end == '\n') reference_evapotranspiration = -42.42e42; else { file >> reference_evapotranspiration; while (file.good () && file.get () != '\n') /* do nothing */; } date = Time (year, month, day, 23); } if (AirTemperature () < T1) Psnow = Precipitation (); else if (T2 < AirTemperature ()) Psnow = 0.0; else Psnow = Precipitation () * (T2 - AirTemperature ()) / (T2 - T1); Prain = Precipitation () - Snow (); } void WeatherFile::output (const string name, Log& log, const Filter& filter) const { if (filter.check (name)) { const Filter& f1 = filter.lookup (name); if (f1.check ("file")) { const Filter& f2 = f1.lookup ("file"); log.open (name, "file"); log.output ("Prain", f2, Prain, true); log.output ("Psnow", f2, Psnow, true); log.close (); } } } double WeatherFile::AirTemperature (void) const // [C] { // BUG: No variation over the day? return air_temperature; } double WeatherFile::GlobalRadiation () const // [W/m^2] { /*a function of the weather*/ static const double A0[] = { 17.0, 44.0, 94.0, 159.0, 214.0, 247.0, 214.0, 184.0, 115.0, 58.0, 25.0, 13.0 }; static const double A1[] = { -31.0, -74.0, -148.0, -232.0, -291.0, -320.0, -279.0, -261.0, -177.0, -96.0, -45.0, -24.0 }; static const double B1[] = { -7.0, -20.0, -34.0, -45.0, -53.0, -63.0, -67.0, -52.0, -30.0, -13.0, -6.0, -4.0 }; static const double A2[] = { 21.0, 42.0, 68.0, 77.0, 67.0, 0.0, 0.0, 75.0, 73.0, 54.0, 32.0, 18.0 }; static const double B2[] = { 11.0, 25.0, 32.0, 29.0, 23.0, 0.0, 0.0, 29.0, 25.0, 15.0, 8.0, 7.0 }; double t = 2.0 * M_PI / 24.0 * time.hour (); int m = time.month () - 1; double Si = ( A0[m] + A1[m] * cos (t) + B1[m] * sin (t) + A2[m] * cos (2 * t) + B2[m] * sin (2 * t)); return max (0.0, Si * (global_radiation / A0[m])); } double WeatherFile::ReferenceEvapotranspiration () const // [mm/h] { if (reference_evapotranspiration < 0) { const double T = 273.16 + AirTemperature (); const double Delta = 5362.7 / pow (T, 2) * exp (26.042 - 5362.7 / T); return 1.05e-3 * Delta / (Delta + 66.7) * GlobalRadiation (); } int m = time.month () - 1; int h = time.hour (); return reference_evapotranspiration * (1.0 + A[m] * cos (2.0 * M_PI / 24.0 * h) + B[m] * sin (2.0 * M_PI / 24.0 * h)); } double WeatherFile::Precipitation () const { return precipitation / 24.0; } double WeatherFile::Rain () const { return Prain; } double WeatherFile::Snow () const { return Psnow; } WeatherFile::WeatherFile (const Time& t, const AttributeList& al) : Weather (t, al.number ("Latitude")), date (42, 1, 1, 0), file_name (al.name ("file")), file (al.name ("file").c_str()), T1 (al.number ("T1")), T2 (al.number ("T2")), A (al.number_sequence ("A")), B (al.number_sequence ("B")), precipitation (-42.42e42), reference_evapotranspiration (-42.42e42), global_radiation (-42.42e42), Prain (-42.42e42), Psnow (-42.42e42) { } WeatherFile::~WeatherFile () { } // Add the WeatherFile syntax to the syntax table. Weather& WeatherFile::make (const Time& t, const AttributeList& al) { return *new WeatherFile (t, al); } static struct WeatherFileSyntax { WeatherFileSyntax (); } WeatherFile_syntax; WeatherFileSyntax::WeatherFileSyntax () { static const double A[] = { -0.916667, -1.687500, -1.681818, -1.468085, -1.387324, -1.377246, -1.389937, -1.518519, -1.629630, -1.631579, -1.333333, -0.900000 }; static const double B[] = { -0.166667, -0.437500, -0.454545, -0.382979, -0.338028, -0.335329, -0.389937, -0.407407, -0.358025, -0.236842, -0.166667, -0.200000 }; Syntax& syntax = *new Syntax (); AttributeList& alist = *new AttributeList (); syntax.add ("Latitude", Syntax::Number, Syntax::Const); alist.add ("Latitude", 56.0); syntax.add ("file", Syntax::String, Syntax::Const); syntax.add ("T1", Syntax::Number, Syntax::Const); alist.add ("T1", -2.0); syntax.add ("T2", Syntax::Number, Syntax::Const); alist.add ("T2", 2.0); syntax.add ("A", Syntax::Number, Syntax::Const, 12); syntax.add ("B", Syntax::Number, Syntax::Const, 12); vector<double>& a = *new vector<double>; vector<double>& b = *new vector<double>; for (int i = 0; i < 12; i++) { a.push_back (A[i]); b.push_back (B[i]); } alist.add ("A", a); alist.add ("B", b); syntax.add ("Prain", Syntax::Number, Syntax::LogOnly); syntax.add ("Psnow", Syntax::Number, Syntax::LogOnly); syntax.order ("file"); Weather::add_type ("file", alist, syntax, &WeatherFile::make); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLTextFrameHyperlinkContext.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: mib $ $Date: 2002-01-17 11:13:08 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _XMLTEXTFRAMECONTEXT_HXX #include "XMLTextFrameContext.hxx" #endif #ifndef _XMLTEXTFRAMEHYPERLINKCONTEXT_HXX #include "XMLTextFrameHyperlinkContext.hxx" #endif using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::text; using namespace ::com::sun::star::xml::sax; using namespace ::com::sun::star::beans; using namespace ::xmloff::token; TYPEINIT1( XMLTextFrameHyperlinkContext, SvXMLImportContext ); XMLTextFrameHyperlinkContext::XMLTextFrameHyperlinkContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const Reference< XAttributeList > & xAttrList, TextContentAnchorType eATyp, Reference < XTextContent> *pTxtCntnt, TextContentAnchorType *pAnchrType ) : SvXMLImportContext( rImport, nPrfx, rLName ), eAnchorType( eATyp ), pTextContent( pTxtCntnt ), pAnchorType( pAnchrType ), bMap( sal_False ) { OUString sShow; const SvXMLTokenMap& rTokenMap = GetImport().GetTextImport()->GetTextHyperlinkAttrTokenMap(); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; i++ ) { const OUString& rAttrName = xAttrList->getNameByIndex( i ); const OUString& rValue = xAttrList->getValueByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName ); switch( rTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_TEXT_HYPERLINK_HREF: sHRef = GetImport().GetAbsoluteReference( rValue ); break; case XML_TOK_TEXT_HYPERLINK_NAME: sName = rValue; break; case XML_TOK_TEXT_HYPERLINK_TARGET_FRAME: sTargetFrameName = rValue; break; case XML_TOK_TEXT_HYPERLINK_SHOW: sShow = rValue; break; case XML_TOK_TEXT_HYPERLINK_SERVER_MAP: { sal_Bool bTmp; if( rImport.GetMM100UnitConverter().convertBool( bTmp, rValue ) ) { bMap = bTmp; } } break; } } if( sShow.getLength() && !sTargetFrameName.getLength() ) { if( IsXMLToken( sShow, XML_NEW ) ) sTargetFrameName = OUString( RTL_CONSTASCII_USTRINGPARAM("_blank" ) ); else if( IsXMLToken( sShow, XML_REPLACE ) ) sTargetFrameName = OUString( RTL_CONSTASCII_USTRINGPARAM("_self" ) ); } } XMLTextFrameHyperlinkContext::~XMLTextFrameHyperlinkContext() { } void XMLTextFrameHyperlinkContext::EndElement() { } SvXMLImportContext *XMLTextFrameHyperlinkContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; XMLTextFrameContext *pTextFrameContext = 0; if( XML_NAMESPACE_DRAW == nPrefix ) { sal_uInt16 nFrameType = USHRT_MAX; if( IsXMLToken( rLocalName, XML_TEXT_BOX ) ) nFrameType = XML_TEXT_FRAME_TEXTBOX; else if( IsXMLToken( rLocalName, XML_IMAGE ) ) nFrameType = XML_TEXT_FRAME_GRAPHIC; else if( IsXMLToken( rLocalName, XML_OBJECT ) ) nFrameType = XML_TEXT_FRAME_OBJECT; else if( IsXMLToken( rLocalName, XML_OBJECT_OLE ) ) nFrameType = XML_TEXT_FRAME_OBJECT_OLE; else if( IsXMLToken( rLocalName, XML_APPLET) ) nFrameType = XML_TEXT_FRAME_APPLET; else if( IsXMLToken( rLocalName, XML_PLUGIN ) ) nFrameType = XML_TEXT_FRAME_PLUGIN; else if( IsXMLToken( rLocalName, XML_FLOATING_FRAME ) ) nFrameType = XML_TEXT_FRAME_FLOATING_FRAME; if( USHRT_MAX != nFrameType ) pTextFrameContext = new XMLTextFrameContext( GetImport(), nPrefix, rLocalName, xAttrList, eAnchorType, nFrameType ); } if( pTextFrameContext ) { pTextFrameContext->SetHyperlink( sHRef, sName, sTargetFrameName, bMap ); if( pAnchorType ) *pAnchorType = pTextFrameContext->GetAnchorType(); if( pTextContent ) *pTextContent = pTextFrameContext->GetTextContent(); pContext = pTextFrameContext; } else pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); return pContext; } <commit_msg>INTEGRATION: CWS swdrawpositioning (1.6.274); FILE MERGED 2004/04/22 13:40:14 od 1.6.274.1: #i26791# - adjustments for the unification of the positioning of Writer fly frames and drawing objects.<commit_after>/************************************************************************* * * $RCSfile: XMLTextFrameHyperlinkContext.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hjs $ $Date: 2004-06-28 13:53:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _XMLTEXTFRAMECONTEXT_HXX #include "XMLTextFrameContext.hxx" #endif #ifndef _XMLTEXTFRAMEHYPERLINKCONTEXT_HXX #include "XMLTextFrameHyperlinkContext.hxx" #endif // OD 2004-04-21 #i26791# #ifndef _XMLOFF_TXTPARAIMPHINT_HXX #include <txtparaimphint.hxx> #endif using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::text; using namespace ::com::sun::star::xml::sax; using namespace ::com::sun::star::beans; using namespace ::xmloff::token; TYPEINIT1( XMLTextFrameHyperlinkContext, SvXMLImportContext ); XMLTextFrameHyperlinkContext::XMLTextFrameHyperlinkContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLName, const Reference< XAttributeList > & xAttrList, TextContentAnchorType eATyp, // OD 2004-04-20 #i26791# XMLTextFrameHint_Impl* pTextFrameHint ) : SvXMLImportContext( rImport, nPrfx, rLName ), eAnchorType( eATyp ), // OD 2004-04-20 #i26791# mpTextFrameHint( pTextFrameHint ), bMap( sal_False ) { OUString sShow; const SvXMLTokenMap& rTokenMap = GetImport().GetTextImport()->GetTextHyperlinkAttrTokenMap(); sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0; for( sal_Int16 i=0; i < nAttrCount; i++ ) { const OUString& rAttrName = xAttrList->getNameByIndex( i ); const OUString& rValue = xAttrList->getValueByIndex( i ); OUString aLocalName; sal_uInt16 nPrefix = GetImport().GetNamespaceMap().GetKeyByAttrName( rAttrName, &aLocalName ); switch( rTokenMap.Get( nPrefix, aLocalName ) ) { case XML_TOK_TEXT_HYPERLINK_HREF: sHRef = GetImport().GetAbsoluteReference( rValue ); break; case XML_TOK_TEXT_HYPERLINK_NAME: sName = rValue; break; case XML_TOK_TEXT_HYPERLINK_TARGET_FRAME: sTargetFrameName = rValue; break; case XML_TOK_TEXT_HYPERLINK_SHOW: sShow = rValue; break; case XML_TOK_TEXT_HYPERLINK_SERVER_MAP: { sal_Bool bTmp; if( rImport.GetMM100UnitConverter().convertBool( bTmp, rValue ) ) { bMap = bTmp; } } break; } } if( sShow.getLength() && !sTargetFrameName.getLength() ) { if( IsXMLToken( sShow, XML_NEW ) ) sTargetFrameName = OUString( RTL_CONSTASCII_USTRINGPARAM("_blank" ) ); else if( IsXMLToken( sShow, XML_REPLACE ) ) sTargetFrameName = OUString( RTL_CONSTASCII_USTRINGPARAM("_self" ) ); } } XMLTextFrameHyperlinkContext::~XMLTextFrameHyperlinkContext() { } void XMLTextFrameHyperlinkContext::EndElement() { } SvXMLImportContext *XMLTextFrameHyperlinkContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference< XAttributeList > & xAttrList ) { SvXMLImportContext *pContext = 0; XMLTextFrameContext *pTextFrameContext = 0; if( XML_NAMESPACE_DRAW == nPrefix ) { sal_uInt16 nFrameType = USHRT_MAX; if( IsXMLToken( rLocalName, XML_TEXT_BOX ) ) nFrameType = XML_TEXT_FRAME_TEXTBOX; else if( IsXMLToken( rLocalName, XML_IMAGE ) ) nFrameType = XML_TEXT_FRAME_GRAPHIC; else if( IsXMLToken( rLocalName, XML_OBJECT ) ) nFrameType = XML_TEXT_FRAME_OBJECT; else if( IsXMLToken( rLocalName, XML_OBJECT_OLE ) ) nFrameType = XML_TEXT_FRAME_OBJECT_OLE; else if( IsXMLToken( rLocalName, XML_APPLET) ) nFrameType = XML_TEXT_FRAME_APPLET; else if( IsXMLToken( rLocalName, XML_PLUGIN ) ) nFrameType = XML_TEXT_FRAME_PLUGIN; else if( IsXMLToken( rLocalName, XML_FLOATING_FRAME ) ) nFrameType = XML_TEXT_FRAME_FLOATING_FRAME; if( USHRT_MAX != nFrameType ) pTextFrameContext = new XMLTextFrameContext( GetImport(), nPrefix, rLocalName, xAttrList, eAnchorType, nFrameType ); } if( pTextFrameContext ) { pTextFrameContext->SetHyperlink( sHRef, sName, sTargetFrameName, bMap ); // OD 2004-04-20 #i26791# if ( mpTextFrameHint ) { mpTextFrameHint->GetContextRef() = pTextFrameContext; mpTextFrameHint->GetAnchorTypeRef() = pTextFrameContext->GetAnchorType(); } pContext = pTextFrameContext; } else pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName ); return pContext; } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2017 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file ManualSmoothingXY.cpp */ #include "ManualSmoothingXY.hpp" #include "uORB/topics/parameter_update.h" #include <mathlib/mathlib.h> #include <float.h> ManualSmoothingXY::ManualSmoothingXY(ModuleParams *parent, const matrix::Vector2f &vel) : ModuleParams(parent), _vel_sp_prev(vel) { _acc_state_dependent = _acc_xy_max.get(); _jerk_state_dependent = _jerk_max.get(); } void ManualSmoothingXY::smoothVelocity(matrix::Vector2f &vel_sp, const matrix::Vector2f &vel, const float &yaw, const float &yawrate_sp, const float dt) { _updateAcceleration(vel_sp, vel, yaw, yawrate_sp, dt); _velocitySlewRate(vel_sp, dt); _vel_sp_prev = vel_sp; } void ManualSmoothingXY::_updateAcceleration(matrix::Vector2f &vel_sp, const matrix::Vector2f &vel, const float &yaw, const float &yawrate_sp, const float dt) { Intention intention = _getIntention(vel_sp, vel, yaw, yawrate_sp); // Adapt acceleration and jerk based on current state and // intention. Jerk is only used for braking. _setStateAcceleration(vel_sp, vel, intention, dt); } ManualSmoothingXY::Intention ManualSmoothingXY::_getIntention(const matrix::Vector2f &vel_sp, const matrix::Vector2f &vel, const float &yaw, const float &yawrate_sp) { if (vel_sp.length() > FLT_EPSILON) { // Distinguish between acceleration, deceleration and direction change // Check if stick direction and current velocity are within 135. // If current setpoint and velocity are more than 135 apart, we assume // that the user demanded a direction change. // The detection is done in body frame. // Rotate velocity setpoint into body frame matrix::Vector2f vel_sp_heading = _getWorldToHeadingFrame(vel_sp, yaw); matrix::Vector2f vel_heading = _getWorldToHeadingFrame(vel, yaw); if (vel_sp_heading.length() > FLT_EPSILON) { vel_sp_heading.normalize(); } if (vel_heading.length() > FLT_EPSILON) { vel_heading.normalize(); } const bool is_aligned = (vel_sp_heading * vel_heading) > -0.707f; // In almost all cases we want to use acceleration. // Only use direction change if not aligned, no yawspeed demand, demand larger than 0.7 of max speed and velocity larger than 2m/s. // Only use deceleration if stick input is lower than previous setpoint, aligned and no yawspeed demand. bool yawspeed_demand = fabsf(yawrate_sp) > 0.05f && PX4_ISFINITE(yawrate_sp); bool direction_change = !is_aligned && (vel_sp.length() > 0.7f * _vel_max) && !yawspeed_demand && (vel.length() > 2.0f); bool deceleration = is_aligned && (vel_sp.length() < _vel_sp_prev.length()) && !yawspeed_demand; if (direction_change) { return Intention::direction_change; } else if (deceleration) { return Intention::deceleration; } else { return Intention::acceleration; } } return Intention::brake; //default is brake } void ManualSmoothingXY::_setStateAcceleration(const matrix::Vector2f &vel_sp, const matrix::Vector2f &vel, const Intention &intention, const float dt) { switch (intention) { case Intention::brake: { if (_intention == Intention::direction_change) { // Vehicle switched from direction change to brake. // Don't do any slwerate and just stop. _jerk_state_dependent = 1e6f; _vel_sp_prev = vel; } else if (intention != _intention) { // start the brake with lowest acceleration which // makes stopping smoother _acc_state_dependent = _dec_xy_min.get(); // Adjust jerk based on current velocity. This ensures // that the vehicle will stop much quicker at large speed but // very slow at low speed. _jerk_state_dependent = 1e6f; // default if (_jerk_max.get() > _jerk_min.get()) { _jerk_state_dependent = math::min((_jerk_max.get() - _jerk_min.get()) / _vel_max * vel.length() + _jerk_min.get(), _jerk_max.get()); } // User wants to brake smoothly but does NOT want the vehicle to // continue to fly in the opposite direction. slewrate has to be reset // by setting previous velocity setpoint to current velocity. */ _vel_sp_prev = vel; } /* limit jerk when braking to zero */ float jerk = (_acc_hover.get() - _acc_state_dependent) / dt; if (jerk > _jerk_state_dependent) { _acc_state_dependent = _jerk_state_dependent * dt + _acc_state_dependent; } else { _acc_state_dependent = _acc_hover.get(); } break; } case Intention::direction_change: { // We allow for fast change by setting previous setpoint to current setpoint. // Because previous setpoint is equal to current setpoint, // slewrate will have no effect. Nonetheless, just set // acceleration to maximum. _acc_state_dependent = _acc_xy_max.get(); break; } case Intention::acceleration: { // Limit acceleration linearly based on velocity setpoint. _acc_state_dependent = (_acc_xy_max.get() - _dec_xy_min.get()) / _vel_max * vel_sp.length() + _dec_xy_min.get(); break; } case Intention::deceleration: { _acc_state_dependent = _dec_xy_min.get(); break; } } // Update intention for next iteration. _intention = intention; } void ManualSmoothingXY::_velocitySlewRate(matrix::Vector2f &vel_sp, const float dt) { // Adjust velocity setpoint if demand exceeds acceleration. / matrix::Vector2f acc = (vel_sp - _vel_sp_prev) / dt; if (acc.length() > _acc_state_dependent) { vel_sp = acc.normalized() * _acc_state_dependent * dt + _vel_sp_prev; } } matrix::Vector2f ManualSmoothingXY::_getWorldToHeadingFrame(const matrix::Vector2f &vec, const float &yaw) { matrix::Quatf q_yaw = matrix::AxisAnglef(matrix::Vector3f(0.0f, 0.0f, 1.0f), yaw); matrix::Vector3f vec_heading = q_yaw.conjugate_inversed(matrix::Vector3f(vec(0), vec(1), 0.0f)); return matrix::Vector2f(&vec_heading(0)); } matrix::Vector2f ManualSmoothingXY::_getHeadingToWorldFrame(const matrix::Vector2f &vec, const float &yaw) { matrix::Quatf q_yaw = matrix::AxisAnglef(matrix::Vector3f(0.0f, 0.0f, 1.0f), yaw); matrix::Vector3f vec_world = q_yaw.conjugate(matrix::Vector3f(vec(0), vec(1), 0.0f)); return matrix::Vector2f(&vec_world(0)); } <commit_msg>ManualSmoothing: direction change with maximum acceleration<commit_after>/**************************************************************************** * * Copyright (c) 2017 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file ManualSmoothingXY.cpp */ #include "ManualSmoothingXY.hpp" #include "uORB/topics/parameter_update.h" #include <mathlib/mathlib.h> #include <float.h> ManualSmoothingXY::ManualSmoothingXY(ModuleParams *parent, const matrix::Vector2f &vel) : ModuleParams(parent), _vel_sp_prev(vel) { _acc_state_dependent = _acc_xy_max.get(); _jerk_state_dependent = _jerk_max.get(); } void ManualSmoothingXY::smoothVelocity(matrix::Vector2f &vel_sp, const matrix::Vector2f &vel, const float &yaw, const float &yawrate_sp, const float dt) { _updateAcceleration(vel_sp, vel, yaw, yawrate_sp, dt); _velocitySlewRate(vel_sp, dt); _vel_sp_prev = vel_sp; } void ManualSmoothingXY::_updateAcceleration(matrix::Vector2f &vel_sp, const matrix::Vector2f &vel, const float &yaw, const float &yawrate_sp, const float dt) { Intention intention = _getIntention(vel_sp, vel, yaw, yawrate_sp); // Adapt acceleration and jerk based on current state and // intention. Jerk is only used for braking. _setStateAcceleration(vel_sp, vel, intention, dt); } ManualSmoothingXY::Intention ManualSmoothingXY::_getIntention(const matrix::Vector2f &vel_sp, const matrix::Vector2f &vel, const float &yaw, const float &yawrate_sp) { if (vel_sp.length() > FLT_EPSILON) { // Distinguish between acceleration, deceleration and direction change // Check if stick direction and current velocity are within 135. // If current setpoint and velocity are more than 135 apart, we assume // that the user demanded a direction change. // The detection is done in body frame. // Rotate velocity setpoint into body frame matrix::Vector2f vel_sp_heading = _getWorldToHeadingFrame(vel_sp, yaw); matrix::Vector2f vel_heading = _getWorldToHeadingFrame(vel, yaw); if (vel_sp_heading.length() > FLT_EPSILON) { vel_sp_heading.normalize(); } if (vel_heading.length() > FLT_EPSILON) { vel_heading.normalize(); } const bool is_aligned = (vel_sp_heading * vel_heading) > -0.707f; // In almost all cases we want to use acceleration. // Only use direction change if not aligned, no yawspeed demand, demand larger than 0.7 of max speed and velocity larger than 2m/s. // Only use deceleration if stick input is lower than previous setpoint, aligned and no yawspeed demand. bool yawspeed_demand = fabsf(yawrate_sp) > 0.05f && PX4_ISFINITE(yawrate_sp); bool direction_change = !is_aligned && (vel_sp.length() > 0.7f * _vel_max) && !yawspeed_demand && (vel.length() > 2.0f); bool deceleration = is_aligned && (vel_sp.length() < _vel_sp_prev.length()) && !yawspeed_demand; if (direction_change) { return Intention::direction_change; } else if (deceleration) { return Intention::deceleration; } else { return Intention::acceleration; } } return Intention::brake; //default is brake } void ManualSmoothingXY::_setStateAcceleration(const matrix::Vector2f &vel_sp, const matrix::Vector2f &vel, const Intention &intention, const float dt) { switch (intention) { case Intention::brake: { if (_intention == Intention::direction_change) { // Vehicle switched from direction change to brake. // Don't do any slwerate and just stop. _jerk_state_dependent = 1e6f; _vel_sp_prev = vel; } else if (intention != _intention) { // start the brake with lowest acceleration which // makes stopping smoother _acc_state_dependent = _dec_xy_min.get(); // Adjust jerk based on current velocity. This ensures // that the vehicle will stop much quicker at large speed but // very slow at low speed. _jerk_state_dependent = 1e6f; // default if (_jerk_max.get() > _jerk_min.get()) { _jerk_state_dependent = math::min((_jerk_max.get() - _jerk_min.get()) / _vel_max * vel.length() + _jerk_min.get(), _jerk_max.get()); } // User wants to brake smoothly but does NOT want the vehicle to // continue to fly in the opposite direction. slewrate has to be reset // by setting previous velocity setpoint to current velocity. */ _vel_sp_prev = vel; } /* limit jerk when braking to zero */ float jerk = (_acc_hover.get() - _acc_state_dependent) / dt; if (jerk > _jerk_state_dependent) { _acc_state_dependent = _jerk_state_dependent * dt + _acc_state_dependent; } else { _acc_state_dependent = _acc_hover.get(); } break; } case Intention::direction_change: { // We allow for fast change by setting previous setpoint to current setpoint. // Because previous setpoint is equal to current setpoint, // slewrate will have no effect. Nonetheless, just set // acceleration to maximum. _acc_state_dependent = _acc_hover.get(); break; } case Intention::acceleration: { // Limit acceleration linearly based on velocity setpoint. _acc_state_dependent = (_acc_xy_max.get() - _dec_xy_min.get()) / _vel_max * vel_sp.length() + _dec_xy_min.get(); break; } case Intention::deceleration: { _acc_state_dependent = _dec_xy_min.get(); break; } } // Update intention for next iteration. _intention = intention; } void ManualSmoothingXY::_velocitySlewRate(matrix::Vector2f &vel_sp, const float dt) { // Adjust velocity setpoint if demand exceeds acceleration. / matrix::Vector2f acc = (vel_sp - _vel_sp_prev) / dt; if (acc.length() > _acc_state_dependent) { vel_sp = acc.normalized() * _acc_state_dependent * dt + _vel_sp_prev; } } matrix::Vector2f ManualSmoothingXY::_getWorldToHeadingFrame(const matrix::Vector2f &vec, const float &yaw) { matrix::Quatf q_yaw = matrix::AxisAnglef(matrix::Vector3f(0.0f, 0.0f, 1.0f), yaw); matrix::Vector3f vec_heading = q_yaw.conjugate_inversed(matrix::Vector3f(vec(0), vec(1), 0.0f)); return matrix::Vector2f(&vec_heading(0)); } matrix::Vector2f ManualSmoothingXY::_getHeadingToWorldFrame(const matrix::Vector2f &vec, const float &yaw) { matrix::Quatf q_yaw = matrix::AxisAnglef(matrix::Vector3f(0.0f, 0.0f, 1.0f), yaw); matrix::Vector3f vec_world = q_yaw.conjugate(matrix::Vector3f(vec(0), vec(1), 0.0f)); return matrix::Vector2f(&vec_world(0)); } <|endoftext|>
<commit_before>// -*- mode: c++; coding: utf-8 -*- #pragma once #ifndef IOSTR_HPP_ #define IOSTR_HPP_ #include <cstring> #include <cerrno> #include <cassert> #include <cstdarg> #include <ctime> #include <stdexcept> #include <iostream> #include <sstream> #include <fstream> #include <string> #include <vector> #include <map> #include <set> #include <algorithm> /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// // prior declaration namespace wtl { template <class T> extern std::string str_join(const T& v, const std::string& sep=",", const unsigned int digits=std::cout.precision(), const bool fixed=false); } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// // global operator<< for containers template <class T> inline std::ostream& operator<< (std::ostream& ost, const std::vector<T>& v) { return ost << '[' << wtl::str_join(v, ", ", ost.precision()) << ']'; } template <> inline std::ostream& operator<< (std::ostream& ost, const std::vector<std::string>& v) { if (v.empty()) {return ost << "[]";} return ost << "['" << wtl::str_join(v, "', '") << "']"; } template <class T> inline std::ostream& operator<< (std::ostream& ost, const std::set<T>& v) { return ost << "set([" << wtl::str_join(v, ", ", ost.precision()) << "])"; } template <class F, class S> inline std::ostream& operator<< (std::ostream& ost, const std::pair<F, S>& p) { return ost << '(' << std::get<0>(p) << ": " << std::get<1>(p) << ')'; } // map template <class Key, class T, class Comp> inline std::ostream& operator<< (std::ostream& ost, const std::map<Key, T, Comp>& m) { ost << '{'; if (!m.empty()) { auto it(begin(m)); ost << std::get<0>(*it) << ": " << std::get<1>(*it); while (++it != end(m)) { ost << ", " << std::get<0>(*it) << ": " << std::get<1>(*it); } } return ost << '}'; } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// namespace wtl { /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// struct identity { template<class T> constexpr T operator()(T&& x) const noexcept { return std::forward<T>(x); } }; template <class Iter, class Func=identity> inline std::ostream& ost_join(std::ostream& ost, Iter begin_, const Iter end_, const std::string& sep=",", Func func=Func()) { if (begin_ == end_) return ost; ost << func(*begin_); while (++begin_ != end_) {ost << sep << func(*begin_);} return ost; } template <class T, class Func=identity> inline std::ostream& ost_join(std::ostream& ost, const T& v, const std::string& sep=",", Func func=Func()) { return ost_join(ost, begin(v), end(v), sep, func); } template <class Iter, class Func=identity> inline std::string oss_join(Iter begin_, const Iter end_, const std::string& sep=",", Func func=Func()) { std::ostringstream oss; ost_join(oss, begin_, end_, sep, func); return oss.str(); } template <class T, class Func=identity> inline std::string oss_join(const T& v, const std::string& sep=",", Func func=Func()) { std::ostringstream oss; ost_join(oss, v, sep, func); return oss.str(); } template <class Iter> inline std::string str_join(Iter begin_, const Iter end_, const std::string& sep=",", const unsigned int digits=std::cout.precision(), const bool fixed=false) { if (begin_ == end_) return ""; std::ostringstream oss; oss.precision(digits); if (fixed) {oss << std::fixed;} oss << *begin_; while (++begin_ != end_) {oss << sep << *begin_;} return oss.str(); } template <class T> inline std::string str_join(const T& v, const std::string& sep, const unsigned int digits, const bool fixed) { return str_join(begin(v), end(v), sep, digits, fixed); } template <class T> inline std::string str_matrix(const T& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) { std::string s; for (const auto& row: m) { s += str_join(row, sep, digits); s += '\n'; } return s; } template <class T> inline std::string str_map(const T& m, const unsigned int digits=std::cout.precision()) { std::ostringstream oss; oss.precision(digits); oss << m; return oss.str(); } template <int N, class Iter> inline std::string str_pairs(Iter begin_, const Iter end_, const std::string& sep=",", const unsigned int digits=std::cout.precision()) { if (begin_ == end_) return ""; std::ostringstream oss; oss.precision(digits); oss << std::get<N>(*begin_); while (++begin_ != end_) {oss << sep << std::get<N>(*begin_);} return oss.str(); } template <int N, class Map> inline std::string str_pairs(const Map& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) { return str_pairs<N>(begin(m), end(m), sep, digits); } template <class Map> inline std::string str_pair_rows(const Map& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) { std::string s = str_pairs<0>(m, sep, digits); s += '\n'; s += str_pairs<1>(m, sep, digits); return s += '\n'; } template <class Map> inline std::string str_pair_cols(const Map& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) { std::ostringstream oss; oss.precision(digits); for (const auto& p: m) { oss << std::get<0>(p) << sep << std::get<1>(p) << '\n'; } return oss.str(); } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// // std::string manipulation inline std::vector<std::string> split_algorithm(const std::string& src, const std::string& delimiter=" \t\n") { std::vector<std::string> dst; for (auto delim_pos=begin(src), start=delim_pos; delim_pos!=end(src); ) { delim_pos = std::find_first_of(start, end(src), begin(delimiter), end(delimiter)); dst.push_back(std::string(start, delim_pos)); ++(start = delim_pos); } return dst; } inline std::vector<std::string> split(const std::string& src, const std::string& delimiter=" \t\n") { std::vector<std::string> dst; size_t start = 0, offset = 0; while (true) { offset = src.find_first_of(delimiter, start); offset -= start; dst.push_back(src.substr(start, offset)); start += offset; if (start == src.npos) break; ++start; } return dst; } inline std::string rstrip(std::string src, const std::string& chars=" ") { size_t pos(src.find_last_not_of(chars)); if (pos == std::string::npos) { src.clear(); } else { src.erase(++pos); } return src; } inline std::string lstrip(std::string src, const std::string& chars=" ") { const size_t pos(src.find_first_not_of(chars)); if (pos == std::string::npos) { src.clear(); } else { src.erase(0, pos); } return src; } inline std::string strip(std::string src, const std::string& chars=" ") { return rstrip(lstrip(src, chars), chars); } inline bool startswith(const std::string& full, const std::string& sub) { const size_t full_size = full.size(); const size_t sub_size = sub.size(); if (full_size > sub_size) { return full.compare(0, sub_size, sub) == 0; } else { return false; } } inline bool endswith(const std::string& full, const std::string& sub) { const size_t full_size = full.size(); const size_t sub_size = sub.size(); if (full_size > sub_size) { return full.compare(full_size - sub_size, sub_size, sub) == 0; } else { return false; } } inline std::string replace_all(const std::string& patt, const std::string& repl, const std::string& src) { std::string result; std::string::size_type pos_before(0); std::string::size_type pos(0); std::string::size_type len(patt.size()); while ((pos = src.find(patt, pos)) != std::string::npos) { result.append(src, pos_before, pos-pos_before); result.append(repl); pos += len; pos_before = pos; } result.append(src, pos_before, src.size()-pos_before); return result; } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// inline std::string strprintf(const char* const format, ...) { assert(format); va_list args; std::string buffer; va_start(args, format); const int length = std::vsnprintf(nullptr, 0, format, args) ; va_end(args); if (length < 0) throw std::runtime_error(format); buffer.resize(length + 1); va_start(args, format); const int result = std::vsnprintf(&buffer[0], length + 1, format, args); va_end(args); if (result < 0) throw std::runtime_error(format); buffer.pop_back(); return buffer; } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// // default is the same as ctime(): Thu Aug 23 14:55:02 2001 // which is equivalent to "%a %b %d %T %Y" inline std::string strftime(const std::string& format="%c") { char cstr[80]; const time_t rawtime = time(nullptr); const struct tm* t = localtime(&rawtime); std::strftime(cstr, sizeof(cstr), format.c_str(), t); return std::string(cstr); } inline std::string iso8601date(const std::string& sep="-") { std::ostringstream oss; oss << "%Y" << sep << "%m" << sep << "%d"; return strftime(oss.str()); } inline std::string iso8601time(const std::string& sep=":") { std::ostringstream oss; oss << "%H" << sep << "%M" << sep << "%S"; return strftime(oss.str()); } inline std::string iso8601datetime() {return strftime("%FT%T%z");} /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// // fstream wrapper for binary mode and exceptions // boost::serialization requires binary mode class Fin: public std::ifstream { public: explicit Fin(const std::string& filepath, const std::ios::openmode mode=std::ios::in): std::ifstream(filepath.c_str(), mode | std::ios::binary) {exceptions(std::ios::badbit);} std::string readline(const char delimiter='\n') { std::string buffer; std::getline(*this, buffer, delimiter); return buffer; } std::vector<std::string> readlines(const char delimiter='\n') { std::vector<std::string> lines; std::string buffer; while (std::getline(*this, buffer, delimiter)) { lines.push_back(buffer); } return lines; } std::string read(const char delimiter='\0') {return readline(delimiter);} }; class Fout: public std::ofstream { public: explicit Fout(const std::string& filepath, const std::ios::openmode mode=std::ios::out): std::ofstream(filepath.c_str(), mode | std::ios::binary) {exceptions(std::ios::failbit);} template <class Iter> Fout& writelines(Iter begin_, const Iter end_, const char sep='\n') { if (begin_ == end_) return *this; *this << *begin_; while (++begin_ != end_) {*this << sep << *begin_;} return *this; } template <class V> Fout& writelines(const V& lines, const char sep='\n') { return writelines(begin(lines), end(lines), sep); } }; inline std::vector<std::pair<std::string, std::string> > read_ini(const std::string& filename) { std::vector<std::string> lines = Fin(filename).readlines(); std::vector<std::pair<std::string, std::string> > dst; dst.reserve(lines.size()); for (auto line_: lines) { line_ = strip(line_); if (startswith(line_, "[")) {continue;} // TODO auto pair_ = split(line_, ":="); // TODO if (pair_.size() < 2) {continue;} dst.emplace_back(rstrip(pair_[0]), lstrip(pair_[1])); } return dst; } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// } // namespace wtl /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// #endif /* IOSTR_HPP_ */ <commit_msg>Add operator<< for std::unordered_map<commit_after>// -*- mode: c++; coding: utf-8 -*- #pragma once #ifndef IOSTR_HPP_ #define IOSTR_HPP_ #include <cstring> #include <cerrno> #include <cassert> #include <cstdarg> #include <ctime> #include <stdexcept> #include <iostream> #include <sstream> #include <fstream> #include <string> #include <vector> #include <map> #include <unordered_map> #include <set> #include <algorithm> /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// // prior declaration namespace wtl { template <class T> extern std::string str_join(const T& v, const std::string& sep=",", const unsigned int digits=std::cout.precision(), const bool fixed=false); } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// // global operator<< for containers template <class T> inline std::ostream& operator<< (std::ostream& ost, const std::vector<T>& v) { return ost << '[' << wtl::str_join(v, ", ", ost.precision()) << ']'; } template <> inline std::ostream& operator<< (std::ostream& ost, const std::vector<std::string>& v) { if (v.empty()) {return ost << "[]";} return ost << "['" << wtl::str_join(v, "', '") << "']"; } template <class T> inline std::ostream& operator<< (std::ostream& ost, const std::set<T>& v) { return ost << "set([" << wtl::str_join(v, ", ", ost.precision()) << "])"; } template <class F, class S> inline std::ostream& operator<< (std::ostream& ost, const std::pair<F, S>& p) { return ost << '(' << std::get<0>(p) << ": " << std::get<1>(p) << ')'; } namespace wtl { namespace detail { template <class Map> inline std::ostream& operator_ost_map(std::ostream& ost, const Map& m) { ost << '{'; if (!m.empty()) { auto it(begin(m)); ost << std::get<0>(*it) << ": " << std::get<1>(*it); while (++it != end(m)) { ost << ", " << std::get<0>(*it) << ": " << std::get<1>(*it); } } return ost << '}'; } }} // namespace // map template <class Key, class T, class Comp> inline std::ostream& operator<< (std::ostream& ost, const std::map<Key, T, Comp>& m) { return wtl::detail::operator_ost_map(ost, m); } // unordered_map template <class Key, class T, class Hash> inline std::ostream& operator<< (std::ostream& ost, const std::unordered_map<Key, T, Hash>& m) { return wtl::detail::operator_ost_map(ost, m); } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// namespace wtl { /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// struct identity { template<class T> constexpr T operator()(T&& x) const noexcept { return std::forward<T>(x); } }; template <class Iter, class Func=identity> inline std::ostream& ost_join(std::ostream& ost, Iter begin_, const Iter end_, const std::string& sep=",", Func func=Func()) { if (begin_ == end_) return ost; ost << func(*begin_); while (++begin_ != end_) {ost << sep << func(*begin_);} return ost; } template <class T, class Func=identity> inline std::ostream& ost_join(std::ostream& ost, const T& v, const std::string& sep=",", Func func=Func()) { return ost_join(ost, begin(v), end(v), sep, func); } template <class Iter, class Func=identity> inline std::string oss_join(Iter begin_, const Iter end_, const std::string& sep=",", Func func=Func()) { std::ostringstream oss; ost_join(oss, begin_, end_, sep, func); return oss.str(); } template <class T, class Func=identity> inline std::string oss_join(const T& v, const std::string& sep=",", Func func=Func()) { std::ostringstream oss; ost_join(oss, v, sep, func); return oss.str(); } template <class Iter> inline std::string str_join(Iter begin_, const Iter end_, const std::string& sep=",", const unsigned int digits=std::cout.precision(), const bool fixed=false) { if (begin_ == end_) return ""; std::ostringstream oss; oss.precision(digits); if (fixed) {oss << std::fixed;} oss << *begin_; while (++begin_ != end_) {oss << sep << *begin_;} return oss.str(); } template <class T> inline std::string str_join(const T& v, const std::string& sep, const unsigned int digits, const bool fixed) { return str_join(begin(v), end(v), sep, digits, fixed); } template <class T> inline std::string str_matrix(const T& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) { std::string s; for (const auto& row: m) { s += str_join(row, sep, digits); s += '\n'; } return s; } template <class T> inline std::string str_map(const T& m, const unsigned int digits=std::cout.precision()) { std::ostringstream oss; oss.precision(digits); oss << m; return oss.str(); } template <int N, class Iter> inline std::string str_pairs(Iter begin_, const Iter end_, const std::string& sep=",", const unsigned int digits=std::cout.precision()) { if (begin_ == end_) return ""; std::ostringstream oss; oss.precision(digits); oss << std::get<N>(*begin_); while (++begin_ != end_) {oss << sep << std::get<N>(*begin_);} return oss.str(); } template <int N, class Map> inline std::string str_pairs(const Map& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) { return str_pairs<N>(begin(m), end(m), sep, digits); } template <class Map> inline std::string str_pair_rows(const Map& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) { std::string s = str_pairs<0>(m, sep, digits); s += '\n'; s += str_pairs<1>(m, sep, digits); return s += '\n'; } template <class Map> inline std::string str_pair_cols(const Map& m, const std::string& sep=",", const unsigned int digits=std::cout.precision()) { std::ostringstream oss; oss.precision(digits); for (const auto& p: m) { oss << std::get<0>(p) << sep << std::get<1>(p) << '\n'; } return oss.str(); } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// // std::string manipulation inline std::vector<std::string> split_algorithm(const std::string& src, const std::string& delimiter=" \t\n") { std::vector<std::string> dst; for (auto delim_pos=begin(src), start=delim_pos; delim_pos!=end(src); ) { delim_pos = std::find_first_of(start, end(src), begin(delimiter), end(delimiter)); dst.push_back(std::string(start, delim_pos)); ++(start = delim_pos); } return dst; } inline std::vector<std::string> split(const std::string& src, const std::string& delimiter=" \t\n") { std::vector<std::string> dst; size_t start = 0, offset = 0; while (true) { offset = src.find_first_of(delimiter, start); offset -= start; dst.push_back(src.substr(start, offset)); start += offset; if (start == src.npos) break; ++start; } return dst; } inline std::string rstrip(std::string src, const std::string& chars=" ") { size_t pos(src.find_last_not_of(chars)); if (pos == std::string::npos) { src.clear(); } else { src.erase(++pos); } return src; } inline std::string lstrip(std::string src, const std::string& chars=" ") { const size_t pos(src.find_first_not_of(chars)); if (pos == std::string::npos) { src.clear(); } else { src.erase(0, pos); } return src; } inline std::string strip(std::string src, const std::string& chars=" ") { return rstrip(lstrip(src, chars), chars); } inline bool startswith(const std::string& full, const std::string& sub) { const size_t full_size = full.size(); const size_t sub_size = sub.size(); if (full_size > sub_size) { return full.compare(0, sub_size, sub) == 0; } else { return false; } } inline bool endswith(const std::string& full, const std::string& sub) { const size_t full_size = full.size(); const size_t sub_size = sub.size(); if (full_size > sub_size) { return full.compare(full_size - sub_size, sub_size, sub) == 0; } else { return false; } } inline std::string replace_all(const std::string& patt, const std::string& repl, const std::string& src) { std::string result; std::string::size_type pos_before(0); std::string::size_type pos(0); std::string::size_type len(patt.size()); while ((pos = src.find(patt, pos)) != std::string::npos) { result.append(src, pos_before, pos-pos_before); result.append(repl); pos += len; pos_before = pos; } result.append(src, pos_before, src.size()-pos_before); return result; } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// inline std::string strprintf(const char* const format, ...) { assert(format); va_list args; std::string buffer; va_start(args, format); const int length = std::vsnprintf(nullptr, 0, format, args) ; va_end(args); if (length < 0) throw std::runtime_error(format); buffer.resize(length + 1); va_start(args, format); const int result = std::vsnprintf(&buffer[0], length + 1, format, args); va_end(args); if (result < 0) throw std::runtime_error(format); buffer.pop_back(); return buffer; } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// // default is the same as ctime(): Thu Aug 23 14:55:02 2001 // which is equivalent to "%a %b %d %T %Y" inline std::string strftime(const std::string& format="%c") { char cstr[80]; const time_t rawtime = time(nullptr); const struct tm* t = localtime(&rawtime); std::strftime(cstr, sizeof(cstr), format.c_str(), t); return std::string(cstr); } inline std::string iso8601date(const std::string& sep="-") { std::ostringstream oss; oss << "%Y" << sep << "%m" << sep << "%d"; return strftime(oss.str()); } inline std::string iso8601time(const std::string& sep=":") { std::ostringstream oss; oss << "%H" << sep << "%M" << sep << "%S"; return strftime(oss.str()); } inline std::string iso8601datetime() {return strftime("%FT%T%z");} /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// // fstream wrapper for binary mode and exceptions // boost::serialization requires binary mode class Fin: public std::ifstream { public: explicit Fin(const std::string& filepath, const std::ios::openmode mode=std::ios::in): std::ifstream(filepath.c_str(), mode | std::ios::binary) {exceptions(std::ios::badbit);} std::string readline(const char delimiter='\n') { std::string buffer; std::getline(*this, buffer, delimiter); return buffer; } std::vector<std::string> readlines(const char delimiter='\n') { std::vector<std::string> lines; std::string buffer; while (std::getline(*this, buffer, delimiter)) { lines.push_back(buffer); } return lines; } std::string read(const char delimiter='\0') {return readline(delimiter);} }; class Fout: public std::ofstream { public: explicit Fout(const std::string& filepath, const std::ios::openmode mode=std::ios::out): std::ofstream(filepath.c_str(), mode | std::ios::binary) {exceptions(std::ios::failbit);} template <class Iter> Fout& writelines(Iter begin_, const Iter end_, const char sep='\n') { if (begin_ == end_) return *this; *this << *begin_; while (++begin_ != end_) {*this << sep << *begin_;} return *this; } template <class V> Fout& writelines(const V& lines, const char sep='\n') { return writelines(begin(lines), end(lines), sep); } }; inline std::vector<std::pair<std::string, std::string> > read_ini(const std::string& filename) { std::vector<std::string> lines = Fin(filename).readlines(); std::vector<std::pair<std::string, std::string> > dst; dst.reserve(lines.size()); for (auto line_: lines) { line_ = strip(line_); if (startswith(line_, "[")) {continue;} // TODO auto pair_ = split(line_, ":="); // TODO if (pair_.size() < 2) {continue;} dst.emplace_back(rstrip(pair_[0]), lstrip(pair_[1])); } return dst; } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// } // namespace wtl /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// #endif /* IOSTR_HPP_ */ <|endoftext|>
<commit_before><commit_msg>aw: Fix SetExtraRequestHeaderByName DCHECK<commit_after><|endoftext|>
<commit_before>/** * Copyright (c) 2007-2012, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file lnav_util.hh * * Dumping ground for useful functions with no other home. */ #ifndef lnav_util_hh #define lnav_util_hh #include <future> #include <iterator> #include <numeric> #include <string> #include <type_traits> #include <vector> #include <fcntl.h> #include <poll.h> #include <sys/resource.h> #include <sys/time.h> #include <sys/types.h> #include <time.h> #include "base/auto_mem.hh" #include "base/intern_string.hh" #include "base/lnav.console.hh" #include "base/result.h" #include "byte_array.hh" #include "config.h" #include "fmt/format.h" #include "optional.hpp" #include "ptimec.hh" #include "spookyhash/SpookyV2.h" #if SIZEOF_OFF_T == 8 # define FORMAT_OFF_T "%lld" #elif SIZEOF_OFF_T == 4 # define FORMAT_OFF_T "%ld" #else # error "off_t has unhandled size..." #endif class hasher { public: using array_t = byte_array<2, uint64_t>; static constexpr size_t STRING_SIZE = array_t::STRING_SIZE; hasher() { this->h_context.Init(0, 0); } hasher& update(const std::string& str) { this->h_context.Update(str.data(), str.length()); return *this; } hasher& update(const string_fragment& str) { this->h_context.Update(str.data(), str.length()); return *this; } hasher& update(const char* bits, size_t len) { this->h_context.Update(bits, len); return *this; } template<typename T, typename = std::enable_if<std::is_arithmetic<T>::value>> hasher& update(T value) { this->h_context.Update(&value, sizeof(value)); return *this; } array_t to_array() { uint64_t h1; uint64_t h2; array_t retval; this->h_context.Final(&h1, &h2); *retval.out(0) = SPOOKYHASH_LITTLE_ENDIAN_64(h1); *retval.out(1) = SPOOKYHASH_LITTLE_ENDIAN_64(h2); return retval; } void to_string(auto_buffer& buf) { array_t bits = this->to_array(); bits.to_string(std::back_inserter(buf)); } std::string to_string() { array_t bits = this->to_array(); return bits.to_string(); } std::string to_uuid_string() { array_t bits = this->to_array(); return bits.to_uuid_string(); } private: SpookyHash h_context; }; bool change_to_parent_dir(); bool next_format(const char* const fmt[], int& index, int& locked_index); namespace std { inline string to_string(const string& s) { return s; } inline string to_string(const char* s) { return s; } } // namespace std inline bool is_glob(const std::string& fn) { return (fn.find('*') != std::string::npos || fn.find('?') != std::string::npos || fn.find('[') != std::string::npos); } inline void rusagesub(const struct rusage& left, const struct rusage& right, struct rusage& diff_out) { timersub(&left.ru_utime, &right.ru_utime, &diff_out.ru_utime); timersub(&left.ru_stime, &right.ru_stime, &diff_out.ru_stime); diff_out.ru_maxrss = left.ru_maxrss - right.ru_maxrss; diff_out.ru_ixrss = left.ru_ixrss - right.ru_ixrss; diff_out.ru_idrss = left.ru_idrss - right.ru_idrss; diff_out.ru_isrss = left.ru_isrss - right.ru_isrss; diff_out.ru_minflt = left.ru_minflt - right.ru_minflt; diff_out.ru_majflt = left.ru_majflt - right.ru_majflt; diff_out.ru_nswap = left.ru_nswap - right.ru_nswap; diff_out.ru_inblock = left.ru_inblock - right.ru_inblock; diff_out.ru_oublock = left.ru_oublock - right.ru_oublock; diff_out.ru_msgsnd = left.ru_msgsnd - right.ru_msgsnd; diff_out.ru_msgrcv = left.ru_msgrcv - right.ru_msgrcv; diff_out.ru_nvcsw = left.ru_nvcsw - right.ru_nvcsw; diff_out.ru_nivcsw = left.ru_nivcsw - right.ru_nivcsw; } inline void rusageadd(const struct rusage& left, const struct rusage& right, struct rusage& diff_out) { timeradd(&left.ru_utime, &right.ru_utime, &diff_out.ru_utime); timeradd(&left.ru_stime, &right.ru_stime, &diff_out.ru_stime); diff_out.ru_maxrss = left.ru_maxrss + right.ru_maxrss; diff_out.ru_ixrss = left.ru_ixrss + right.ru_ixrss; diff_out.ru_idrss = left.ru_idrss + right.ru_idrss; diff_out.ru_isrss = left.ru_isrss + right.ru_isrss; diff_out.ru_minflt = left.ru_minflt + right.ru_minflt; diff_out.ru_majflt = left.ru_majflt + right.ru_majflt; diff_out.ru_nswap = left.ru_nswap + right.ru_nswap; diff_out.ru_inblock = left.ru_inblock + right.ru_inblock; diff_out.ru_oublock = left.ru_oublock + right.ru_oublock; diff_out.ru_msgsnd = left.ru_msgsnd + right.ru_msgsnd; diff_out.ru_msgrcv = left.ru_msgrcv + right.ru_msgrcv; diff_out.ru_nvcsw = left.ru_nvcsw + right.ru_nvcsw; diff_out.ru_nivcsw = left.ru_nivcsw + right.ru_nivcsw; } bool is_dev_null(const struct stat& st); bool is_dev_null(int fd); template<typename A> struct final_action { // slightly simplified A act; final_action(A a) : act{a} {} ~final_action() { act(); } }; template<typename A> final_action<A> finally(A act) // deduce action type { return final_action<A>{act}; } void write_line_to(FILE* outfile, const attr_line_t& al); namespace lnav { std::string to_json(const std::string& str); std::string to_json(const lnav::console::user_message& um); std::string to_json(const attr_line_t& al); template<typename T> Result<T, std::vector<lnav::console::user_message>> from_json( const std::string& json); } // namespace lnav #endif <commit_msg>[port] one more endianness change<commit_after>/** * Copyright (c) 2007-2012, Timothy Stack * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Timothy Stack nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * @file lnav_util.hh * * Dumping ground for useful functions with no other home. */ #ifndef lnav_util_hh #define lnav_util_hh #include <future> #include <iterator> #include <numeric> #include <string> #include <type_traits> #include <vector> #include <fcntl.h> #include <poll.h> #include <sys/resource.h> #include <sys/time.h> #include <sys/types.h> #include <time.h> #include "base/auto_mem.hh" #include "base/intern_string.hh" #include "base/lnav.console.hh" #include "base/result.h" #include "byte_array.hh" #include "config.h" #include "fmt/format.h" #include "optional.hpp" #include "ptimec.hh" #include "spookyhash/SpookyV2.h" #if SIZEOF_OFF_T == 8 # define FORMAT_OFF_T "%lld" #elif SIZEOF_OFF_T == 4 # define FORMAT_OFF_T "%ld" #else # error "off_t has unhandled size..." #endif class hasher { public: using array_t = byte_array<2, uint64_t>; static constexpr size_t STRING_SIZE = array_t::STRING_SIZE; hasher() { this->h_context.Init(0, 0); } hasher& update(const std::string& str) { this->h_context.Update(str.data(), str.length()); return *this; } hasher& update(const string_fragment& str) { this->h_context.Update(str.data(), str.length()); return *this; } hasher& update(const char* bits, size_t len) { this->h_context.Update(bits, len); return *this; } hasher& update(int64_t value) { value = SPOOKYHASH_LITTLE_ENDIAN_64(value); this->h_context.Update(&value, sizeof(value)); return *this; } array_t to_array() { uint64_t h1; uint64_t h2; array_t retval; this->h_context.Final(&h1, &h2); *retval.out(0) = SPOOKYHASH_LITTLE_ENDIAN_64(h1); *retval.out(1) = SPOOKYHASH_LITTLE_ENDIAN_64(h2); return retval; } void to_string(auto_buffer& buf) { array_t bits = this->to_array(); bits.to_string(std::back_inserter(buf)); } std::string to_string() { array_t bits = this->to_array(); return bits.to_string(); } std::string to_uuid_string() { array_t bits = this->to_array(); return bits.to_uuid_string(); } private: SpookyHash h_context; }; bool change_to_parent_dir(); bool next_format(const char* const fmt[], int& index, int& locked_index); namespace std { inline string to_string(const string& s) { return s; } inline string to_string(const char* s) { return s; } } // namespace std inline bool is_glob(const std::string& fn) { return (fn.find('*') != std::string::npos || fn.find('?') != std::string::npos || fn.find('[') != std::string::npos); } inline void rusagesub(const struct rusage& left, const struct rusage& right, struct rusage& diff_out) { timersub(&left.ru_utime, &right.ru_utime, &diff_out.ru_utime); timersub(&left.ru_stime, &right.ru_stime, &diff_out.ru_stime); diff_out.ru_maxrss = left.ru_maxrss - right.ru_maxrss; diff_out.ru_ixrss = left.ru_ixrss - right.ru_ixrss; diff_out.ru_idrss = left.ru_idrss - right.ru_idrss; diff_out.ru_isrss = left.ru_isrss - right.ru_isrss; diff_out.ru_minflt = left.ru_minflt - right.ru_minflt; diff_out.ru_majflt = left.ru_majflt - right.ru_majflt; diff_out.ru_nswap = left.ru_nswap - right.ru_nswap; diff_out.ru_inblock = left.ru_inblock - right.ru_inblock; diff_out.ru_oublock = left.ru_oublock - right.ru_oublock; diff_out.ru_msgsnd = left.ru_msgsnd - right.ru_msgsnd; diff_out.ru_msgrcv = left.ru_msgrcv - right.ru_msgrcv; diff_out.ru_nvcsw = left.ru_nvcsw - right.ru_nvcsw; diff_out.ru_nivcsw = left.ru_nivcsw - right.ru_nivcsw; } inline void rusageadd(const struct rusage& left, const struct rusage& right, struct rusage& diff_out) { timeradd(&left.ru_utime, &right.ru_utime, &diff_out.ru_utime); timeradd(&left.ru_stime, &right.ru_stime, &diff_out.ru_stime); diff_out.ru_maxrss = left.ru_maxrss + right.ru_maxrss; diff_out.ru_ixrss = left.ru_ixrss + right.ru_ixrss; diff_out.ru_idrss = left.ru_idrss + right.ru_idrss; diff_out.ru_isrss = left.ru_isrss + right.ru_isrss; diff_out.ru_minflt = left.ru_minflt + right.ru_minflt; diff_out.ru_majflt = left.ru_majflt + right.ru_majflt; diff_out.ru_nswap = left.ru_nswap + right.ru_nswap; diff_out.ru_inblock = left.ru_inblock + right.ru_inblock; diff_out.ru_oublock = left.ru_oublock + right.ru_oublock; diff_out.ru_msgsnd = left.ru_msgsnd + right.ru_msgsnd; diff_out.ru_msgrcv = left.ru_msgrcv + right.ru_msgrcv; diff_out.ru_nvcsw = left.ru_nvcsw + right.ru_nvcsw; diff_out.ru_nivcsw = left.ru_nivcsw + right.ru_nivcsw; } bool is_dev_null(const struct stat& st); bool is_dev_null(int fd); template<typename A> struct final_action { // slightly simplified A act; final_action(A a) : act{a} {} ~final_action() { act(); } }; template<typename A> final_action<A> finally(A act) // deduce action type { return final_action<A>{act}; } void write_line_to(FILE* outfile, const attr_line_t& al); namespace lnav { std::string to_json(const std::string& str); std::string to_json(const lnav::console::user_message& um); std::string to_json(const attr_line_t& al); template<typename T> Result<T, std::vector<lnav::console::user_message>> from_json( const std::string& json); } // namespace lnav #endif <|endoftext|>
<commit_before> // This test demonstrates using tracing to give you something like a // stack trace in case of a crash (due to a compiler bug, or a bug in // external code). We use a posix signal handler, which is probably // os-dependent, so I'm going to enable this test on linux only. #if defined(__linux__) || defined(__APPLE__) || defined(__unix) || defined(__posix) #include <Halide.h> #include <stdio.h> #include <signal.h> #include <stack> #include <string> using namespace Halide; using std::stack; using std::string; stack<string> stack_trace; void my_trace(const char *function, int event_type, int type_code, int bits, int width, int value_index, const void *value, int num_int_args, const int *int_args) { const string event_types[] = {"Load ", "Store ", "Begin realization ", "End realization ", "Produce ", "Update ", "Consume ", "End consume "}; if (event_type == 3 || event_type > 4) { // These events signal the end of some previous event stack_trace.pop(); } if (event_type == 2 || event_type == 4 || event_type == 5 || event_type == 6) { // These events signal the start of some new region stack_trace.push(event_types[event_type] + function); } } void signal_handler(int signum) { printf("Correctly triggered a segfault. Here is the stack trace:\n"); while (!stack_trace.empty()) { printf("%s\n", stack_trace.top().c_str()); stack_trace.pop(); } printf("Success!\n"); exit(0); } int main(int argc, char **argv) { signal(SIGSEGV, signal_handler); // Loads from this image will barf, because we've messed up the host pointer Image<int> input(100, 100); buffer_t *buf = input.raw_buffer(); buf->host = (uint8_t *)17; Func f("f"), g("g"), h("h"); Var x("x"), y("y"); f(x, y) = x+y; f.compute_root().trace_realizations(); g(x, y) = f(x, y) + 37; g.compute_root().trace_realizations(); h(x, y) = g(x, y) + input(x, y); h.trace_realizations(); h.set_custom_trace(&my_trace); h.realize(100, 100); printf("The code should not have reached this print statement.\n"); return -1; } #else #include <stdio.h> int main(int argc, char **argv) { printf("Test skipped because we're not on a system with UNIX signal handling\n"); return 0; } #endif <commit_msg>Also catch SIGBUS for os x<commit_after> // This test demonstrates using tracing to give you something like a // stack trace in case of a crash (due to a compiler bug, or a bug in // external code). We use a posix signal handler, which is probably // os-dependent, so I'm going to enable this test on linux only. #if defined(__linux__) || defined(__APPLE__) || defined(__unix) || defined(__posix) #include <Halide.h> #include <stdio.h> #include <signal.h> #include <stack> #include <string> using namespace Halide; using std::stack; using std::string; stack<string> stack_trace; void my_trace(const char *function, int event_type, int type_code, int bits, int width, int value_index, const void *value, int num_int_args, const int *int_args) { const string event_types[] = {"Load ", "Store ", "Begin realization ", "End realization ", "Produce ", "Update ", "Consume ", "End consume "}; if (event_type == 3 || event_type > 4) { // These events signal the end of some previous event stack_trace.pop(); } if (event_type == 2 || event_type == 4 || event_type == 5 || event_type == 6) { // These events signal the start of some new region stack_trace.push(event_types[event_type] + function); } } void signal_handler(int signum) { printf("Correctly triggered a segfault. Here is the stack trace:\n"); while (!stack_trace.empty()) { printf("%s\n", stack_trace.top().c_str()); stack_trace.pop(); } printf("Success!\n"); exit(0); } int main(int argc, char **argv) { signal(SIGSEGV, signal_handler); signal(SIGBUS, signal_handler); // Loads from this image will barf, because we've messed up the host pointer Image<int> input(100, 100); buffer_t *buf = input.raw_buffer(); buf->host = (uint8_t *)17; Func f("f"), g("g"), h("h"); Var x("x"), y("y"); f(x, y) = x+y; f.compute_root().trace_realizations(); g(x, y) = f(x, y) + 37; g.compute_root().trace_realizations(); h(x, y) = g(x, y) + input(x, y); h.trace_realizations(); h.set_custom_trace(&my_trace); h.realize(100, 100); printf("The code should not have reached this print statement.\n"); return -1; } #else #include <stdio.h> int main(int argc, char **argv) { printf("Test skipped because we're not on a system with UNIX signal handling\n"); return 0; } #endif <|endoftext|>
<commit_before>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "tools/gpu/gl/GLTestContext.h" #include "include/gpu/GrDirectContext.h" #include "src/gpu/gl/GrGLUtil.h" #include "tools/gpu/GpuTimer.h" namespace { class GLGpuTimer : public sk_gpu_test::GpuTimer { public: static std::unique_ptr<GLGpuTimer> MakeIfSupported(const sk_gpu_test::GLTestContext*); QueryStatus checkQueryStatus(sk_gpu_test::PlatformTimerQuery) override; std::chrono::nanoseconds getTimeElapsed(sk_gpu_test::PlatformTimerQuery) override; void deleteQuery(sk_gpu_test::PlatformTimerQuery) override; private: GLGpuTimer(bool disjointSupport, const sk_gpu_test::GLTestContext*, const char* ext = ""); bool validate() const; sk_gpu_test::PlatformTimerQuery onQueueTimerStart() const override; void onQueueTimerStop(sk_gpu_test::PlatformTimerQuery) const override; static constexpr GrGLenum GL_QUERY_RESULT = 0x8866; static constexpr GrGLenum GL_QUERY_RESULT_AVAILABLE = 0x8867; static constexpr GrGLenum GL_TIME_ELAPSED = 0x88bf; static constexpr GrGLenum GL_GPU_DISJOINT = 0x8fbb; typedef void (GR_GL_FUNCTION_TYPE* GLGetIntegervProc) (GrGLenum, GrGLint*); typedef void (GR_GL_FUNCTION_TYPE* GLGenQueriesProc) (GrGLsizei, GrGLuint*); typedef void (GR_GL_FUNCTION_TYPE* GLDeleteQueriesProc) (GrGLsizei, const GrGLuint*); typedef void (GR_GL_FUNCTION_TYPE* GLBeginQueryProc) (GrGLenum, GrGLuint); typedef void (GR_GL_FUNCTION_TYPE* GLEndQueryProc) (GrGLenum); typedef void (GR_GL_FUNCTION_TYPE* GLGetQueryObjectuivProc) (GrGLuint, GrGLenum, GrGLuint*); typedef void (GR_GL_FUNCTION_TYPE* GLGetQueryObjectui64vProc) (GrGLuint, GrGLenum, GrGLuint64*); GLGetIntegervProc fGLGetIntegerv; GLGenQueriesProc fGLGenQueries; GLDeleteQueriesProc fGLDeleteQueries; GLBeginQueryProc fGLBeginQuery; GLEndQueryProc fGLEndQuery; GLGetQueryObjectuivProc fGLGetQueryObjectuiv; GLGetQueryObjectui64vProc fGLGetQueryObjectui64v; using INHERITED = sk_gpu_test::GpuTimer; }; std::unique_ptr<GLGpuTimer> GLGpuTimer::MakeIfSupported(const sk_gpu_test::GLTestContext* ctx) { #ifdef SK_GL std::unique_ptr<GLGpuTimer> ret; const GrGLInterface* gl = ctx->gl(); if (gl->fExtensions.has("GL_EXT_disjoint_timer_query")) { ret.reset(new GLGpuTimer(true, ctx, "EXT")); } else if (kGL_GrGLStandard == gl->fStandard && (GrGLGetVersion(gl) > GR_GL_VER(3,3) || gl->fExtensions.has("GL_ARB_timer_query"))) { ret.reset(new GLGpuTimer(false, ctx)); } else if (gl->fExtensions.has("GL_EXT_timer_query")) { ret.reset(new GLGpuTimer(false, ctx, "EXT")); } if (ret && !ret->validate()) { ret = nullptr; } return ret; #else return nullptr; #endif } GLGpuTimer::GLGpuTimer(bool disjointSupport, const sk_gpu_test::GLTestContext* ctx, const char* ext) : INHERITED(disjointSupport) { ctx->getGLProcAddress(&fGLGetIntegerv, "glGetIntegerv"); ctx->getGLProcAddress(&fGLGenQueries, "glGenQueries", ext); ctx->getGLProcAddress(&fGLDeleteQueries, "glDeleteQueries", ext); ctx->getGLProcAddress(&fGLBeginQuery, "glBeginQuery", ext); ctx->getGLProcAddress(&fGLEndQuery, "glEndQuery", ext); ctx->getGLProcAddress(&fGLGetQueryObjectuiv, "glGetQueryObjectuiv", ext); ctx->getGLProcAddress(&fGLGetQueryObjectui64v, "glGetQueryObjectui64v", ext); } bool GLGpuTimer::validate() const { return fGLGetIntegerv && fGLGenQueries && fGLDeleteQueries && fGLBeginQuery && fGLEndQuery && fGLGetQueryObjectuiv && fGLGetQueryObjectui64v; } sk_gpu_test::PlatformTimerQuery GLGpuTimer::onQueueTimerStart() const { GrGLuint queryID; fGLGenQueries(1, &queryID); if (!queryID) { return sk_gpu_test::kInvalidTimerQuery; } if (this->disjointSupport()) { // Clear the disjoint flag. GrGLint disjoint; fGLGetIntegerv(GL_GPU_DISJOINT, &disjoint); } fGLBeginQuery(GL_TIME_ELAPSED, queryID); return static_cast<sk_gpu_test::PlatformTimerQuery>(queryID); } void GLGpuTimer::onQueueTimerStop(sk_gpu_test::PlatformTimerQuery platformTimer) const { if (sk_gpu_test::kInvalidTimerQuery == platformTimer) { return; } fGLEndQuery(GL_TIME_ELAPSED); } sk_gpu_test::GpuTimer::QueryStatus GLGpuTimer::checkQueryStatus(sk_gpu_test::PlatformTimerQuery platformTimer) { const GrGLuint queryID = static_cast<GrGLuint>(platformTimer); if (!queryID) { return QueryStatus::kInvalid; } GrGLuint available = 0; fGLGetQueryObjectuiv(queryID, GL_QUERY_RESULT_AVAILABLE, &available); if (!available) { return QueryStatus::kPending; } if (this->disjointSupport()) { GrGLint disjoint = 1; fGLGetIntegerv(GL_GPU_DISJOINT, &disjoint); if (disjoint) { return QueryStatus::kDisjoint; } } return QueryStatus::kAccurate; } std::chrono::nanoseconds GLGpuTimer::getTimeElapsed(sk_gpu_test::PlatformTimerQuery platformTimer) { SkASSERT(this->checkQueryStatus(platformTimer) >= QueryStatus::kDisjoint); const GrGLuint queryID = static_cast<GrGLuint>(platformTimer); GrGLuint64 nanoseconds; fGLGetQueryObjectui64v(queryID, GL_QUERY_RESULT, &nanoseconds); return std::chrono::nanoseconds(nanoseconds); } void GLGpuTimer::deleteQuery(sk_gpu_test::PlatformTimerQuery platformTimer) { const GrGLuint queryID = static_cast<GrGLuint>(platformTimer); fGLDeleteQueries(1, &queryID); } static_assert(sizeof(GrGLuint) <= sizeof(sk_gpu_test::PlatformTimerQuery)); } // anonymous namespace namespace sk_gpu_test { GLTestContext::GLTestContext() : TestContext() {} GLTestContext::~GLTestContext() { SkASSERT(!fGLInterface); SkASSERT(!fOriginalGLInterface); } bool GLTestContext::isValid() const { #ifdef SK_GL return SkToBool(this->gl()); #else return fWasInitialized; #endif } static bool fence_is_supported(const GLTestContext* ctx) { #ifdef SK_GL if (kGL_GrGLStandard == ctx->gl()->fStandard) { if (GrGLGetVersion(ctx->gl()) < GR_GL_VER(3, 2) && !ctx->gl()->hasExtension("GL_ARB_sync")) { return false; } return true; } else { if (ctx->gl()->hasExtension("GL_APPLE_sync")) { return true; } else if (ctx->gl()->hasExtension("GL_NV_fence")) { return true; } else if (GrGLGetVersion(ctx->gl()) >= GR_GL_VER(3, 0)) { return true; } else { return false; } } #else return false; #endif } void GLTestContext::init(sk_sp<const GrGLInterface> gl) { fGLInterface = std::move(gl); fOriginalGLInterface = fGLInterface; fFenceSupport = fence_is_supported(this); fGpuTimer = GLGpuTimer::MakeIfSupported(this); #ifndef SK_GL fWasInitialized = true; #endif } void GLTestContext::teardown() { fGLInterface.reset(); fOriginalGLInterface.reset(); INHERITED::teardown(); } void GLTestContext::testAbandon() { INHERITED::testAbandon(); #ifdef SK_GL if (fGLInterface) { fGLInterface->abandon(); fOriginalGLInterface->abandon(); } #endif } void GLTestContext::finish() { #ifdef SK_GL if (fGLInterface) { GR_GL_CALL(fGLInterface.get(), Finish()); } #endif } void GLTestContext::overrideVersion(const char* version, const char* shadingLanguageVersion) { #ifdef SK_GL // GrGLFunction has both a limited capture size and doesn't call a destructor when it is // initialized with a lambda. So here we're trusting fOriginalGLInterface will be kept alive. auto getString = [wrapped = &fOriginalGLInterface->fFunctions.fGetString, version, shadingLanguageVersion](GrGLenum name) { if (name == GR_GL_VERSION) { return reinterpret_cast<const GrGLubyte*>(version); } else if (name == GR_GL_SHADING_LANGUAGE_VERSION) { return reinterpret_cast<const GrGLubyte*>(shadingLanguageVersion); } return (*wrapped)(name); }; auto newInterface = sk_make_sp<GrGLInterface>(*fOriginalGLInterface); newInterface->fFunctions.fGetString = getString; fGLInterface = std::move(newInterface); #endif }; sk_sp<GrDirectContext> GLTestContext::makeContext(const GrContextOptions& options) { #ifdef SK_GL return GrDirectContext::MakeGL(fGLInterface, options); #else return nullptr; #endif } } // namespace sk_gpu_test <commit_msg>Fix skia_use_gl = false build<commit_after>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "tools/gpu/gl/GLTestContext.h" #include "include/gpu/GrDirectContext.h" #include "src/gpu/gl/GrGLUtil.h" #include "tools/gpu/GpuTimer.h" namespace { class GLGpuTimer : public sk_gpu_test::GpuTimer { public: static std::unique_ptr<GLGpuTimer> MakeIfSupported(const sk_gpu_test::GLTestContext*); QueryStatus checkQueryStatus(sk_gpu_test::PlatformTimerQuery) override; std::chrono::nanoseconds getTimeElapsed(sk_gpu_test::PlatformTimerQuery) override; void deleteQuery(sk_gpu_test::PlatformTimerQuery) override; private: #ifdef SK_GL GLGpuTimer(bool disjointSupport, const sk_gpu_test::GLTestContext*, const char* ext = ""); bool validate() const; #endif sk_gpu_test::PlatformTimerQuery onQueueTimerStart() const override; void onQueueTimerStop(sk_gpu_test::PlatformTimerQuery) const override; static constexpr GrGLenum GL_QUERY_RESULT = 0x8866; static constexpr GrGLenum GL_QUERY_RESULT_AVAILABLE = 0x8867; static constexpr GrGLenum GL_TIME_ELAPSED = 0x88bf; static constexpr GrGLenum GL_GPU_DISJOINT = 0x8fbb; typedef void (GR_GL_FUNCTION_TYPE* GLGetIntegervProc) (GrGLenum, GrGLint*); typedef void (GR_GL_FUNCTION_TYPE* GLGenQueriesProc) (GrGLsizei, GrGLuint*); typedef void (GR_GL_FUNCTION_TYPE* GLDeleteQueriesProc) (GrGLsizei, const GrGLuint*); typedef void (GR_GL_FUNCTION_TYPE* GLBeginQueryProc) (GrGLenum, GrGLuint); typedef void (GR_GL_FUNCTION_TYPE* GLEndQueryProc) (GrGLenum); typedef void (GR_GL_FUNCTION_TYPE* GLGetQueryObjectuivProc) (GrGLuint, GrGLenum, GrGLuint*); typedef void (GR_GL_FUNCTION_TYPE* GLGetQueryObjectui64vProc) (GrGLuint, GrGLenum, GrGLuint64*); GLGetIntegervProc fGLGetIntegerv; GLGenQueriesProc fGLGenQueries; GLDeleteQueriesProc fGLDeleteQueries; GLBeginQueryProc fGLBeginQuery; GLEndQueryProc fGLEndQuery; GLGetQueryObjectuivProc fGLGetQueryObjectuiv; GLGetQueryObjectui64vProc fGLGetQueryObjectui64v; using INHERITED = sk_gpu_test::GpuTimer; }; std::unique_ptr<GLGpuTimer> GLGpuTimer::MakeIfSupported(const sk_gpu_test::GLTestContext* ctx) { #ifdef SK_GL std::unique_ptr<GLGpuTimer> ret; const GrGLInterface* gl = ctx->gl(); if (gl->fExtensions.has("GL_EXT_disjoint_timer_query")) { ret.reset(new GLGpuTimer(true, ctx, "EXT")); } else if (kGL_GrGLStandard == gl->fStandard && (GrGLGetVersion(gl) > GR_GL_VER(3,3) || gl->fExtensions.has("GL_ARB_timer_query"))) { ret.reset(new GLGpuTimer(false, ctx)); } else if (gl->fExtensions.has("GL_EXT_timer_query")) { ret.reset(new GLGpuTimer(false, ctx, "EXT")); } if (ret && !ret->validate()) { ret = nullptr; } return ret; #else return nullptr; #endif } #ifdef SK_GL GLGpuTimer::GLGpuTimer(bool disjointSupport, const sk_gpu_test::GLTestContext* ctx, const char* ext) : INHERITED(disjointSupport) { ctx->getGLProcAddress(&fGLGetIntegerv, "glGetIntegerv"); ctx->getGLProcAddress(&fGLGenQueries, "glGenQueries", ext); ctx->getGLProcAddress(&fGLDeleteQueries, "glDeleteQueries", ext); ctx->getGLProcAddress(&fGLBeginQuery, "glBeginQuery", ext); ctx->getGLProcAddress(&fGLEndQuery, "glEndQuery", ext); ctx->getGLProcAddress(&fGLGetQueryObjectuiv, "glGetQueryObjectuiv", ext); ctx->getGLProcAddress(&fGLGetQueryObjectui64v, "glGetQueryObjectui64v", ext); } bool GLGpuTimer::validate() const { return fGLGetIntegerv && fGLGenQueries && fGLDeleteQueries && fGLBeginQuery && fGLEndQuery && fGLGetQueryObjectuiv && fGLGetQueryObjectui64v; } #endif sk_gpu_test::PlatformTimerQuery GLGpuTimer::onQueueTimerStart() const { GrGLuint queryID; fGLGenQueries(1, &queryID); if (!queryID) { return sk_gpu_test::kInvalidTimerQuery; } if (this->disjointSupport()) { // Clear the disjoint flag. GrGLint disjoint; fGLGetIntegerv(GL_GPU_DISJOINT, &disjoint); } fGLBeginQuery(GL_TIME_ELAPSED, queryID); return static_cast<sk_gpu_test::PlatformTimerQuery>(queryID); } void GLGpuTimer::onQueueTimerStop(sk_gpu_test::PlatformTimerQuery platformTimer) const { if (sk_gpu_test::kInvalidTimerQuery == platformTimer) { return; } fGLEndQuery(GL_TIME_ELAPSED); } sk_gpu_test::GpuTimer::QueryStatus GLGpuTimer::checkQueryStatus(sk_gpu_test::PlatformTimerQuery platformTimer) { const GrGLuint queryID = static_cast<GrGLuint>(platformTimer); if (!queryID) { return QueryStatus::kInvalid; } GrGLuint available = 0; fGLGetQueryObjectuiv(queryID, GL_QUERY_RESULT_AVAILABLE, &available); if (!available) { return QueryStatus::kPending; } if (this->disjointSupport()) { GrGLint disjoint = 1; fGLGetIntegerv(GL_GPU_DISJOINT, &disjoint); if (disjoint) { return QueryStatus::kDisjoint; } } return QueryStatus::kAccurate; } std::chrono::nanoseconds GLGpuTimer::getTimeElapsed(sk_gpu_test::PlatformTimerQuery platformTimer) { SkASSERT(this->checkQueryStatus(platformTimer) >= QueryStatus::kDisjoint); const GrGLuint queryID = static_cast<GrGLuint>(platformTimer); GrGLuint64 nanoseconds; fGLGetQueryObjectui64v(queryID, GL_QUERY_RESULT, &nanoseconds); return std::chrono::nanoseconds(nanoseconds); } void GLGpuTimer::deleteQuery(sk_gpu_test::PlatformTimerQuery platformTimer) { const GrGLuint queryID = static_cast<GrGLuint>(platformTimer); fGLDeleteQueries(1, &queryID); } static_assert(sizeof(GrGLuint) <= sizeof(sk_gpu_test::PlatformTimerQuery)); } // anonymous namespace namespace sk_gpu_test { GLTestContext::GLTestContext() : TestContext() {} GLTestContext::~GLTestContext() { SkASSERT(!fGLInterface); SkASSERT(!fOriginalGLInterface); } bool GLTestContext::isValid() const { #ifdef SK_GL return SkToBool(this->gl()); #else return fWasInitialized; #endif } static bool fence_is_supported(const GLTestContext* ctx) { #ifdef SK_GL if (kGL_GrGLStandard == ctx->gl()->fStandard) { if (GrGLGetVersion(ctx->gl()) < GR_GL_VER(3, 2) && !ctx->gl()->hasExtension("GL_ARB_sync")) { return false; } return true; } else { if (ctx->gl()->hasExtension("GL_APPLE_sync")) { return true; } else if (ctx->gl()->hasExtension("GL_NV_fence")) { return true; } else if (GrGLGetVersion(ctx->gl()) >= GR_GL_VER(3, 0)) { return true; } else { return false; } } #else return false; #endif } void GLTestContext::init(sk_sp<const GrGLInterface> gl) { fGLInterface = std::move(gl); fOriginalGLInterface = fGLInterface; fFenceSupport = fence_is_supported(this); fGpuTimer = GLGpuTimer::MakeIfSupported(this); #ifndef SK_GL fWasInitialized = true; #endif } void GLTestContext::teardown() { fGLInterface.reset(); fOriginalGLInterface.reset(); INHERITED::teardown(); } void GLTestContext::testAbandon() { INHERITED::testAbandon(); #ifdef SK_GL if (fGLInterface) { fGLInterface->abandon(); fOriginalGLInterface->abandon(); } #endif } void GLTestContext::finish() { #ifdef SK_GL if (fGLInterface) { GR_GL_CALL(fGLInterface.get(), Finish()); } #endif } void GLTestContext::overrideVersion(const char* version, const char* shadingLanguageVersion) { #ifdef SK_GL // GrGLFunction has both a limited capture size and doesn't call a destructor when it is // initialized with a lambda. So here we're trusting fOriginalGLInterface will be kept alive. auto getString = [wrapped = &fOriginalGLInterface->fFunctions.fGetString, version, shadingLanguageVersion](GrGLenum name) { if (name == GR_GL_VERSION) { return reinterpret_cast<const GrGLubyte*>(version); } else if (name == GR_GL_SHADING_LANGUAGE_VERSION) { return reinterpret_cast<const GrGLubyte*>(shadingLanguageVersion); } return (*wrapped)(name); }; auto newInterface = sk_make_sp<GrGLInterface>(*fOriginalGLInterface); newInterface->fFunctions.fGetString = getString; fGLInterface = std::move(newInterface); #endif }; sk_sp<GrDirectContext> GLTestContext::makeContext(const GrContextOptions& options) { #ifdef SK_GL return GrDirectContext::MakeGL(fGLInterface, options); #else return nullptr; #endif } } // namespace sk_gpu_test <|endoftext|>
<commit_before>/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "OpenWireFormat.h" #include <activemq/util/Boolean.h> #include <activemq/util/Integer.h> #include <activemq/util/Long.h> #include <activemq/util/Guid.h> #include <activemq/util/Math.h> #include <activemq/io/ByteArrayOutputStream.h> #include <activemq/connector/openwire/utils/BooleanStream.h> #include <activemq/connector/openwire/commands/WireFormatInfo.h> #include <activemq/connector/openwire/commands/DataStructure.h> #include <activemq/connector/openwire/marshal/MarshalAware.h> #include <activemq/connector/openwire/marshal/DataStreamMarshaller.h> #include <activemq/connector/openwire/marshal/v2/MarshallerFactory.h> #include <activemq/connector/openwire/marshal/v1/MarshallerFactory.h> using namespace std; using namespace activemq; using namespace activemq::wireformat; using namespace activemq::io; using namespace activemq::util; using namespace activemq::connector; using namespace activemq::transport; using namespace activemq::exceptions; using namespace activemq::connector::openwire; using namespace activemq::connector::openwire::commands; using namespace activemq::connector::openwire::marshal; using namespace activemq::connector::openwire::utils; //////////////////////////////////////////////////////////////////////////////// const unsigned char OpenWireFormat::NULL_TYPE = 0; //////////////////////////////////////////////////////////////////////////////// OpenWireFormat::OpenWireFormat( const activemq::util::Properties& properties ) { // Copy config data this->properties.copy( &properties ); this->preferedWireFormatInfo = NULL; // Fill in that DataStreamMarshallers collection dataMarshallers.resize( 256 ); // Generate an ID this->id = Guid::createGUIDString(); // Set defaults for initial WireFormat negotiation this->version = 0; this->stackTraceEnabled = false; this->cacheEnabled = false; this->tcpNoDelayEnabled = false; this->tightEncodingEnabled = false; this->sizePrefixDisabled = false; // Set to Default as lowest common denominator, then we will try // and move up to the prefered when the wireformat is negotiated. this->setVersion( DEFAULT_VERSION ); } //////////////////////////////////////////////////////////////////////////////// OpenWireFormat::~OpenWireFormat() { try { this->destroyMarshalers(); delete preferedWireFormatInfo; } AMQ_CATCH_NOTHROW( ActiveMQException ) AMQ_CATCHALL_NOTHROW() } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::destroyMarshalers() { try { for( size_t i = 0; i < dataMarshallers.size(); ++i ) { delete dataMarshallers[i]; dataMarshallers[i] = NULL; } } AMQ_CATCH_NOTHROW( ActiveMQException ) AMQ_CATCHALL_NOTHROW() } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::setVersion( int version ) throw ( IllegalArgumentException ) { if( version == this->getVersion() ){ return; } // Clear old marshalers in preperation for the new set. this->destroyMarshalers(); this->version = version; switch( this->version ){ case 1: v1::MarshallerFactory().configure( this ); break; case 2: v2::MarshallerFactory().configure( this ); break; default: throw IllegalArgumentException( __FILE__, __LINE__, "OpenWireFormat::setVersion - " "Given Version: %d , is not supported", version ); } } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::addMarshaller( DataStreamMarshaller* marshaller ) { unsigned char type = marshaller->getDataStructureType(); dataMarshallers[type & 0xFF] = marshaller; } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::setPreferedWireFormatInfo( commands::WireFormatInfo* info ) throw ( IllegalStateException ) { delete preferedWireFormatInfo; this->preferedWireFormatInfo = info; } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::marshal( transport::Command* command, io::DataOutputStream* dataOut ) throw ( io::IOException ) { try { int size = 1; if( command != NULL ) { DataStructure* dataStructure = dynamic_cast< DataStructure* >( command ); unsigned char type = dataStructure->getDataStructureType(); DataStreamMarshaller* dsm = dataMarshallers[type & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( type ) ).c_str() ); } if( tightEncodingEnabled ) { BooleanStream bs; size += dsm->tightMarshal1( this, dataStructure, &bs ); size += bs.marshalledSize(); if( !sizePrefixDisabled ) { dataOut->writeInt( size ); } dataOut->writeByte( type ); bs.marshal( dataOut ); dsm->tightMarshal2( this, dataStructure, dataOut, &bs ); } else { DataOutputStream* looseOut = dataOut; ByteArrayOutputStream* baos = NULL; if( !sizePrefixDisabled ) { baos = new ByteArrayOutputStream(); looseOut = new DataOutputStream( baos ); } looseOut->writeByte( type ); dsm->looseMarshal( this, dataStructure, looseOut ); if( !sizePrefixDisabled ) { looseOut->close(); dataOut->writeInt( (int)baos->getByteArraySize() ); dataOut->write( baos->getByteArray(), baos->getByteArraySize() ); // Delete allocated resource delete baos; delete looseOut; } } } else { dataOut->writeInt( size ); dataOut->writeByte( NULL_TYPE ); } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// transport::Command* OpenWireFormat::unmarshal( io::DataInputStream* dis ) throw ( io::IOException ) { try { if( !sizePrefixDisabled ) { dis->readInt(); } // Get the unmarshalled DataStructure DataStructure* data = doUnmarshal( dis ); if( data == NULL ) { throw IOException( __FILE__, __LINE__, "OpenWireFormat::doUnmarshal - " "Failed to unmarshal an Object" ); } // Now all unmarshals from this level should result in an object // that is a transport::Command type, if its not then we throw an // exception. transport::Command* command = dynamic_cast< transport::Command* >( data ); if( command == NULL ) { delete data; throw IOException( __FILE__, __LINE__, "OpenWireFormat::doUnmarshal - " "Unmarshalled a non Command Type" ); } return command; } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// commands::DataStructure* OpenWireFormat::doUnmarshal( DataInputStream* dis ) throw ( IOException ) { try { unsigned char dataType = dis->readByte(); if( dataType != NULL_TYPE ) { DataStreamMarshaller* dsm = dynamic_cast< DataStreamMarshaller* >( dataMarshallers[dataType & 0xFF] ); if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } // Ask the DataStreamMarshaller to create a new instance of its // command so that we can fill in its data. DataStructure* data = dsm->createObject(); if( this->tightEncodingEnabled ) { BooleanStream bs; bs.unmarshal( dis ); dsm->tightUnmarshal( this, data, dis, &bs ); } else { dsm->looseUnmarshal( this, data, dis ); } return data; } return NULL; } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// int OpenWireFormat::tightMarshalNestedObject1( commands::DataStructure* object, utils::BooleanStream* bs ) throw ( io::IOException ) { try { bs->writeBoolean( object != NULL ); if( object == NULL ) { return 0; } if( object->isMarshalAware() ) { std::vector<unsigned char> sequence = object->getMarshaledForm(this); bs->writeBoolean( !sequence.empty() ); if( !sequence.empty() ) { return (int)(1 + sequence.size()); } } unsigned char type = object->getDataStructureType(); if( type == 0 ) { throw IOException( __FILE__, __LINE__, "No valid data structure type for object of this type"); } DataStreamMarshaller* dsm = dynamic_cast< DataStreamMarshaller* >( dataMarshallers[type & 0xFF] ); if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( type ) ).c_str() ); } return 1 + dsm->tightMarshal1( this, object, bs ); } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::tightMarshalNestedObject2( DataStructure* o, DataOutputStream* ds, BooleanStream* bs ) throw ( IOException ) { try { if( !bs->readBoolean() ) { return; } unsigned char type = o->getDataStructureType(); ds->writeByte(type); if( o->isMarshalAware() && bs->readBoolean() ) { MarshalAware* ma = dynamic_cast< MarshalAware* >( o ); vector<unsigned char> sequence = ma->getMarshaledForm( this ); ds->write( &sequence[0], sequence.size() ); } else { DataStreamMarshaller* dsm = dynamic_cast< DataStreamMarshaller* >( dataMarshallers[type & 0xFF] ); if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( type ) ).c_str() ); } dsm->tightMarshal2( this, o, ds, bs ); } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// DataStructure* OpenWireFormat::tightUnmarshalNestedObject( DataInputStream* dis, BooleanStream* bs ) throw ( io::IOException ) { try { if( bs->readBoolean() ) { const unsigned char dataType = dis->readByte(); DataStreamMarshaller* dsm = dynamic_cast< DataStreamMarshaller* >( dataMarshallers[dataType & 0xFF] ); if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } DataStructure* data = dsm->createObject(); if( data->isMarshalAware() && bs->readBoolean() ) { dis->readInt(); dis->readByte(); BooleanStream bs2; bs2.unmarshal( dis ); dsm->tightUnmarshal( this, data, dis, &bs2 ); } else { dsm->tightUnmarshal( this, data, dis, bs ); } return data; } else { return NULL; } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// DataStructure* OpenWireFormat::looseUnmarshalNestedObject( io::DataInputStream* dis ) throw ( IOException ) { try{ if( dis->readBoolean() ) { unsigned char dataType = dis->readByte(); DataStreamMarshaller* dsm = dynamic_cast< DataStreamMarshaller* >( dataMarshallers[dataType & 0xFF] ); if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } DataStructure* data = dsm->createObject(); dsm->looseUnmarshal( this, data, dis ); return data; } else { return NULL; } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::looseMarshalNestedObject( commands::DataStructure* o, io::DataOutputStream* dataOut ) throw ( io::IOException ) { try{ dataOut->writeBoolean( o != NULL ); if( o != NULL ) { unsigned char dataType = o->getDataStructureType(); dataOut->writeByte( dataType ); DataStreamMarshaller* dsm = dynamic_cast< DataStreamMarshaller* >( dataMarshallers[dataType & 0xFF] ); if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } dsm->looseMarshal( this, o, dataOut ); } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::renegotiateWireFormat( WireFormatInfo* info ) throw ( exceptions::IllegalStateException ) { if( preferedWireFormatInfo == NULL ) { throw IllegalStateException( __FILE__, __LINE__, "OpenWireFormat::renegotiateWireFormat - " "Wireformat cannot not be renegotiated." ); } this->setVersion( Math::min( preferedWireFormatInfo->getVersion(), info->getVersion() ) ); this->stackTraceEnabled = info->isStackTraceEnabled() && preferedWireFormatInfo->isStackTraceEnabled(); this->tcpNoDelayEnabled = info->isTcpNoDelayEnabled() && preferedWireFormatInfo->isTcpNoDelayEnabled(); this->cacheEnabled = info->isCacheEnabled() && preferedWireFormatInfo->isCacheEnabled(); this->tightEncodingEnabled = info->isTightEncodingEnabled() && preferedWireFormatInfo->isTightEncodingEnabled(); this->sizePrefixDisabled = info->isSizePrefixDisabled() && preferedWireFormatInfo->isSizePrefixDisabled(); } <commit_msg>https://issues.apache.org/activemq/browse/AMQCPP-142<commit_after>/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "OpenWireFormat.h" #include <activemq/util/Boolean.h> #include <activemq/util/Integer.h> #include <activemq/util/Long.h> #include <activemq/util/Guid.h> #include <activemq/util/Math.h> #include <activemq/io/ByteArrayOutputStream.h> #include <activemq/connector/openwire/utils/BooleanStream.h> #include <activemq/connector/openwire/commands/WireFormatInfo.h> #include <activemq/connector/openwire/commands/DataStructure.h> #include <activemq/connector/openwire/marshal/MarshalAware.h> #include <activemq/connector/openwire/marshal/DataStreamMarshaller.h> #include <activemq/connector/openwire/marshal/v2/MarshallerFactory.h> #include <activemq/connector/openwire/marshal/v1/MarshallerFactory.h> using namespace std; using namespace activemq; using namespace activemq::wireformat; using namespace activemq::io; using namespace activemq::util; using namespace activemq::connector; using namespace activemq::transport; using namespace activemq::exceptions; using namespace activemq::connector::openwire; using namespace activemq::connector::openwire::commands; using namespace activemq::connector::openwire::marshal; using namespace activemq::connector::openwire::utils; //////////////////////////////////////////////////////////////////////////////// const unsigned char OpenWireFormat::NULL_TYPE = 0; //////////////////////////////////////////////////////////////////////////////// OpenWireFormat::OpenWireFormat( const activemq::util::Properties& properties ) { // Copy config data this->properties.copy( &properties ); this->preferedWireFormatInfo = NULL; // Fill in that DataStreamMarshallers collection dataMarshallers.resize( 256 ); // Generate an ID this->id = Guid::createGUIDString(); // Set defaults for initial WireFormat negotiation this->version = 0; this->stackTraceEnabled = false; this->cacheEnabled = false; this->tcpNoDelayEnabled = false; this->tightEncodingEnabled = false; this->sizePrefixDisabled = false; // Set to Default as lowest common denominator, then we will try // and move up to the prefered when the wireformat is negotiated. this->setVersion( DEFAULT_VERSION ); } //////////////////////////////////////////////////////////////////////////////// OpenWireFormat::~OpenWireFormat() { try { this->destroyMarshalers(); delete preferedWireFormatInfo; } AMQ_CATCH_NOTHROW( ActiveMQException ) AMQ_CATCHALL_NOTHROW() } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::destroyMarshalers() { try { for( size_t i = 0; i < dataMarshallers.size(); ++i ) { delete dataMarshallers[i]; dataMarshallers[i] = NULL; } } AMQ_CATCH_NOTHROW( ActiveMQException ) AMQ_CATCHALL_NOTHROW() } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::setVersion( int version ) throw ( IllegalArgumentException ) { if( version == this->getVersion() ){ return; } // Clear old marshalers in preperation for the new set. this->destroyMarshalers(); this->version = version; switch( this->version ){ case 1: v1::MarshallerFactory().configure( this ); break; case 2: v2::MarshallerFactory().configure( this ); break; default: throw IllegalArgumentException( __FILE__, __LINE__, "OpenWireFormat::setVersion - " "Given Version: %d , is not supported", version ); } } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::addMarshaller( DataStreamMarshaller* marshaller ) { unsigned char type = marshaller->getDataStructureType(); dataMarshallers[type & 0xFF] = marshaller; } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::setPreferedWireFormatInfo( commands::WireFormatInfo* info ) throw ( IllegalStateException ) { delete preferedWireFormatInfo; this->preferedWireFormatInfo = info; } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::marshal( transport::Command* command, io::DataOutputStream* dataOut ) throw ( io::IOException ) { try { int size = 1; if( command != NULL ) { DataStructure* dataStructure = dynamic_cast< DataStructure* >( command ); unsigned char type = dataStructure->getDataStructureType(); DataStreamMarshaller* dsm = dataMarshallers[type & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( type ) ).c_str() ); } if( tightEncodingEnabled ) { BooleanStream bs; size += dsm->tightMarshal1( this, dataStructure, &bs ); size += bs.marshalledSize(); if( !sizePrefixDisabled ) { dataOut->writeInt( size ); } dataOut->writeByte( type ); bs.marshal( dataOut ); dsm->tightMarshal2( this, dataStructure, dataOut, &bs ); } else { DataOutputStream* looseOut = dataOut; ByteArrayOutputStream* baos = NULL; if( !sizePrefixDisabled ) { baos = new ByteArrayOutputStream(); looseOut = new DataOutputStream( baos ); } looseOut->writeByte( type ); dsm->looseMarshal( this, dataStructure, looseOut ); if( !sizePrefixDisabled ) { looseOut->close(); dataOut->writeInt( (int)baos->getByteArraySize() ); dataOut->write( baos->getByteArray(), baos->getByteArraySize() ); // Delete allocated resource delete baos; delete looseOut; } } } else { dataOut->writeInt( size ); dataOut->writeByte( NULL_TYPE ); } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// transport::Command* OpenWireFormat::unmarshal( io::DataInputStream* dis ) throw ( io::IOException ) { try { if( !sizePrefixDisabled ) { dis->readInt(); } // Get the unmarshalled DataStructure DataStructure* data = doUnmarshal( dis ); if( data == NULL ) { throw IOException( __FILE__, __LINE__, "OpenWireFormat::doUnmarshal - " "Failed to unmarshal an Object" ); } // Now all unmarshals from this level should result in an object // that is a transport::Command type, if its not then we throw an // exception. transport::Command* command = dynamic_cast< transport::Command* >( data ); if( command == NULL ) { delete data; throw IOException( __FILE__, __LINE__, "OpenWireFormat::doUnmarshal - " "Unmarshalled a non Command Type" ); } return command; } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// commands::DataStructure* OpenWireFormat::doUnmarshal( DataInputStream* dis ) throw ( IOException ) { try { unsigned char dataType = dis->readByte(); if( dataType != NULL_TYPE ) { DataStreamMarshaller* dsm = dynamic_cast< DataStreamMarshaller* >( dataMarshallers[dataType & 0xFF] ); if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } // Ask the DataStreamMarshaller to create a new instance of its // command so that we can fill in its data. DataStructure* data = dsm->createObject(); if( this->tightEncodingEnabled ) { BooleanStream bs; bs.unmarshal( dis ); dsm->tightUnmarshal( this, data, dis, &bs ); } else { dsm->looseUnmarshal( this, data, dis ); } return data; } return NULL; } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// int OpenWireFormat::tightMarshalNestedObject1( commands::DataStructure* object, utils::BooleanStream* bs ) throw ( io::IOException ) { try { bs->writeBoolean( object != NULL ); if( object == NULL ) { return 0; } if( object->isMarshalAware() ) { std::vector<unsigned char> sequence = object->getMarshaledForm(this); bs->writeBoolean( !sequence.empty() ); if( !sequence.empty() ) { return (int)(1 + sequence.size()); } } unsigned char type = object->getDataStructureType(); if( type == 0 ) { throw IOException( __FILE__, __LINE__, "No valid data structure type for object of this type"); } DataStreamMarshaller* dsm = dataMarshallers[type & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( type ) ).c_str() ); } return 1 + dsm->tightMarshal1( this, object, bs ); } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::tightMarshalNestedObject2( DataStructure* o, DataOutputStream* ds, BooleanStream* bs ) throw ( IOException ) { try { if( !bs->readBoolean() ) { return; } unsigned char type = o->getDataStructureType(); ds->writeByte(type); if( o->isMarshalAware() && bs->readBoolean() ) { MarshalAware* ma = dynamic_cast< MarshalAware* >( o ); vector<unsigned char> sequence = ma->getMarshaledForm( this ); ds->write( &sequence[0], sequence.size() ); } else { DataStreamMarshaller* dsm = dataMarshallers[type & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( type ) ).c_str() ); } dsm->tightMarshal2( this, o, ds, bs ); } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// DataStructure* OpenWireFormat::tightUnmarshalNestedObject( DataInputStream* dis, BooleanStream* bs ) throw ( io::IOException ) { try { if( bs->readBoolean() ) { const unsigned char dataType = dis->readByte(); DataStreamMarshaller* dsm = dataMarshallers[dataType & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } DataStructure* data = dsm->createObject(); if( data->isMarshalAware() && bs->readBoolean() ) { dis->readInt(); dis->readByte(); BooleanStream bs2; bs2.unmarshal( dis ); dsm->tightUnmarshal( this, data, dis, &bs2 ); } else { dsm->tightUnmarshal( this, data, dis, bs ); } return data; } else { return NULL; } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// DataStructure* OpenWireFormat::looseUnmarshalNestedObject( io::DataInputStream* dis ) throw ( IOException ) { try{ if( dis->readBoolean() ) { unsigned char dataType = dis->readByte(); DataStreamMarshaller* dsm = dataMarshallers[dataType & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } DataStructure* data = dsm->createObject(); dsm->looseUnmarshal( this, data, dis ); return data; } else { return NULL; } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::looseMarshalNestedObject( commands::DataStructure* o, io::DataOutputStream* dataOut ) throw ( io::IOException ) { try{ dataOut->writeBoolean( o != NULL ); if( o != NULL ) { unsigned char dataType = o->getDataStructureType(); dataOut->writeByte( dataType ); DataStreamMarshaller* dsm = dataMarshallers[dataType & 0xFF]; if( dsm == NULL ) { throw IOException( __FILE__, __LINE__, ( string( "OpenWireFormat::marshal - Unknown data type: " ) + Integer::toString( dataType ) ).c_str() ); } dsm->looseMarshal( this, o, dataOut ); } } AMQ_CATCH_RETHROW( IOException ) AMQ_CATCH_EXCEPTION_CONVERT( ActiveMQException, IOException ) AMQ_CATCHALL_THROW( IOException ) } //////////////////////////////////////////////////////////////////////////////// void OpenWireFormat::renegotiateWireFormat( WireFormatInfo* info ) throw ( exceptions::IllegalStateException ) { if( preferedWireFormatInfo == NULL ) { throw IllegalStateException( __FILE__, __LINE__, "OpenWireFormat::renegotiateWireFormat - " "Wireformat cannot not be renegotiated." ); } this->setVersion( Math::min( preferedWireFormatInfo->getVersion(), info->getVersion() ) ); this->stackTraceEnabled = info->isStackTraceEnabled() && preferedWireFormatInfo->isStackTraceEnabled(); this->tcpNoDelayEnabled = info->isTcpNoDelayEnabled() && preferedWireFormatInfo->isTcpNoDelayEnabled(); this->cacheEnabled = info->isCacheEnabled() && preferedWireFormatInfo->isCacheEnabled(); this->tightEncodingEnabled = info->isTightEncodingEnabled() && preferedWireFormatInfo->isTightEncodingEnabled(); this->sizePrefixDisabled = info->isSizePrefixDisabled() && preferedWireFormatInfo->isSizePrefixDisabled(); } <|endoftext|>
<commit_before>#include "PresentMonCsv.h" #include <../PresentMon/generated/version.h> #include <gtest/gtest.h> #include <strsafe.h> #include <windows.h> #define RETURN_ON_FATAL_FAILURE(_P) do { _P; if (::testing::Test::HasFatalFailure()) return; } while (0) std::string presentMonPath_; std::string testDir_; std::string outDir_; class GoldStandardTests : public ::testing::Test { public: struct Paths { std::string etl_; std::string goldCsv_; std::string testCsv_; } path_; explicit GoldStandardTests(Paths const& paths) : path_(paths) { } bool CreateOutputDirectories() const { auto path = (char*) &path_.testCsv_[0]; for (auto i = outDir_.size() - 1, n = path_.testCsv_.size(); i < n; ++i) { if (path[i] == '\\') { path[i] = '\0'; auto attr = GetFileAttributesA(path); if (attr == INVALID_FILE_ATTRIBUTES) { if (!CreateDirectoryA(path, NULL)) { return false; } } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0) { return false; } path[i] = '\\'; } } return true; } void TestBody() override { // Open the gold CSV PresentMonCsv goldCsv; RETURN_ON_FATAL_FAILURE(goldCsv.Open(path_.goldCsv_.c_str())); // Make sure output directory exists. ASSERT_TRUE(CreateOutputDirectories()); // Generate command line, querying gold CSV to try and match expected // data. std::string cmdline; cmdline += '\"'; cmdline += presentMonPath_; cmdline += "\" -stop_existing_session -no_top -etl_file \""; cmdline += path_.etl_; cmdline += "\" -output_file \""; cmdline += path_.testCsv_; cmdline += "\""; if (goldCsv.GetColumnIndex("AllowsTearing") == SIZE_MAX) { cmdline += " -simple"; } else if (goldCsv.GetColumnIndex("WasBatched") != SIZE_MAX) { cmdline += " -verbose"; } SCOPED_TRACE(cmdline); // Start PresentMon wait for it to complete. STARTUPINFOA si = {}; si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES; PROCESS_INFORMATION pi = {}; if (!CreateProcessA(nullptr, (LPSTR) cmdline.c_str(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &si, &pi)) { FAIL() << "Failed to start the PresentMon process."; } WaitForSingleObject(pi.hProcess, INFINITE); DWORD exitCode = 0; EXPECT_TRUE(GetExitCodeProcess(pi.hProcess, &exitCode)); EXPECT_EQ(exitCode, 0u); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); // Open test CSV file and check it has the same columns as gold PresentMonCsv testCsv; RETURN_ON_FATAL_FAILURE(testCsv.Open(path_.testCsv_.c_str())); RETURN_ON_FATAL_FAILURE(testCsv.CompareColumns(goldCsv)); // Compare gold/test CSV data rows UINT errorLineCount = 0; for (;;) { auto goldDone = !goldCsv.ReadRow(); auto testDone = !testCsv.ReadRow(); EXPECT_EQ(goldDone, testDone); if (goldDone || testDone) { break; } errorLineCount += goldCsv.CompareRow(testCsv, errorLineCount == 0, "GOLD", "TEST") ? 0 : 1; } goldCsv.Close(); testCsv.Close(); EXPECT_EQ(errorLineCount, 0u); } }; bool CheckGoldEtlCsvPair( char* relName, size_t relNameLen, GoldStandardTests::Paths* paths) { (void) relNameLen; // Confirm fileName is an ETL auto len = strlen(relName); if (len < 4 || _strnicmp(relName + len - 4, ".etl", 4) != 0) { return false; } paths->etl_ = testDir_; paths->etl_ += relName; // Check if there is a CSV with the same path/name but different extension relName[len - 3] = 'c'; relName[len - 2] = 's'; relName[len - 1] = 'v'; paths->goldCsv_ = testDir_; paths->goldCsv_ += relName; auto attr = GetFileAttributesA(paths->goldCsv_.c_str()); if (attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { return false; } // Create test CSV path paths->testCsv_ = outDir_; paths->testCsv_ += relName; // Prune off extension to use as test name relName[len - 4] = '\0'; return true; } void AddGoldEtlCsvTests( char const* dir) { GoldStandardTests::Paths paths; auto fnidx = strlen(dir); auto relidx = testDir_.size(); // Start listing files at dir/* char path[MAX_PATH]; if (fnidx + 1 >= _countof(path)) { return; } memcpy(path, dir, fnidx); path[fnidx + 0] = '*'; path[fnidx + 1] = '\0'; auto relName = path + relidx; auto relNameLen = _countof(path) - relidx; WIN32_FIND_DATAA ff = {}; auto h = FindFirstFileA(path, &ff); if (h == INVALID_HANDLE_VALUE) { return; } do { auto len = strlen(ff.cFileName); if (ff.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (len == 1 && ff.cFileName[0] == '.') continue; if (len == 2 && ff.cFileName[0] == '.' && ff.cFileName[1] == '.') continue; if (fnidx + len + 2 > _countof(path)) continue; memcpy(path + fnidx, ff.cFileName, len); memcpy(path + fnidx + len, "\\", 2); AddGoldEtlCsvTests(path); } else { if (fnidx + len + 1 > _countof(path)) continue; memcpy(path + fnidx, ff.cFileName, len + 1); if (CheckGoldEtlCsvPair(relName, relNameLen, &paths)) { ::testing::RegisterTest( "CsvCompareTests", relName, nullptr, nullptr, __FILE__, __LINE__, [=]() -> ::testing::Test* { return new GoldStandardTests(paths); }); } } } while (FindNextFileA(h, &ff) != 0); FindClose(h); } void DeleteDirectory( char const* dir) { char path[MAX_PATH]; auto fnidx = strlen(dir); if (fnidx + 1 >= _countof(path)) { return; } memcpy(path, dir, fnidx); path[fnidx + 0] = '*'; path[fnidx + 1] = '\0'; WIN32_FIND_DATAA ff = {}; auto h = FindFirstFileA(path, &ff); if (h == INVALID_HANDLE_VALUE) { return; } do { if (ff.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (strcmp(ff.cFileName, ".") != 0 && strcmp(ff.cFileName, "..") != 0) { strcpy_s(path + fnidx, _countof(path) - fnidx, ff.cFileName); DeleteDirectory(path); } } else { strcpy_s(path + fnidx, _countof(path) - fnidx, ff.cFileName); DeleteFileA(path); } } while (FindNextFileA(h, &ff) != 0); path[fnidx - 1] = '\0'; RemoveDirectoryA(path); FindClose(h); } bool CheckPath( char const* commandLineArg, std::string* str, char const* path, bool directory, bool* exists) { // If path not specified in command line, use default value if (path == nullptr) { path = str->c_str(); } // Get full path char fullPath[MAX_PATH]; auto r = GetFullPathNameA(path, _countof(fullPath), fullPath, nullptr); if (r == 0 || r > _countof(fullPath)) { fprintf(stderr, "error: could not get full path for: %s\n", path); fprintf(stderr, " Specify a new path using the %s command line argument.\n", commandLineArg); return false; } // Make sure file exists and is the right type (file vs directory). auto attr = GetFileAttributesA(fullPath); if (attr == INVALID_FILE_ATTRIBUTES) { if (exists == nullptr) { // must exist fprintf(stderr, "error: path does not exist: %s\n", fullPath); fprintf(stderr, " Specify a new path using the %s command line argument.\n", commandLineArg); return false; } *exists = false; } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != (directory ? FILE_ATTRIBUTE_DIRECTORY : 0u)) { fprintf(stderr, "error: path is not a %s: %s\n", directory ? "directory" : "file", fullPath); fprintf(stderr, " Specify a new path using the %s command line argument.\n", commandLineArg); return false; } // Update the string with the full path and end directories with separator. *str = fullPath; if (directory) { *str += '\\'; } return true; } void SetDefaults() { // PresentMon path presentMonPath_ = "PresentMon64-"; if (strncmp(PRESENT_MON_VERSION, "dev", 3) == 0) { presentMonPath_ += "dev"; } else { presentMonPath_ += PRESENT_MON_VERSION; } presentMonPath_ += ".exe"; // Test dir testDir_ = "../../../Tests/Gold"; // Output dir char path[MAX_PATH]; GetTempPathA(_countof(path), path); strcat_s(path, "PresentMonTestOutput"); outDir_ = path; } int main( int argc, char** argv) { // Put out usage before googletest auto help = false; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0 || strcmp(argv[i], "/?") == 0) { printf( "PresentMonTests.exe [options]\n" "options:\n" " --presentmon=path Path to the PresentMon exe path to test (default=%s).\n" " --testdir=path Path to directory of test ETLs and gold CSVs (default=%s).\n" " --outdir=path Path to directory for test outputs (default=%%temp%%/PresentMonTestOutput).\n" " --delete Delete output directory after tests, unless the directory already existed.\n" "\n", presentMonPath_.c_str(), testDir_.c_str()); help = true; break; } } // InitGoogleTest will remove the arguments it recognizes testing::InitGoogleTest(&argc, argv); if (help) { return 0; } // Set option defaults SetDefaults(); // Parse remaining command line arguments for custom commands. char* presentMonPath = nullptr; char* testDir = nullptr; char* outDir = nullptr; bool deleteOutDir = false; for (int i = 1; i < argc; ++i) { if (_strnicmp(argv[i], "--presentmon=", 13) == 0) { presentMonPath = argv[i] + 13; continue; } if (_strnicmp(argv[i], "--testdir=", 10) == 0) { testDir = argv[i] + 10; continue; } if (_strnicmp(argv[i], "--outdir=", 9) == 0) { outDir = argv[i] + 9; continue; } if (_stricmp(argv[i], "--delete") == 0) { deleteOutDir = true; continue; } fprintf(stderr, "error: unrecognized command line argument: %s.\n", argv[i]); fprintf(stderr, " Use --help command line argument for usage.\n"); return 1; } // Check command line arguments... bool outDirExisted = true; if (!CheckPath("--presentmon", &presentMonPath_, presentMonPath, false, nullptr) || !CheckPath("--testdir", &testDir_, testDir, true, nullptr) || !CheckPath("--outdir", &outDir_, outDir, true, &outDirExisted)) { return 1; } // Search test dir for gold ETL/CSV test pairs. AddGoldEtlCsvTests(testDir_.c_str()); // Run all the tests int result = RUN_ALL_TESTS(); // If we created the output directory, and the user requested it, delete // the output directory. if (deleteOutDir) { if (outDirExisted) { fprintf(stderr, "warning: output directory existed before running tests, and won't be deleted.\n"); } else { DeleteDirectory(outDir_.c_str()); } } return result; } <commit_msg>Add source license header<commit_after>/* Copyright 2020 Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "PresentMonCsv.h" #include <../PresentMon/generated/version.h> #include <gtest/gtest.h> #include <strsafe.h> #include <windows.h> #define RETURN_ON_FATAL_FAILURE(_P) do { _P; if (::testing::Test::HasFatalFailure()) return; } while (0) std::string presentMonPath_; std::string testDir_; std::string outDir_; class GoldStandardTests : public ::testing::Test { public: struct Paths { std::string etl_; std::string goldCsv_; std::string testCsv_; } path_; explicit GoldStandardTests(Paths const& paths) : path_(paths) { } bool CreateOutputDirectories() const { auto path = (char*) &path_.testCsv_[0]; for (auto i = outDir_.size() - 1, n = path_.testCsv_.size(); i < n; ++i) { if (path[i] == '\\') { path[i] = '\0'; auto attr = GetFileAttributesA(path); if (attr == INVALID_FILE_ATTRIBUTES) { if (!CreateDirectoryA(path, NULL)) { return false; } } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0) { return false; } path[i] = '\\'; } } return true; } void TestBody() override { // Open the gold CSV PresentMonCsv goldCsv; RETURN_ON_FATAL_FAILURE(goldCsv.Open(path_.goldCsv_.c_str())); // Make sure output directory exists. ASSERT_TRUE(CreateOutputDirectories()); // Generate command line, querying gold CSV to try and match expected // data. std::string cmdline; cmdline += '\"'; cmdline += presentMonPath_; cmdline += "\" -stop_existing_session -no_top -etl_file \""; cmdline += path_.etl_; cmdline += "\" -output_file \""; cmdline += path_.testCsv_; cmdline += "\""; if (goldCsv.GetColumnIndex("AllowsTearing") == SIZE_MAX) { cmdline += " -simple"; } else if (goldCsv.GetColumnIndex("WasBatched") != SIZE_MAX) { cmdline += " -verbose"; } SCOPED_TRACE(cmdline); // Start PresentMon wait for it to complete. STARTUPINFOA si = {}; si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES; PROCESS_INFORMATION pi = {}; if (!CreateProcessA(nullptr, (LPSTR) cmdline.c_str(), nullptr, nullptr, TRUE, 0, nullptr, nullptr, &si, &pi)) { FAIL() << "Failed to start the PresentMon process."; } WaitForSingleObject(pi.hProcess, INFINITE); DWORD exitCode = 0; EXPECT_TRUE(GetExitCodeProcess(pi.hProcess, &exitCode)); EXPECT_EQ(exitCode, 0u); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); // Open test CSV file and check it has the same columns as gold PresentMonCsv testCsv; RETURN_ON_FATAL_FAILURE(testCsv.Open(path_.testCsv_.c_str())); RETURN_ON_FATAL_FAILURE(testCsv.CompareColumns(goldCsv)); // Compare gold/test CSV data rows UINT errorLineCount = 0; for (;;) { auto goldDone = !goldCsv.ReadRow(); auto testDone = !testCsv.ReadRow(); EXPECT_EQ(goldDone, testDone); if (goldDone || testDone) { break; } errorLineCount += goldCsv.CompareRow(testCsv, errorLineCount == 0, "GOLD", "TEST") ? 0 : 1; } goldCsv.Close(); testCsv.Close(); EXPECT_EQ(errorLineCount, 0u); } }; bool CheckGoldEtlCsvPair( char* relName, size_t relNameLen, GoldStandardTests::Paths* paths) { (void) relNameLen; // Confirm fileName is an ETL auto len = strlen(relName); if (len < 4 || _strnicmp(relName + len - 4, ".etl", 4) != 0) { return false; } paths->etl_ = testDir_; paths->etl_ += relName; // Check if there is a CSV with the same path/name but different extension relName[len - 3] = 'c'; relName[len - 2] = 's'; relName[len - 1] = 'v'; paths->goldCsv_ = testDir_; paths->goldCsv_ += relName; auto attr = GetFileAttributesA(paths->goldCsv_.c_str()); if (attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { return false; } // Create test CSV path paths->testCsv_ = outDir_; paths->testCsv_ += relName; // Prune off extension to use as test name relName[len - 4] = '\0'; return true; } void AddGoldEtlCsvTests( char const* dir) { GoldStandardTests::Paths paths; auto fnidx = strlen(dir); auto relidx = testDir_.size(); // Start listing files at dir/* char path[MAX_PATH]; if (fnidx + 1 >= _countof(path)) { return; } memcpy(path, dir, fnidx); path[fnidx + 0] = '*'; path[fnidx + 1] = '\0'; auto relName = path + relidx; auto relNameLen = _countof(path) - relidx; WIN32_FIND_DATAA ff = {}; auto h = FindFirstFileA(path, &ff); if (h == INVALID_HANDLE_VALUE) { return; } do { auto len = strlen(ff.cFileName); if (ff.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (len == 1 && ff.cFileName[0] == '.') continue; if (len == 2 && ff.cFileName[0] == '.' && ff.cFileName[1] == '.') continue; if (fnidx + len + 2 > _countof(path)) continue; memcpy(path + fnidx, ff.cFileName, len); memcpy(path + fnidx + len, "\\", 2); AddGoldEtlCsvTests(path); } else { if (fnidx + len + 1 > _countof(path)) continue; memcpy(path + fnidx, ff.cFileName, len + 1); if (CheckGoldEtlCsvPair(relName, relNameLen, &paths)) { ::testing::RegisterTest( "CsvCompareTests", relName, nullptr, nullptr, __FILE__, __LINE__, [=]() -> ::testing::Test* { return new GoldStandardTests(paths); }); } } } while (FindNextFileA(h, &ff) != 0); FindClose(h); } void DeleteDirectory( char const* dir) { char path[MAX_PATH]; auto fnidx = strlen(dir); if (fnidx + 1 >= _countof(path)) { return; } memcpy(path, dir, fnidx); path[fnidx + 0] = '*'; path[fnidx + 1] = '\0'; WIN32_FIND_DATAA ff = {}; auto h = FindFirstFileA(path, &ff); if (h == INVALID_HANDLE_VALUE) { return; } do { if (ff.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { if (strcmp(ff.cFileName, ".") != 0 && strcmp(ff.cFileName, "..") != 0) { strcpy_s(path + fnidx, _countof(path) - fnidx, ff.cFileName); DeleteDirectory(path); } } else { strcpy_s(path + fnidx, _countof(path) - fnidx, ff.cFileName); DeleteFileA(path); } } while (FindNextFileA(h, &ff) != 0); path[fnidx - 1] = '\0'; RemoveDirectoryA(path); FindClose(h); } bool CheckPath( char const* commandLineArg, std::string* str, char const* path, bool directory, bool* exists) { // If path not specified in command line, use default value if (path == nullptr) { path = str->c_str(); } // Get full path char fullPath[MAX_PATH]; auto r = GetFullPathNameA(path, _countof(fullPath), fullPath, nullptr); if (r == 0 || r > _countof(fullPath)) { fprintf(stderr, "error: could not get full path for: %s\n", path); fprintf(stderr, " Specify a new path using the %s command line argument.\n", commandLineArg); return false; } // Make sure file exists and is the right type (file vs directory). auto attr = GetFileAttributesA(fullPath); if (attr == INVALID_FILE_ATTRIBUTES) { if (exists == nullptr) { // must exist fprintf(stderr, "error: path does not exist: %s\n", fullPath); fprintf(stderr, " Specify a new path using the %s command line argument.\n", commandLineArg); return false; } *exists = false; } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != (directory ? FILE_ATTRIBUTE_DIRECTORY : 0u)) { fprintf(stderr, "error: path is not a %s: %s\n", directory ? "directory" : "file", fullPath); fprintf(stderr, " Specify a new path using the %s command line argument.\n", commandLineArg); return false; } // Update the string with the full path and end directories with separator. *str = fullPath; if (directory) { *str += '\\'; } return true; } void SetDefaults() { // PresentMon path presentMonPath_ = "PresentMon64-"; if (strncmp(PRESENT_MON_VERSION, "dev", 3) == 0) { presentMonPath_ += "dev"; } else { presentMonPath_ += PRESENT_MON_VERSION; } presentMonPath_ += ".exe"; // Test dir testDir_ = "../../../Tests/Gold"; // Output dir char path[MAX_PATH]; GetTempPathA(_countof(path), path); strcat_s(path, "PresentMonTestOutput"); outDir_ = path; } int main( int argc, char** argv) { // Put out usage before googletest auto help = false; for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-?") == 0 || strcmp(argv[i], "/?") == 0) { printf( "PresentMonTests.exe [options]\n" "options:\n" " --presentmon=path Path to the PresentMon exe path to test (default=%s).\n" " --testdir=path Path to directory of test ETLs and gold CSVs (default=%s).\n" " --outdir=path Path to directory for test outputs (default=%%temp%%/PresentMonTestOutput).\n" " --delete Delete output directory after tests, unless the directory already existed.\n" "\n", presentMonPath_.c_str(), testDir_.c_str()); help = true; break; } } // InitGoogleTest will remove the arguments it recognizes testing::InitGoogleTest(&argc, argv); if (help) { return 0; } // Set option defaults SetDefaults(); // Parse remaining command line arguments for custom commands. char* presentMonPath = nullptr; char* testDir = nullptr; char* outDir = nullptr; bool deleteOutDir = false; for (int i = 1; i < argc; ++i) { if (_strnicmp(argv[i], "--presentmon=", 13) == 0) { presentMonPath = argv[i] + 13; continue; } if (_strnicmp(argv[i], "--testdir=", 10) == 0) { testDir = argv[i] + 10; continue; } if (_strnicmp(argv[i], "--outdir=", 9) == 0) { outDir = argv[i] + 9; continue; } if (_stricmp(argv[i], "--delete") == 0) { deleteOutDir = true; continue; } fprintf(stderr, "error: unrecognized command line argument: %s.\n", argv[i]); fprintf(stderr, " Use --help command line argument for usage.\n"); return 1; } // Check command line arguments... bool outDirExisted = true; if (!CheckPath("--presentmon", &presentMonPath_, presentMonPath, false, nullptr) || !CheckPath("--testdir", &testDir_, testDir, true, nullptr) || !CheckPath("--outdir", &outDir_, outDir, true, &outDirExisted)) { return 1; } // Search test dir for gold ETL/CSV test pairs. AddGoldEtlCsvTests(testDir_.c_str()); // Run all the tests int result = RUN_ALL_TESTS(); // If we created the output directory, and the user requested it, delete // the output directory. if (deleteOutDir) { if (outDirExisted) { fprintf(stderr, "warning: output directory existed before running tests, and won't be deleted.\n"); } else { DeleteDirectory(outDir_.c_str()); } } return result; } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <vector> #include <sstream> #include <string> #include <math.h> using namespace std; bool controllo(string x); struct dato { float valore; float errore; }; int main (int argc, char *argv[]) { ifstream leggi(argv[1]); ofstream scrivi("output.txt"); if(!leggi.is_open()) { cout << "Impossibile aprire il file" << endl; return -1; } vector<float> tempo; vector<dato> veloc; int i=0; string temp; getline(leggi, temp); // scarto la prima riga while(getline(leggi, temp)) { if (controllo(temp)) break; i++; istringstream iss(temp); float a; iss >> a; tempo.push_back(a); } while(i>0) { getline(leggi, temp); //scarto la seconda "riga titolo" if (controllo(temp)) break; istringstream iss(temp); float a, c; iss >> a >> c >> c; veloc.push_back(dato{a, c}); i--; } if(leggi.bad()) { cout << "Impossibile leggere il file" << endl; return -1; } //Interpolo float x1, y1, x2, xy, e=0; for (int k = 0; k < tempo.size(); k++){ x1=x1+tempo[k]*tempo[k]; y1=y1+veloc[k].valore; x2=x2+tempo[k]; xy=xy+tempo[k]*veloc[k].valore; } float delta=tempo.size()*x1-x2*x2; float a=(x1*y1-x2*xy)/delta; float b=(xy*tempo.size()-x2*y1)/delta; for (int k = 0; k < tempo.size(); k++){ e=((a+b*tempo[k])-veloc[k].valore); e=e*e; } e=sqrt(e/(tempo.size()-2)); float eA=e*sqrt(x1/delta); float eB=e*sqrt(tempo.size()/delta); scrivi << "Tempo (s)\tVelocità (m/s)\t Errore velocità (m/s)" << endl; //da controllare for (int k = 0; k < tempo.size(); k++){ scrivi << tempo[k] << "\t" << veloc[k].valore << "\t" << veloc[k].errore << endl; } scrivi << "a è " << a << ", b è " << b << endl; scrivi << "Dev y è " << e << endl; scrivi << "Dev.std di a è " << eA << " e dev.std di b è " << eB; return 0; } bool controllo(string x){ for(auto w:x) { if(isalpha(w) || (isspace(w) && !isblank(w))) return 1; //da migliorare else return 0; } } //http://stackoverflow.com/questions/7868936/read-file-line-by-line //http://en.cppreference.com/w/cpp/string/byte/isdigit http://www.cprogramming.com/tutorial/lesson2.html <commit_msg>Sistemata inizializzazione<commit_after>#include <iostream> #include <fstream> #include <vector> #include <sstream> #include <string> #include <math.h> using namespace std; bool controllo(string x); struct dato { float valore; float errore; }; int main (int argc, char *argv[]) { ifstream leggi(argv[1]); ofstream scrivi("output.txt"); if(!leggi.is_open()) { cout << "Impossibile aprire il file" << endl; return -1; } vector<float> tempo; vector<dato> veloc; int i=0; string temp; getline(leggi, temp); // scarto la prima riga while(getline(leggi, temp)) { if (controllo(temp)) break; i++; istringstream iss(temp); float a; iss >> a; tempo.push_back(a); } while(i>0) { getline(leggi, temp); //scarto la seconda "riga titolo" if (controllo(temp)) break; istringstream iss(temp); float a, c; iss >> a >> c >> c; veloc.push_back(dato{a, c}); i--; } if(leggi.bad()) { cout << "Impossibile leggere il file" << endl; return -1; } //Interpolo float x1=0, y1=0, x2=0, xy=0, e=0; for (int k = 0; k < tempo.size(); k++){ x1+=tempo[k]*tempo[k]; y1+=veloc[k].valore; x2+=tempo[k]; xy+=tempo[k]*veloc[k].valore; } float delta=tempo.size()*x1-x2*x2; float a=(x1*y1-x2*xy)/delta; float b=(xy*tempo.size()-x2*y1)/delta; for (int k = 0; k < tempo.size(); k++){ e+=((a+b*tempo[k])-veloc[k].valore)*((a+b*tempo[k])-veloc[k].valore); } e=sqrt(e/(tempo.size()-2)); float eA=e*sqrt(x1/delta); float eB=e*sqrt(tempo.size()/delta); scrivi << "Tempo (s)\tVelocità (m/s)\t Errore velocità (m/s)" << endl; //da controllare for (int k = 0; k < tempo.size(); k++){ scrivi << tempo[k] << "\t" << veloc[k].valore << "\t" << veloc[k].errore << endl; } scrivi << "a è " << a << ", b è " << b << endl; scrivi << "Dev y è " << e << endl; scrivi << "Dev.std di a è " << eA << " e dev.std di b è " << eB; return 0; } bool controllo(string x){ for(auto w:x) { if(isalpha(w) || (isspace(w) && !isblank(w))) return 1; //da migliorare else return 0; } } //http://stackoverflow.com/questions/7868936/read-file-line-by-line //http://en.cppreference.com/w/cpp/string/byte/isdigit http://www.cprogramming.com/tutorial/lesson2.html <|endoftext|>
<commit_before>// ========================================================================== // // This file is part of DO++, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2013 David Ok <david.ok8@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #include <gtest/gtest.h> #include <DO/KDTree.hpp> using namespace DO; using namespace std; class TestKDTree : public testing::Test { protected: MatrixXd data; size_t num_points; size_t num_points_in_circle; TestKDTree() { // We construct two sets in points. The first one lives in the // zero-centered unit circle and the second in the zero-centered // circle with radius 10. num_points_in_circle = 5; num_points = 2*num_points_in_circle; data.resize(2, num_points); const size_t& N = num_points_in_circle; for (size_t i = 0; i < N; ++i) { double theta = i / (2*N*M_PI); data.col(i) << cos(theta), sin(theta); } for (size_t i = N; i < 2*N; ++i) { double theta = i / (2*N*M_PI); data.col(i) << 10*cos(theta), 10*sin(theta); } } }; TEST_F(TestKDTree, test_simple_knn_search) { KDTree tree(data); Vector2d query = Vector2d::Zero(); size_t num_nearest_neighbors = num_points_in_circle; vector<int> indices; vector<double> squared_distances; tree.knn_search(query, num_nearest_neighbors, indices, squared_distances); EXPECT_EQ(indices.size(), num_nearest_neighbors); for (size_t j = 0; j < indices.size(); ++j) { EXPECT_LE(indices[j], num_nearest_neighbors); EXPECT_NEAR(squared_distances[j], 1., 1e-10); } } TEST_F(TestKDTree, test_simple_radius_search) { // Input data. KDTree tree(data); Vector2d query = Vector2d::Zero(); size_t num_nearest_neighbors = num_points_in_circle; double squared_search_radius = 1.0001; // In-out data. vector<int> nn_indices; vector<double> nn_squared_distances; // Output data. int num_found_neighbors; // First use case: we want to examine the squared distances. num_found_neighbors = tree.radius_search( query, squared_search_radius, nn_indices, nn_squared_distances); EXPECT_EQ(nn_indices.size(), num_nearest_neighbors); EXPECT_EQ(num_found_neighbors, num_nearest_neighbors); for (size_t j = 0; j < nn_indices.size(); ++j) { EXPECT_LE(nn_indices[j], num_nearest_neighbors); EXPECT_NEAR(nn_squared_distances[j], 1., 1e-10); } // Second use case: we want to limit the number of neighbors to return. size_t max_num_nearest_neighbors = 2; num_found_neighbors = tree.radius_search(query, squared_search_radius, nn_indices, nn_squared_distances, max_num_nearest_neighbors); EXPECT_EQ(nn_indices.size(), max_num_nearest_neighbors); EXPECT_EQ(num_found_neighbors, max_num_nearest_neighbors); for (size_t j = 0; j < nn_indices.size(); ++j) { EXPECT_LE(nn_indices[j], num_nearest_neighbors); EXPECT_NEAR(nn_squared_distances[j], 1., 1e-10); } } TEST_F(TestKDTree, test_simple_knn_search_with_query_point_in_data) { KDTree tree(data); size_t query_index = 0; size_t num_nearest_neighbors = num_points_in_circle-1; vector<int> indices; vector<double> squared_distances; tree.knn_search(query_index, num_nearest_neighbors, indices, squared_distances); EXPECT_EQ(indices.size(), num_nearest_neighbors); for (size_t j = 0; j < indices.size(); ++j) { EXPECT_LE(indices[j], num_nearest_neighbors); EXPECT_LE(squared_distances[j], 2.); } } TEST_F(TestKDTree, test_simple_radius_search_with_query_point_in_data) { // Input data. KDTree tree(data); size_t query = 0; size_t num_nearest_neighbors = num_points_in_circle-1; double squared_search_radius = 2.0001; // In-out data. vector<int> nn_indices; vector<double> nn_squared_distances; // Output data. int num_found_neighbors; // First use case: we want to examine the squared distances. num_found_neighbors = tree.radius_search( query, squared_search_radius, nn_indices, nn_squared_distances); EXPECT_EQ(nn_indices.size(), num_nearest_neighbors); EXPECT_EQ(num_found_neighbors, num_nearest_neighbors); for (size_t j = 0; j < nn_indices.size(); ++j) { EXPECT_LE(nn_indices[j], num_nearest_neighbors); EXPECT_LE(nn_squared_distances[j], 2.); } // Second use case: we want to limit the number of neighbors to return. size_t max_num_nearest_neighbors = 2; tree.radius_search(query, squared_search_radius, nn_indices, nn_squared_distances, max_num_nearest_neighbors); EXPECT_EQ(nn_indices.size(), max_num_nearest_neighbors); EXPECT_EQ(num_found_neighbors, num_nearest_neighbors); for (size_t j = 0; j < nn_indices.size(); ++j) { EXPECT_LE(nn_indices[j], num_nearest_neighbors); EXPECT_LE(nn_squared_distances[j], 2.); } } TEST_F(TestKDTree, test_batch_knn_search) { KDTree tree(data); const size_t& num_queries = num_points_in_circle; const size_t& num_nearest_neighbors = num_points_in_circle; MatrixXd queries(data.leftCols(num_queries)); vector<vector<int> > indices; vector<vector<double> > squared_distances; tree.knn_search(queries, num_nearest_neighbors, indices, squared_distances); EXPECT_EQ(indices.size(), num_queries); for (size_t i = 0; i < num_queries; ++i) { EXPECT_EQ(indices[i].size(), num_queries); for (size_t j = 0; j < indices[i].size(); ++j) { EXPECT_LE(indices[i][j], num_queries); EXPECT_LE(squared_distances[i][j], 2.); } } } TEST_F(TestKDTree, test_batch_radius_search) { // Input data. KDTree tree(data); const size_t& num_queries = num_points_in_circle; MatrixXd queries(data.leftCols(num_queries)); double squared_search_radius = 2.0001; // In-out data. vector<vector<int> > nn_indices; vector<vector<double> > nn_squared_distances; // First use case: we want to examine the squared distances. tree.radius_search( queries, squared_search_radius, nn_indices, nn_squared_distances); EXPECT_EQ(nn_indices.size(), num_queries); for (size_t i = 0; i < num_queries; ++i) { EXPECT_EQ(nn_indices[i].size(), num_queries); for (size_t j = 0; j < nn_indices[i].size(); ++j) { EXPECT_LE(nn_indices[i][j], num_queries); EXPECT_LE(nn_squared_distances[i][j], 2.); } } // Second use case: we want to limit the number of neighbors to return. size_t max_num_nearest_neighbors = 2; tree.radius_search(queries, squared_search_radius, nn_indices, nn_squared_distances, max_num_nearest_neighbors); EXPECT_EQ(nn_indices.size(), num_queries); for (size_t i = 0; i < num_queries; ++i) { EXPECT_EQ(nn_indices[i].size(), max_num_nearest_neighbors); for (size_t j = 0; j < nn_indices[i].size(); ++j) { EXPECT_LE(nn_indices[i][j], num_queries); EXPECT_LE(nn_squared_distances[i][j], 2.); } } } TEST_F(TestKDTree, test_batch_knn_search_with_query_point_in_data) { KDTree tree(data); const size_t num_queries = num_points_in_circle; const size_t num_nearest_neighbors = num_points_in_circle-1; vector<size_t> queries(num_queries); for (size_t i = 0; i != queries.size(); ++i) queries[i] = i; vector<vector<int> > indices; vector<vector<double> > squared_distances; tree.knn_search(queries, num_nearest_neighbors, indices, squared_distances); EXPECT_EQ(indices.size(), num_queries); for (size_t i = 0; i != indices.size(); ++i) { EXPECT_EQ(indices[i].size(), num_nearest_neighbors); for (size_t j = 0; j < indices[i].size(); ++j) { EXPECT_LE(indices[i][j], num_nearest_neighbors); EXPECT_LE(squared_distances[i][j], 2.); } } } TEST_F(TestKDTree, test_batch_radius_search_with_query_point_in_data) { // Input data. KDTree tree(data); const size_t& num_queries = num_points_in_circle; vector<size_t> queries; for (size_t i = 0; i < num_queries; ++i) queries.push_back(i); double squared_search_radius = 2.0001; // In-out data. vector<vector<int> > nn_indices; vector<vector<double> > nn_squared_distances; // First use case: we want to examine the squared distances. tree.radius_search( queries, squared_search_radius, nn_indices, nn_squared_distances); EXPECT_EQ(nn_indices.size(), num_queries); for (size_t i = 0; i < num_queries; ++i) { EXPECT_EQ(nn_indices[i].size(), num_queries-1); for (size_t j = 0; j < nn_indices[i].size(); ++j) { EXPECT_LE(nn_indices[i][j], num_queries); EXPECT_LE(nn_squared_distances[i][j], 2.); } } // Second use case: we want to limit the number of neighbors to return. size_t max_num_nearest_neighbors = 2; tree.radius_search(queries, squared_search_radius, nn_indices, nn_squared_distances, max_num_nearest_neighbors); EXPECT_EQ(nn_indices.size(), num_queries); for (size_t i = 0; i < num_queries; ++i) { EXPECT_EQ(nn_indices[i].size(), max_num_nearest_neighbors); for (size_t j = 0; j < nn_indices[i].size(); ++j) { EXPECT_LE(nn_indices[i][j], num_queries); EXPECT_LE(nn_squared_distances[i][j], 2.); } } } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<commit_msg>Fix test case for batch radius search.<commit_after>// ========================================================================== // // This file is part of DO++, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2013 David Ok <david.ok8@gmail.com> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // #include <gtest/gtest.h> #include <DO/KDTree.hpp> using namespace DO; using namespace std; class TestKDTree : public testing::Test { protected: MatrixXd data; size_t num_points; size_t num_points_in_circle; TestKDTree() { // We construct two sets in points. The first one lives in the // zero-centered unit circle and the second in the zero-centered // circle with radius 10. num_points_in_circle = 5; num_points = 2*num_points_in_circle; data.resize(2, num_points); const size_t& N = num_points_in_circle; for (size_t i = 0; i < N; ++i) { double theta = i / (2*N*M_PI); data.col(i) << cos(theta), sin(theta); } for (size_t i = N; i < 2*N; ++i) { double theta = i / (2*N*M_PI); data.col(i) << 10*cos(theta), 10*sin(theta); } } }; TEST_F(TestKDTree, test_simple_knn_search) { KDTree tree(data); Vector2d query = Vector2d::Zero(); size_t num_nearest_neighbors = num_points_in_circle; vector<int> indices; vector<double> squared_distances; tree.knn_search(query, num_nearest_neighbors, indices, squared_distances); EXPECT_EQ(indices.size(), num_nearest_neighbors); for (size_t j = 0; j < indices.size(); ++j) { EXPECT_LE(indices[j], num_nearest_neighbors); EXPECT_NEAR(squared_distances[j], 1., 1e-10); } } TEST_F(TestKDTree, test_simple_radius_search) { // Input data. KDTree tree(data); Vector2d query = Vector2d::Zero(); size_t num_nearest_neighbors = num_points_in_circle; double squared_search_radius = 1.0001; // In-out data. vector<int> nn_indices; vector<double> nn_squared_distances; // Output data. int num_found_neighbors; // First use case: we want to examine the squared distances. num_found_neighbors = tree.radius_search( query, squared_search_radius, nn_indices, nn_squared_distances); EXPECT_EQ(nn_indices.size(), num_nearest_neighbors); EXPECT_EQ(num_found_neighbors, num_nearest_neighbors); for (size_t j = 0; j < nn_indices.size(); ++j) { EXPECT_LE(nn_indices[j], num_nearest_neighbors); EXPECT_NEAR(nn_squared_distances[j], 1., 1e-10); } // Second use case: we want to limit the number of neighbors to return. size_t max_num_nearest_neighbors = 2; num_found_neighbors = tree.radius_search(query, squared_search_radius, nn_indices, nn_squared_distances, max_num_nearest_neighbors); EXPECT_EQ(nn_indices.size(), max_num_nearest_neighbors); EXPECT_EQ(num_found_neighbors, max_num_nearest_neighbors); for (size_t j = 0; j < nn_indices.size(); ++j) { EXPECT_LE(nn_indices[j], num_nearest_neighbors); EXPECT_NEAR(nn_squared_distances[j], 1., 1e-10); } } TEST_F(TestKDTree, test_simple_knn_search_with_query_point_in_data) { KDTree tree(data); size_t query_index = 0; size_t num_nearest_neighbors = num_points_in_circle-1; vector<int> indices; vector<double> squared_distances; tree.knn_search(query_index, num_nearest_neighbors, indices, squared_distances); EXPECT_EQ(indices.size(), num_nearest_neighbors); for (size_t j = 0; j < indices.size(); ++j) { EXPECT_LE(indices[j], num_nearest_neighbors); EXPECT_LE(squared_distances[j], 2.); } } TEST_F(TestKDTree, test_simple_radius_search_with_query_point_in_data) { // Input data. KDTree tree(data); size_t query = 0; size_t num_nearest_neighbors = num_points_in_circle-1; double squared_search_radius = 2.0001; // In-out data. vector<int> nn_indices; vector<double> nn_squared_distances; // Output data. int num_found_neighbors; // First use case: we want to examine the squared distances. num_found_neighbors = tree.radius_search( query, squared_search_radius, nn_indices, nn_squared_distances); EXPECT_EQ(nn_indices.size(), num_nearest_neighbors); EXPECT_EQ(num_found_neighbors, num_nearest_neighbors); for (size_t j = 0; j < nn_indices.size(); ++j) { EXPECT_LE(nn_indices[j], num_nearest_neighbors); EXPECT_LE(nn_squared_distances[j], 2.); } // Second use case: we want to limit the number of neighbors to return. size_t max_num_nearest_neighbors = 2; num_found_neighbors = tree.radius_search(query, squared_search_radius, nn_indices, nn_squared_distances, max_num_nearest_neighbors); EXPECT_EQ(nn_indices.size(), max_num_nearest_neighbors); EXPECT_EQ(num_found_neighbors, max_num_nearest_neighbors); for (size_t j = 0; j < nn_indices.size(); ++j) { EXPECT_LE(nn_indices[j], num_nearest_neighbors); EXPECT_LE(nn_squared_distances[j], 2.); } } TEST_F(TestKDTree, test_batch_knn_search) { KDTree tree(data); const size_t& num_queries = num_points_in_circle; const size_t& num_nearest_neighbors = num_points_in_circle; MatrixXd queries(data.leftCols(num_queries)); vector<vector<int> > indices; vector<vector<double> > squared_distances; tree.knn_search(queries, num_nearest_neighbors, indices, squared_distances); EXPECT_EQ(indices.size(), num_queries); for (size_t i = 0; i < num_queries; ++i) { EXPECT_EQ(indices[i].size(), num_queries); for (size_t j = 0; j < indices[i].size(); ++j) { EXPECT_LE(indices[i][j], num_queries); EXPECT_LE(squared_distances[i][j], 2.); } } } TEST_F(TestKDTree, test_batch_radius_search) { // Input data. KDTree tree(data); const size_t& num_queries = num_points_in_circle; MatrixXd queries(data.leftCols(num_queries)); double squared_search_radius = 2.0001; // In-out data. vector<vector<int> > nn_indices; vector<vector<double> > nn_squared_distances; // First use case: we want to examine the squared distances. tree.radius_search( queries, squared_search_radius, nn_indices, nn_squared_distances); EXPECT_EQ(nn_indices.size(), num_queries); for (size_t i = 0; i < num_queries; ++i) { EXPECT_EQ(nn_indices[i].size(), num_queries); for (size_t j = 0; j < nn_indices[i].size(); ++j) { EXPECT_LE(nn_indices[i][j], num_queries); EXPECT_LE(nn_squared_distances[i][j], 2.); } } // Second use case: we want to limit the number of neighbors to return. size_t max_num_nearest_neighbors = 2; tree.radius_search(queries, squared_search_radius, nn_indices, nn_squared_distances, max_num_nearest_neighbors); EXPECT_EQ(nn_indices.size(), num_queries); for (size_t i = 0; i < num_queries; ++i) { EXPECT_EQ(nn_indices[i].size(), max_num_nearest_neighbors); for (size_t j = 0; j < nn_indices[i].size(); ++j) { EXPECT_LE(nn_indices[i][j], num_queries); EXPECT_LE(nn_squared_distances[i][j], 2.); } } } TEST_F(TestKDTree, test_batch_knn_search_with_query_point_in_data) { KDTree tree(data); const size_t num_queries = num_points_in_circle; const size_t num_nearest_neighbors = num_points_in_circle-1; vector<size_t> queries(num_queries); for (size_t i = 0; i != queries.size(); ++i) queries[i] = i; vector<vector<int> > indices; vector<vector<double> > squared_distances; tree.knn_search(queries, num_nearest_neighbors, indices, squared_distances); EXPECT_EQ(indices.size(), num_queries); for (size_t i = 0; i != indices.size(); ++i) { EXPECT_EQ(indices[i].size(), num_nearest_neighbors); for (size_t j = 0; j < indices[i].size(); ++j) { EXPECT_LE(indices[i][j], num_nearest_neighbors); EXPECT_LE(squared_distances[i][j], 2.); } } } TEST_F(TestKDTree, test_batch_radius_search_with_query_point_in_data) { // Input data. KDTree tree(data); const size_t& num_queries = num_points_in_circle; vector<size_t> queries; for (size_t i = 0; i < num_queries; ++i) queries.push_back(i); double squared_search_radius = 2.0001; // In-out data. vector<vector<int> > nn_indices; vector<vector<double> > nn_squared_distances; // First use case: we want to examine the squared distances. tree.radius_search( queries, squared_search_radius, nn_indices, nn_squared_distances); EXPECT_EQ(nn_indices.size(), num_queries); for (size_t i = 0; i < num_queries; ++i) { EXPECT_EQ(nn_indices[i].size(), num_queries-1); for (size_t j = 0; j < nn_indices[i].size(); ++j) { EXPECT_LE(nn_indices[i][j], num_queries); EXPECT_LE(nn_squared_distances[i][j], 2.); } } // Second use case: we want to limit the number of neighbors to return. size_t max_num_nearest_neighbors = 2; tree.radius_search(queries, squared_search_radius, nn_indices, nn_squared_distances, max_num_nearest_neighbors); EXPECT_EQ(nn_indices.size(), num_queries); for (size_t i = 0; i < num_queries; ++i) { EXPECT_EQ(nn_indices[i].size(), max_num_nearest_neighbors); for (size_t j = 0; j < nn_indices[i].size(); ++j) { EXPECT_LE(nn_indices[i][j], num_queries); EXPECT_LE(nn_squared_distances[i][j], 2.); } } } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<|endoftext|>
<commit_before><commit_msg>Switched to using surface.frame callbacks on wayland for painting<commit_after><|endoftext|>
<commit_before>/***************************************************************************** * CameraCalibration.cpp * * Set white balance for given lighting, write parameters to file * https://web.stanford.edu/~sujason/ColorBalancing/robustawb.html ******************************************************************************/ #include "CameraCalibration.h" using namespace cv; using namespace std; //////////////// // Parameters // //////////////// #define BRIGHT_EXPOSURE 100 #define DARK_EXPOSURE 5 #define ISO_VALUE 1 // Image Size //#define FRAME_WIDTH 3280 // 8 megapixels //#define FRAME_HEIGHT 2464 // 8 megapixels #define FRAME_WIDTH 1280 // 720 HD #define FRAME_HEIGHT 720 // 720 HD ////////////////////// // Global Variables // ////////////////////// // Global Variables int stopprogram = 0; string sourcewindow = "Current Image"; VideoCapture cap; int redbalance = 1600; int bluebalance = 1600; int exposure = 5; Mat frame; Mat bgrframe; Mat yuvframe; // V4L2 Global Device Object V4L2Control picamctrl; //////////////////////// // Callback Functions // //////////////////////// /******************************************************************************* * void whiteBalanceCallback(int, void*) * * Sets white balance values (from 1-7999) * Changing position of trackbar calls this function ******************************************************************************/ void whiteBalanceCallback(int, void*) { picamctrl.set(V4L2_CID_RED_BALANCE,redbalance); picamctrl.set(V4L2_CID_BLUE_BALANCE,bluebalance); } /******************************************************************************* * void mouseCallback(int event, int x, int y, int flags, void* userdata) * * Write HSV and RGB values of point clicked on to terminal * Any mouse movement will call this function ******************************************************************************/ void mouseCallback(int event, int x, int y, int flags, void* userdata) { if ( event == EVENT_LBUTTONDOWN ) // Only run when left button is pressed { Vec3b bgr = bgrframe.at<Vec3b>(y, x); int b = bgr.val[0]; int g = bgr.val[1]; int r = bgr.val[2]; // print out RGB values (sanity check) cout << "B: " << b << ",\tG:" << g << ",\tR:" << r << endl; } } ////////////// // Threads! // ////////////// /******************************************************************************* * void *takePictures(void*) * * Camera-handling thread: continuously save images as soon as they come in ******************************************************************************/ void *takePictures(void*) { // Initialize exposure settings picamctrl.set(V4L2_CID_EXPOSURE_ABSOLUTE, BRIGHT_EXPOSURE ); // Grab all 5 images from the frame buffer in order to clear the buffer for(int i=0; i<5; i++) { cap.grab(); } // Loop quickly to pick up images as soon as they are taken while(!stopprogram) { // 'Grab' frame from webcam's image buffer cap.grab(); // Retrieve encodes image from grab buffer to 'frame' variable cap.retrieve( frame ); } // End thread pthread_exit(NULL); } ////////// // Main // ////////// int main(int argc, char** argv) { // Open the camera! cap.open(0); // opens first video device picamctrl.open("/dev/video0"); // check to make sure device properly opened if ( !cap.isOpened() ) { cerr << "Error opening the camera (OpenCV)" << endl; return -1; } // Set framerate (OpenCV capture property) cap.set(CV_CAP_PROP_FPS,2); // Set camera exposure control to manual (driver property) picamctrl.set(V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL); // Set camera autowhitebalance to manual picamctrl.set(V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE,V4L2_WHITE_BALANCE_MANUAL); // Set camera iso to manual picamctrl.set(V4L2_CID_ISO_SENSITIVITY_AUTO, 0); // Initialize exposure, iso values picamctrl.set(V4L2_CID_EXPOSURE_ABSOLUTE, BRIGHT_EXPOSURE); picamctrl.set(V4L2_CID_ISO_SENSITIVITY, ISO_VALUE); // Set capture camera size (resolution) cap.set(CV_CAP_PROP_FRAME_WIDTH,FRAME_WIDTH); cap.set(CV_CAP_PROP_FRAME_HEIGHT,FRAME_HEIGHT); // Open windows on your monitor namedWindow( source_window, CV_WINDOW_AUTOSIZE ); // Create trackbars for white balancing // createTrackbar( " Red: ", source_window, &redbalance, 100, whiteBalanceCallback ); // createTrackbar( " Blue:", source_window, &bluebalance, 100, whiteBalanceCallback ); // Create trackbar for exposure setting // createTrackbar( " Exposure:", source_window, &exposure, 100, NULL); // set the callback function for any mouse event setMouseCallback(source_window, mouseCallback, NULL); // set default white balance whiteBalanceCallback(0,0); // Start multithreading! pthread_t cameraThread; // Setting Priorities pthread_attr_t tattr; sched_param param; // Initialize attributes with defaults pthread_attr_init (&tattr); // Save the parameters to "param" pthread_attr_getschedparam (&tattr, &param); // Set the priority parameter of "param", leaving others at default param.sched_priority = sched_get_priority_max(SCHED_RR) - 1; // Set attributes to modified parameters pthread_attr_setschedparam (&tattr, &param); // Create thread using modified attributes pthread_create (&cameraThread, &tattr, takePictures, NULL); // Pause for 2 seconds to let everything initialize sleep(2); // Announce that we're done initializing cout << "Done Initializing." << endl; int key = 0; // Take a bunch of pictures while(key != 27) // 27 is keycode for escape key // for(int i=1; i<=10; i++) { // Save most recent frame to local variable frame.copyTo(bgrframe); // Convert color spaces cvtColor(bgrframe, yuvframe, CV_BGR2YCrCb); // Display image on current open window imshow( sourcewindow, bgrframe ); // wait 1 ms to check for press of escape key key = waitKey(1); } // end while // Set mode to STOPPED stopprogram = 1; // Wait a second to let the threads stop sleep(1); // close camera cap.release(); picamctrl.close(); }// end main <commit_msg>still testing<commit_after>/***************************************************************************** * CameraCalibration.cpp * * Set white balance for given lighting, write parameters to file * https://web.stanford.edu/~sujason/ColorBalancing/robustawb.html ******************************************************************************/ #include "CameraCalibration.h" using namespace cv; using namespace std; //////////////// // Parameters // //////////////// #define BRIGHT_EXPOSURE 100 #define DARK_EXPOSURE 5 #define ISO_VALUE 1 // Image Size //#define FRAME_WIDTH 3280 // 8 megapixels //#define FRAME_HEIGHT 2464 // 8 megapixels #define FRAME_WIDTH 1280 // 720 HD #define FRAME_HEIGHT 720 // 720 HD // Balancing Region #define BALANCE_WIDTH 0.2 #define BALANCE_HEIGHT 0.2 ////////////////////// // Global Variables // ////////////////////// // Global Variables string sourcewindow = "Current Image"; VideoCapture cap; int redbalance = 1600; int bluebalance = 1600; int exposure = 5; Mat bgrframe, yuvframe; // V4L2 Global Device Object V4L2Control picamctrl; //////////////////////// // Callback Functions // //////////////////////// /******************************************************************************* * void mouseCallback(int event, int x, int y, int flags, void* userdata) * * Write HSV and RGB values of point clicked on to terminal * Any mouse movement will call this function ******************************************************************************/ void mouseCallback(int event, int x, int y, int flags, void* userdata) { if ( event == EVENT_LBUTTONDOWN ) // Only run when left button is pressed { Vec3b bgr = bgrframe.at<Vec3b>(y, x); int b = bgr.val[0]; int g = bgr.val[1]; int r = bgr.val[2]; // print out RGB values (sanity check) cout << "B: " << b << ",\tG:" << g << ",\tR:" << r << endl; Vec3b yuv = yuvframe.at<Vec3b>(y, x); int y = yuv.val[0]; int u = yuv.val[1]; int v = yuv.val[2]; // print out YUV values (sanity check) cout << "Y: " << y << ",\tU:" << u << ",\tV:" << v << endl; } } ////////// // Main // ////////// int main(int argc, char** argv) { // Open the camera! cap.open(0); // opens first video device picamctrl.open("/dev/video0"); // check to make sure device properly opened if ( !cap.isOpened() ) { cerr << "Error opening the camera (OpenCV)" << endl; return -1; } // Set framerate (OpenCV capture property) cap.set(CV_CAP_PROP_FPS,2); // Set camera exposure control to manual (driver property) picamctrl.set(V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL); // Set camera autowhitebalance to manual picamctrl.set(V4L2_CID_AUTO_N_PRESET_WHITE_BALANCE,V4L2_WHITE_BALANCE_MANUAL); // Disable scene mode picamctrl.set(V4L2_CID_SCENE_MODE, V4L2_SCENE_MODE_NONE); // Set camera iso to manual picamctrl.set(V4L2_CID_ISO_SENSITIVITY_AUTO, 0); // Initialize exposure, iso values picamctrl.set(V4L2_CID_EXPOSURE_ABSOLUTE, BRIGHT_EXPOSURE); picamctrl.set(V4L2_CID_ISO_SENSITIVITY, ISO_VALUE); // Set capture camera size (resolution) cap.set(CV_CAP_PROP_FRAME_WIDTH,FRAME_WIDTH); cap.set(CV_CAP_PROP_FRAME_HEIGHT,FRAME_HEIGHT); // Open window on your monitor namedWindow( source_window, CV_WINDOW_AUTOSIZE ); // Create trackbar for exposure setting // createTrackbar( " Exposure:", source_window, &exposure, 100, NULL); // set the callback function for any mouse event setMouseCallback(source_window, mouseCallback, NULL); // set default white balance picamctrl.set(V4L2_CID_RED_BALANCE, redbalance); picamctrl.set(V4L2_CID_BLUE_BALANCE, bluebalance); // Calculate region within which we will be balancing the image int balanceh_2 = FRAME_HEIGHT * BALANCE_HEIGHT / 2; // half balance box height int balancew_2 = FRAME_WIDTH * BALANCE_WIDTH / 2; // half balance box width int framecentery = FRAME_HEIGHT / 2; // y coord of "center" of frame int framecenterx = FRAME_WIDTH / 2; // x coord of "center" of frame // Calculate coordinates of balancing box int balancexmin = framecenterx - balancew_2; int balancexmax = framecenterx + balancew_2 - 1; int balanceymin = framecentery - balanceh_2; int balanceymax = framecentery + balanceh_2 - 1; // Generate points for bounds of balancing box Point b1 = Point(balancexmin, balanceymin); Point b2 = Point(balancexmax, balanceymax); // Grab all 5 images from the frame buffer in order to clear the buffer for(int i=0; i<5; i++) { cap.grab(); } // Announce that we're done initializing cout << "Done Initializing." << endl; int key = 0; // Loop quickly to pick up images as soon as they are taken while(key != 27) // 27 is keycode for escape key { // 'Grab' frame from webcam's image buffer cap.grab(); // Retrieve encodes image from grab buffer to 'frame' variable cap.retrieve( bgrframe ); // Convert color spaces cvtColor(bgrframe, yuvframe, CV_BGR2YCrCb); // Obtain average YUV values over our balancing box area. Scalar yuvmean = mean(yuvframe(Rect(b1, b2))); float ubar = yuvmean[1]; // red float vbar = yuvmean[2]; // blue // Check whether red (u) or blue (v) is more off. if ( abs(ubar) > abs(vbar) ) { // If red is more wrong, adjust red balance } // Draw rectangle in middle of image rectangle(bgrframe, b1, b2 , Scalar(255, 255, 0)); // Display image on current open window imshow( sourcewindow, bgrframe ); // wait 1 ms to check for press of escape key key = waitKey(1); } // end while // close camera cap.release(); picamctrl.close(); }// end main <|endoftext|>
<commit_before>#include "textbox.hpp" #include "jatekrekord.h" static OBJ *tabla; class MEZO : public ABLAK // A mező amin valamelyik játékos áll vagy állhat. { public: MEZO(double x, double y, int szine) : ABLAK(x,y,33,33,650,szine*33+1,false) {}; void setter(istream& be); void addObj(OBJ *obj) {}; // Nem lehet hozzáadni újabb objektumokoat. void getter(ostream& ki) const; }; void MEZO::setter(istream& be) // A setterbe 0-6ig vár színt. { int p; be >> p; ky=p*33+1; } void MEZO::getter(ostream& ki) const { ki << ((ky-1)/33); } class TABLA : public ABLAK { private: int kattintva; vector<Mezo*> m; public: TABLA(vector<Mezo*> m) : ABLAK(83,33,462,462,683,0,true), m(m) { for (int y = 0; y < 7; ++y) // A tábla 7*7-es de csak 24 mező van rajta. { for (int x = 0; x < 7; ++x) { if (m[x+y*7]->szin==6) {m[x+y*7]->id=objektumok.size(); objektumok.push_back( new MEZO(16+x*66,16+y*66,6) ); } // Létrehozzuk és id-t adunk hogy tudjunk rá hivatkozni. } } kattintva=0; } void srajzol(canvas &Tkepek, double X0, double Y0, double Xb, double Yb, double Xj, double Yj, KAMERA kamera, bool focus) const; bool supdate(event ev, double X0, double Y0, KAMERA kamera); void addObj(OBJ *obj) {}; // Nem lehet hozzáadni újabb objektumokoat. void setter(istream& be); void getter(ostream& ki) const; }; void TABLA::srajzol(canvas &Tkepek, double X0, double Y0, double Xb, double Yb, double Xj, double Yj, KAMERA kamera, bool focus) const { double ux,uy,usx,usy,ukx,uky; // Lekellett volna cserélni ezt a szépséget canvesre mielött elkezdem írni a malmot... ux=x+X0;uy=y+Y0;usx=sx;usy=sy;ukx=kx;uky=ky; kamera.getKamCoords(ux,uy); if (ux+usx<Xb or ux>Xb+Xj or uy+usy<Yb or uy>Yb+Yj) return; if (ux+usx>Xb+Xj) {usx=Xb+Xj-ux;} if (ux<Xb) {usx+=ux-Xb; ukx-=ux; ux=Xb;} if (uy+usy>Yb+Yj) {usy=Yb+Yj-uy;} if (uy<Yb) {usy+=uy-Yb; uky-=uy; uy=Yb;} gout << stamp(Tkepek,ukx,uky,usx,usy,ux,uy); // Kép canvas c; c.open(462,462); c.transparent(true); for (int i = 0; i < 49; ++i) // Vonal rajzolás { if (m[i]->szin!=9) { c << color(255,255,255); double nx,ny,mx,my; objektumok[m[i]->id]->getPosition(nx,ny); nx+=16.5; ny+=16.5; kamera.getKamCoords(nx,ny); if (m[i]->szom.j) { // Csak a közvetlen szömszédokból a jobbra és le objektumok[m[i]->szom.j->id]->getPosition(mx,my); mx+=16.5; my+=16.5; kamera.getKamCoords(mx,my); c << move_to(nx,ny) << line_to(mx,my); } if (m[i]->szom.l) { objektumok[m[i]->szom.l->id]->getPosition(mx,my); mx+=16.5; my+=16.5; kamera.getKamCoords(mx,my); c << move_to(nx,ny) << line_to(mx,my); } } } gout << stamp(c,x,y); for (int i = 0; i < objektumok.size();++i) // Mezők és a vonalak kirajzolása { objektumok[i]->srajzol(Tkepek,x+X0,y+Y0,ux,uy,usx,usy,kamera,(i+1==objektumok.size()&&focus)); // Ha utolsó elem és az ablak is az utolsó: focusban van. } } bool TABLA::supdate(event ev, double X0, double Y0, KAMERA kamera) { if (ev.type==ev_mouse) { if (ev.button==btn_left) { double ux,uy; // Kamera elmozdulás miatt kellenek. ux=x+X0;uy=y+Y0; kamera.getKamCoords(ux,uy); for (int i = objektumok.size()-1; i >= 0; i--) { if (objektumok[i]->BenneVan(ev.pos_x-ux,ev.pos_y-uy)) { kattintva=i; return true; } } kattintva=-1; } } return false; } void TABLA::setter(istream& be) { if (kattintva==-1) return; objektumok[kattintva]->setter(be); } void TABLA::getter(ostream& ki) const { if (kattintva==-1) return; stringstream s; objektumok[kattintva]->getter(s); ki << s.str(); } bool lepes(bool jatekos,ENV &env,Rekord &rekord) { bool felszed=false; // Felvesz mozgatáshoz while(gin >> env.ev and env.ev.keycode!=key_escape) { env.UpdateDrawHandle(); if (env.ev.type==ev_mouse) { if (env.ev.button==btn_left) { stringstream gs,ss; tabla->getter(gs); int ijsz; gs >> ijsz; if (ijsz==6 and rekord.p[jatekos].babu>0) { ss << rekord.p[jatekos].szin; tabla->setter(ss); rekord.p[jatekos].babu--; return true; // Átadja a kört } else if (ijsz==rekord.p[jatekos].szin and !felszed) { ss << 6; tabla->setter(ss); felszed=true; rekord.p[jatekos].babu++; } }else if (env.ev.button==-btn_left) { } } } return false; // Kilép a menübe } void mainjatek(ENV &env,Rekord &rekord) { env.ObjKiemel(tabla); tabla->setPosition(83,33); while(gin >> env.ev and env.ev.keycode!=key_escape) { if (!lepes(0,env,rekord)) break; if (!lepes(1,env,rekord)) break; } tabla->setPosition(999,999); } bool okxy(vector<Mezo*> m,int xx,int yy) { unsigned char x=0,y=0; for (int i = 0; i < 7; ++i) { if (m[i+yy*7]->szin!=9) x++; if (m[xx+i*7]->szin!=9) y++; } return (x<3 and y<3); } void vonalaz(vector<Mezo*> m,int xx,int yy) // rekurzívan végigmegy az egész táblán és feltölti ki-kinek a szomszédja. { if (m[xx+yy*7]->szin!=6) {vonalaz(m,xx+1,yy); return;} // Ha olyannal kezdődik ami nem léphető mező akkor elindul jobbra keresni egyet. for (int x = xx-1; x >= 0 and !m[xx+yy*7]->szom.b; --x) // Balra if (m[x+yy*7]->szin==6) {m[xx+yy*7]->szom.b=m[x+yy*7]; vonalaz(m,x,yy);} for (int x = xx+1; x < 7 and !m[xx+yy*7]->szom.j; ++x) // Jobbra if (m[x+yy*7]->szin==6) {m[xx+yy*7]->szom.j=m[x+yy*7]; vonalaz(m,x,yy);} for (int y = yy-1; y >= 0 and !m[xx+yy*7]->szom.f; --y) // Fel if (m[xx+y*7]->szin==6) {m[xx+yy*7]->szom.f=m[xx+y*7]; vonalaz(m,xx,y);} for (int y = yy+1; y < 7 and !m[xx+yy*7]->szom.l; ++y) // Le if (m[xx+y*7]->szin==6) {m[xx+yy*7]->szom.l=m[xx+y*7]; vonalaz(m,xx,y);} } void initjatek(ENV &env,Rekord &rekord) { srand(rekord.seed); for (int i = 0; i < 49; ++i) { rekord.palya.push_back(new Mezo); } int mezoszam=0, lepes=0; while(mezoszam<21 and lepes<999) // Ez egy fair pálya generáló, ha ezer lépésből megvan. { int xx = rand()%7; int yy = rand()%7; if ( rekord.palya[xx+yy*7]->szin==9 and okxy(rekord.palya,xx,yy)) {rekord.palya[xx+yy*7]->szin=6; mezoszam++;} lepes++; } int i=0; while(mezoszam<21 and i<49) // Ha nem lett meg ezerből, sorba megy és berakja oda ahol hiányzik. { if ( rekord.palya[i]->szin==9 and okxy(rekord.palya,i%7,i/7)) {rekord.palya[i]->szin=6; mezoszam++;} i++; } vonalaz(rekord.palya,0,0); // Ha nem léphető mező akkor elöbb keres egyet. rekord.p[0].babu= (rekord.p[0].babu==8 ? 8 : 7); // easter egg jutalma rekord.p[1].babu=7; tabla = new TABLA(rekord.palya); env.addObj(tabla); tabla->setPosition(999,999); } void endjatek(ENV &env, Rekord &rekord) { env.delObj(tabla); while (rekord.palya.size()>0) { delete rekord.palya[rekord.palya.size()-1]; rekord.palya.pop_back(); } } <commit_msg>Csak szomszédba lehet lépni<commit_after>#include "textbox.hpp" #include "jatekrekord.h" static OBJ *tabla; class MEZO : public ABLAK // A mező amin valamelyik játékos áll vagy állhat. { public: MEZO(double x, double y, int szine) : ABLAK(x,y,33,33,650,szine*33+1,false) {}; void setter(istream& be); void addObj(OBJ *obj) {}; // Nem lehet hozzáadni újabb objektumokoat. void getter(ostream& ki) const; }; void MEZO::setter(istream& be) // A setterbe 0-6ig vár színt. { int p; be >> p; ky=p*33+1; } void MEZO::getter(ostream& ki) const { ki << ((ky-1)/33); } class TABLA : public ABLAK { private: int kattintva; vector<Mezo*> m; public: TABLA(vector<Mezo*> m) : ABLAK(83,33,462,462,683,0,true), m(m) { for (int y = 0; y < 7; ++y) // A tábla 7*7-es de csak 24 mező van rajta. { for (int x = 0; x < 7; ++x) { if (m[x+y*7]->szin==6) {m[x+y*7]->id=objektumok.size(); objektumok.push_back( new MEZO(16+x*66,16+y*66,6) ); } // Létrehozzuk és id-t adunk hogy tudjunk rá hivatkozni. } } kattintva=0; } void srajzol(canvas &Tkepek, double X0, double Y0, double Xb, double Yb, double Xj, double Yj, KAMERA kamera, bool focus) const; bool supdate(event ev, double X0, double Y0, KAMERA kamera); void addObj(OBJ *obj) {}; // Nem lehet hozzáadni újabb objektumokoat. void setter(istream& be); void getter(ostream& ki) const; }; void TABLA::srajzol(canvas &Tkepek, double X0, double Y0, double Xb, double Yb, double Xj, double Yj, KAMERA kamera, bool focus) const { double ux,uy,usx,usy,ukx,uky; // Lekellett volna cserélni ezt a szépséget canvesre mielött elkezdem írni a malmot... ux=x+X0;uy=y+Y0;usx=sx;usy=sy;ukx=kx;uky=ky; kamera.getKamCoords(ux,uy); if (ux+usx<Xb or ux>Xb+Xj or uy+usy<Yb or uy>Yb+Yj) return; if (ux+usx>Xb+Xj) {usx=Xb+Xj-ux;} if (ux<Xb) {usx+=ux-Xb; ukx-=ux; ux=Xb;} if (uy+usy>Yb+Yj) {usy=Yb+Yj-uy;} if (uy<Yb) {usy+=uy-Yb; uky-=uy; uy=Yb;} gout << stamp(Tkepek,ukx,uky,usx,usy,ux,uy); // Kép canvas c; c.open(462,462); c.transparent(true); for (int i = 0; i < 49; ++i) // Vonal rajzolás { if (m[i]->szin!=9) { c << color(255,255,255); double nx,ny,mx,my; objektumok[m[i]->id]->getPosition(nx,ny); nx+=16.5; ny+=16.5; kamera.getKamCoords(nx,ny); if (m[i]->szom.j) { // Csak a közvetlen szömszédokból a jobbra és le objektumok[m[i]->szom.j->id]->getPosition(mx,my); mx+=16.5; my+=16.5; kamera.getKamCoords(mx,my); c << move_to(nx,ny) << line_to(mx,my); } if (m[i]->szom.f) { objektumok[m[i]->szom.f->id]->getPosition(mx,my); mx+=16.5; my+=16.5; kamera.getKamCoords(mx,my); c << move_to(nx,ny) << line_to(mx,my); } } } gout << stamp(c,x,y); for (int i = 0; i < objektumok.size();++i) // Mezők és a vonalak kirajzolása { objektumok[i]->srajzol(Tkepek,x+X0,y+Y0,ux,uy,usx,usy,kamera,(i+1==objektumok.size()&&focus)); // Ha utolsó elem és az ablak is az utolsó: focusban van. } } bool TABLA::supdate(event ev, double X0, double Y0, KAMERA kamera) { if (ev.type==ev_mouse) { if (ev.button==btn_left) { double ux,uy; // Kamera elmozdulás miatt kellenek. ux=x+X0;uy=y+Y0; kamera.getKamCoords(ux,uy); for (int i = objektumok.size()-1; i >= 0; i--) { if (objektumok[i]->BenneVan(ev.pos_x-ux,ev.pos_y-uy)) { kattintva=i; return true; } } kattintva=-1; } } return false; } void TABLA::setter(istream& be) { if (kattintva==-1) return; objektumok[kattintva]->setter(be); } void TABLA::getter(ostream& ki) const { if (kattintva==-1) return; stringstream s; objektumok[kattintva]->getter(s); ki << s.str() << " " << kattintva; } int gethanyadikfromid(Rekord &rekord,int id) { for (int i = 0; i < rekord.palya.size(); ++i) { if (id==rekord.palya[i]->id) return i; } return -1; } bool szomszede(vector<int> &szomszedok,int id) { for (int i = 0; i < szomszedok.size(); ++i) { if (szomszedok[i]==id) return true; } return false; } void getszomszedok(Rekord &rekord,int i,vector<int> &szomszedok) { int id = gethanyadikfromid(rekord,i); if (rekord.palya[id]->szom.b) szomszedok.push_back(rekord.palya[id]->szom.b->id); if (rekord.palya[id]->szom.f) szomszedok.push_back(rekord.palya[id]->szom.f->id); if (rekord.palya[id]->szom.j) szomszedok.push_back(rekord.palya[id]->szom.j->id); if (rekord.palya[id]->szom.l) szomszedok.push_back(rekord.palya[id]->szom.l->id); } bool lepes(bool jatekos,ENV &env,Rekord &rekord) { bool felszedve = false; vector<int> szomszedok; while(gin >> env.ev and env.ev.keycode!=key_escape) { env.UpdateDrawHandle(); if (env.ev.type==ev_mouse) { if (env.ev.button==btn_left) { stringstream gs,ss; tabla->getter(gs); int ijsz, kat; gs >> ijsz; gs >> kat; cout << kat << endl; // Üres és van bábuja és vagy nem szedte fel vagy szomszédba rakta le if (ijsz==6 and rekord.p[jatekos].babu>0 and (!felszedve or szomszede(szomszedok,kat)) ) { ss << rekord.p[jatekos].szin; tabla->setter(ss); rekord.p[jatekos].babu--; return true; // Átadja a kört } else if (ijsz==rekord.p[jatekos].szin and !felszedve) // Bábu felszedése { getszomszedok(rekord,kat,szomszedok); if (szomszedok.size()>0){ ss << 6; tabla->setter(ss); rekord.p[jatekos].babu++; felszedve=true; } } }else if (env.ev.button==-btn_left) { } } } return false; // Kilép a menübe } void mainjatek(ENV &env,Rekord &rekord) { env.ObjKiemel(tabla); tabla->setPosition(83,33); while(gin >> env.ev and env.ev.keycode!=key_escape) { if (!lepes(0,env,rekord)) break; if (!lepes(1,env,rekord)) break; } tabla->setPosition(999,999); } bool okxy(vector<Mezo*> m,int xx,int yy) { unsigned char x=0,y=0; for (int i = 0; i < 7; ++i) { if (m[i+yy*7]->szin!=9) x++; if (m[xx+i*7]->szin!=9) y++; } return (x<3 and y<3); } void vonalaz(vector<Mezo*> m,int xx,int yy) // rekurzívan végigmegy az egész táblán és feltölti ki-kinek a szomszédja. { if (m[xx+yy*7]->szin!=6) {vonalaz(m,xx+1,yy); return;} // Ha olyannal kezdődik ami nem léphető mező akkor elindul jobbra keresni egyet. for (int x = xx-1; x >= 0 and !m[xx+yy*7]->szom.b; --x) // Balra if (m[x+yy*7]->szin==6) {m[xx+yy*7]->szom.b=m[x+yy*7]; vonalaz(m,x,yy);} for (int x = xx+1; x < 7 and !m[xx+yy*7]->szom.j; ++x) // Jobbra if (m[x+yy*7]->szin==6) {m[xx+yy*7]->szom.j=m[x+yy*7]; vonalaz(m,x,yy);} for (int y = yy-1; y >= 0 and !m[xx+yy*7]->szom.f; --y) // Fel if (m[xx+y*7]->szin==6) {m[xx+yy*7]->szom.f=m[xx+y*7]; vonalaz(m,xx,y);} for (int y = yy+1; y < 7 and !m[xx+yy*7]->szom.l; ++y) // Le if (m[xx+y*7]->szin==6) {m[xx+yy*7]->szom.l=m[xx+y*7]; vonalaz(m,xx,y);} } void initjatek(ENV &env,Rekord &rekord) { srand(rekord.seed); for (int i = 0; i < 49; ++i) { rekord.palya.push_back(new Mezo); } int mezoszam=0, lepes=0; while(mezoszam<21 and lepes<999) // Ez egy fair pálya generáló, ha ezer lépésből megvan. { int xx = rand()%7; int yy = rand()%7; if ( rekord.palya[xx+yy*7]->szin==9 and okxy(rekord.palya,xx,yy)) {rekord.palya[xx+yy*7]->szin=6; mezoszam++;} lepes++; } int i=0; while(mezoszam<21 and i<49) // Ha nem lett meg ezerből, sorba megy és berakja oda ahol hiányzik. { if ( rekord.palya[i]->szin==9 and okxy(rekord.palya,i%7,i/7)) {rekord.palya[i]->szin=6; mezoszam++;} i++; } vonalaz(rekord.palya,0,0); // Ha nem léphető mező akkor elöbb keres egyet. rekord.p[0].babu= (rekord.p[0].babu==8 ? 8 : 7); // easter egg jutalma rekord.p[1].babu=7; tabla = new TABLA(rekord.palya); env.addObj(tabla); tabla->setPosition(999,999); } void endjatek(ENV &env, Rekord &rekord) { env.delObj(tabla); while (rekord.palya.size()>0) { delete rekord.palya[rekord.palya.size()-1]; rekord.palya.pop_back(); } } <|endoftext|>
<commit_before>/*************************************************************************** * * * Copyright (C) 2007-2013 by Johan De Taeye, frePPLe bvba * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Affero General Public License as published * * by the Free Software Foundation; either version 3 of the License, or * * (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with this program. * * If not, see <http://www.gnu.org/licenses/>. * * * ***************************************************************************/ #define FREPPLE_CORE #include "frepple/solver.h" namespace frepple { DECLARE_EXPORT void SolverMRP::solve(const BufferProcure* b, void* v) { SolverMRPdata* data = static_cast<SolverMRPdata*>(v); // TODO create a more performant procurement solver. Instead of creating a list of operationplans // moves and creations, we can create a custom command "updateProcurements". The commit of // this command will update the operationplans. // The solve method is only worried about getting a Yes/No reply. The reply is almost always yes, // except a) when the request is inside max(current + the lead time, latest procurement + min time // after locked procurement), or b) when the min time > 0 and max qty > 0 // Call the user exit if (userexit_buffer) userexit_buffer.call(b, PythonObject(data->constrainedPlanning)); // Message if (data->getSolver()->getLogLevel()>1) logger << indent(b->getLevel()) << " Procurement buffer '" << b->getName() << "' is asked: " << data->state->q_qty << " " << data->state->q_date << endl; // Standard reply date data->state->a_date = Date::infiniteFuture; // Collect all reusable existing procurements in a vector data structure. // Also find the latest locked procurement operation. It is used to know what // the earliest date is for a new procurement. int countProcurements = 0; int indexProcurements = -1; Date earliest_next; Date latest_next = Date::infiniteFuture; vector<OperationPlan*> procurements(30); // Initial size of 30 for (OperationPlan::iterator i(b->getOperation()); i!=OperationPlan::end(); ++i) { if (i->getLocked()) earliest_next = i->getDates().getEnd(); else procurements[countProcurements++] = &*i; } // Find constraints on earliest and latest date for the next procurement if (earliest_next && b->getMaximumInterval()) latest_next = earliest_next + b->getMaximumInterval(); if (earliest_next && b->getMinimumInterval()) earliest_next += b->getMinimumInterval(); if (data->constrainedPlanning) { if (data->getSolver()->isLeadtimeConstrained() && earliest_next < Plan::instance().getCurrent() + b->getLeadtime()) earliest_next = Plan::instance().getCurrent() + b->getLeadtime(); if (data->getSolver()->isFenceConstrained() && earliest_next < Plan::instance().getCurrent() + b->getFence()) earliest_next = Plan::instance().getCurrent() + b->getFence(); } // Loop through all flowplans Date current_date; double produced = 0.0; double consumed = 0.0; double current_inventory = 0.0; const FlowPlan* current_flowplan = NULL; for (Buffer::flowplanlist::const_iterator cur=b->getFlowPlans().begin(); latest_next != Date::infiniteFuture || cur != b->getFlowPlans().end(); ) { if (cur==b->getFlowPlans().end() || latest_next < cur->getDate()) { // Latest procument time is reached current_date = latest_next; current_flowplan = NULL; } else if (earliest_next && earliest_next < cur->getDate()) { // Earliest procument time was reached current_date = earliest_next; current_flowplan = NULL; } else { // Date with flowplans found if (current_date && current_date >= cur->getDate()) { // When procurements are being moved, it happens that we revisit the // same consuming flowplans twice. This check catches this case. cur++; continue; } current_date = cur->getDate(); bool noConsumers = true; do { if (cur->getType() != 1) { cur++; continue; } current_flowplan = static_cast<const FlowPlan*>(&*(cur++)); if (current_flowplan->getQuantity() < 0) { consumed -= current_flowplan->getQuantity(); noConsumers = false; } else if (current_flowplan->getOperationPlan()->getLocked()) produced += current_flowplan->getQuantity(); } // Loop to pick up the last consuming flowplan on the given date while (cur != b->getFlowPlans().end() && cur->getDate() == current_date); // No further interest in dates with only producing flowplans. if (noConsumers) continue; } // Compute current inventory. The actual onhand in the buffer may be // different since we count only consumers and *locked* producers. current_inventory = produced - consumed; // Hard limit: respect minimum interval if (current_date < earliest_next) { if (current_inventory < -ROUNDING_ERROR && current_date >= data->state->q_date && b->getMinimumInterval() && data->state->a_date > earliest_next && data->getSolver()->isMaterialConstrained() && data->constrainedPlanning) // The inventory goes negative here and we can't procure more // material because of the minimum interval... data->state->a_date = earliest_next; continue; } // Now the normal reorder check if (current_inventory >= b->getMinimumInventory() && current_date < latest_next) { if (current_date == earliest_next) earliest_next = Date::infinitePast; continue; } // When we are within the minimum interval, we may need to increase the // size of the previous procurements. if (current_date == earliest_next && current_inventory < b->getMinimumInventory() - ROUNDING_ERROR) { for (int cnt=indexProcurements; cnt>=0 && current_inventory < b->getMinimumInventory() - ROUNDING_ERROR; cnt--) { double origqty = procurements[cnt]->getQuantity(); procurements[cnt]->setQuantity( procurements[cnt]->getQuantity() + b->getMinimumInventory() - current_inventory); produced += procurements[cnt]->getQuantity() - origqty; current_inventory = produced - consumed; } if (current_inventory < -ROUNDING_ERROR && data->state->a_date > earliest_next && earliest_next > data->state->q_date && data->getSolver()->isMaterialConstrained() && data->constrainedPlanning) // Resizing didn't work, and we still have shortage (not only compared // to the minimum, but also to 0. data->state->a_date = earliest_next; } // At this point, we know we need to reorder... earliest_next = Date::infinitePast; double order_qty = b->getMaximumInventory() - current_inventory; do { if (order_qty <= 0) { if (latest_next == current_date && b->getSizeMinimum()) // Forced to buy the minumum quantity order_qty = b->getSizeMinimum(); else break; } // Create a procurement or update an existing one indexProcurements++; if (indexProcurements >= countProcurements) { // No existing procurement can be reused. Create a new one. CommandCreateOperationPlan *a = new CommandCreateOperationPlan(b->getOperation(), order_qty, Date::infinitePast, current_date, data->state->curDemand); a->getOperationPlan()->setMotive(data->state->motive); a->getOperationPlan()->insertInOperationplanList(); // TODO Not very nice: unregistered opplan in the list! produced += a->getOperationPlan()->getQuantity(); order_qty -= a->getOperationPlan()->getQuantity(); data->add(a); procurements[countProcurements++] = a->getOperationPlan(); } else if (procurements[indexProcurements]->getDates().getEnd() == current_date && procurements[indexProcurements]->getQuantity() == order_qty) { // Reuse existing procurement unchanged. produced += order_qty; order_qty = 0; } else { // Update an existing procurement to meet current needs CommandMoveOperationPlan *a = new CommandMoveOperationPlan(procurements[indexProcurements], Date::infinitePast, current_date, order_qty); produced += procurements[indexProcurements]->getQuantity(); order_qty -= procurements[indexProcurements]->getQuantity(); data->add(a); } if (b->getMinimumInterval()) { earliest_next = current_date + b->getMinimumInterval(); break; // Only 1 procurement allowed at this time... } } while (order_qty > 0 && order_qty >= b->getSizeMinimum()); if (b->getMaximumInterval()) { current_inventory = produced - consumed; if (current_inventory >= b->getMaximumInventory() && cur == b->getFlowPlans().end()) // Nothing happens any more further in the future. // Abort procuring based on the max inteval latest_next = Date::infiniteFuture; else latest_next = current_date + b->getMaximumInterval(); } } // Get rid of extra procurements that have become redundant indexProcurements++; while (indexProcurements < countProcurements) data->add(new CommandDeleteOperationPlan(procurements[++indexProcurements])); // Create the answer if (data->constrainedPlanning && (data->getSolver()->isFenceConstrained() || data->getSolver()->isLeadtimeConstrained() || data->getSolver()->isMaterialConstrained())) { // Check if the inventory drops below zero somewhere double shortage = 0; Date startdate; for (Buffer::flowplanlist::const_iterator cur = b->getFlowPlans().begin(); cur != b->getFlowPlans().end(); ++cur) if (cur->getDate() >= data->state->q_date && cur->getOnhand() < -ROUNDING_ERROR && cur->getOnhand() < shortage) { shortage = cur->getOnhand(); if (-shortage >= data->state->q_qty) break; if (startdate == Date::infinitePast) startdate = cur->getDate(); } if (shortage < 0) { // Answer a shorted quantity data->state->a_qty = data->state->q_qty + shortage; // Log a constraint if (data->logConstraints) data->planningDemand->getConstraints().push( ProblemMaterialShortage::metadata, b, startdate, Date::infiniteFuture, // @todo calculate a better end date -shortage); // Nothing to promise... if (data->state->a_qty < 0) data->state->a_qty = 0; // Check the reply date if (data->constrainedPlanning) { if (data->getSolver()->isFenceConstrained() && data->state->q_date < Plan::instance().getCurrent() + b->getFence() && data->state->a_date > Plan::instance().getCurrent() + b->getFence()) data->state->a_date = Plan::instance().getCurrent() + b->getFence(); if (data->getSolver()->isLeadtimeConstrained() && data->state->q_date < Plan::instance().getCurrent() + b->getLeadtime() && data->state->a_date > Plan::instance().getCurrent() + b->getLeadtime()) data->state->a_date = Plan::instance().getCurrent() + b->getLeadtime(); } } else // Answer the full quantity data->state->a_qty = data->state->q_qty; } else // Answer the full quantity data->state->a_qty = data->state->q_qty; // Increment the cost if (b->getItem() && data->state->a_qty > 0.0) data->state->a_cost += data->state->a_qty * b->getItem()->getPrice(); // Message if (data->getSolver()->getLogLevel()>1) logger << indent(b->getLevel()) << " Procurement buffer '" << b << "' answers: " << data->state->a_qty << " " << data->state->a_date << " " << data->state->a_cost << " " << data->state->a_penalty << endl; } } <commit_msg>bug fix for procurement buffer solver: memory allocation issue<commit_after>/*************************************************************************** * * * Copyright (C) 2007-2013 by Johan De Taeye, frePPLe bvba * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Affero General Public License as published * * by the Free Software Foundation; either version 3 of the License, or * * (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Affero General Public License for more details. * * * * You should have received a copy of the GNU Affero General Public * * License along with this program. * * If not, see <http://www.gnu.org/licenses/>. * * * ***************************************************************************/ #define FREPPLE_CORE #include "frepple/solver.h" namespace frepple { DECLARE_EXPORT void SolverMRP::solve(const BufferProcure* b, void* v) { SolverMRPdata* data = static_cast<SolverMRPdata*>(v); // TODO create a more performant procurement solver. Instead of creating a list of operationplans // moves and creations, we can create a custom command "updateProcurements". The commit of // this command will update the operationplans. // The solve method is only worried about getting a Yes/No reply. The reply is almost always yes, // except a) when the request is inside max(current + the lead time, latest procurement + min time // after locked procurement), or b) when the min time > 0 and max qty > 0 // Call the user exit if (userexit_buffer) userexit_buffer.call(b, PythonObject(data->constrainedPlanning)); // Message if (data->getSolver()->getLogLevel()>1) logger << indent(b->getLevel()) << " Procurement buffer '" << b->getName() << "' is asked: " << data->state->q_qty << " " << data->state->q_date << endl; // Standard reply date data->state->a_date = Date::infiniteFuture; // Collect all reusable existing procurements in a vector data structure. // Also find the latest locked procurement operation. It is used to know what // the earliest date is for a new procurement. int countProcurements = 0; int indexProcurements = -1; Date earliest_next; Date latest_next = Date::infiniteFuture; vector<OperationPlan*> procurements; for (OperationPlan::iterator i(b->getOperation()); i!=OperationPlan::end(); ++i) { if (i->getLocked()) earliest_next = i->getDates().getEnd(); else { procurements.push_back(&*i); ++countProcurements; } } // Find constraints on earliest and latest date for the next procurement if (earliest_next && b->getMaximumInterval()) latest_next = earliest_next + b->getMaximumInterval(); if (earliest_next && b->getMinimumInterval()) earliest_next += b->getMinimumInterval(); if (data->constrainedPlanning) { if (data->getSolver()->isLeadtimeConstrained() && earliest_next < Plan::instance().getCurrent() + b->getLeadtime()) earliest_next = Plan::instance().getCurrent() + b->getLeadtime(); if (data->getSolver()->isFenceConstrained() && earliest_next < Plan::instance().getCurrent() + b->getFence()) earliest_next = Plan::instance().getCurrent() + b->getFence(); } // Loop through all flowplans Date current_date; double produced = 0.0; double consumed = 0.0; double current_inventory = 0.0; const FlowPlan* current_flowplan = NULL; for (Buffer::flowplanlist::const_iterator cur=b->getFlowPlans().begin(); latest_next != Date::infiniteFuture || cur != b->getFlowPlans().end(); ) { if (cur==b->getFlowPlans().end() || latest_next < cur->getDate()) { // Latest procument time is reached current_date = latest_next; current_flowplan = NULL; } else if (earliest_next && earliest_next < cur->getDate()) { // Earliest procument time was reached current_date = earliest_next; current_flowplan = NULL; } else { // Date with flowplans found if (current_date && current_date >= cur->getDate()) { // When procurements are being moved, it happens that we revisit the // same consuming flowplans twice. This check catches this case. cur++; continue; } current_date = cur->getDate(); bool noConsumers = true; do { if (cur->getType() != 1) { cur++; continue; } current_flowplan = static_cast<const FlowPlan*>(&*(cur++)); if (current_flowplan->getQuantity() < 0) { consumed -= current_flowplan->getQuantity(); noConsumers = false; } else if (current_flowplan->getOperationPlan()->getLocked()) produced += current_flowplan->getQuantity(); } // Loop to pick up the last consuming flowplan on the given date while (cur != b->getFlowPlans().end() && cur->getDate() == current_date); // No further interest in dates with only producing flowplans. if (noConsumers) continue; } // Compute current inventory. The actual onhand in the buffer may be // different since we count only consumers and *locked* producers. current_inventory = produced - consumed; // Hard limit: respect minimum interval if (current_date < earliest_next) { if (current_inventory < -ROUNDING_ERROR && current_date >= data->state->q_date && b->getMinimumInterval() && data->state->a_date > earliest_next && data->getSolver()->isMaterialConstrained() && data->constrainedPlanning) // The inventory goes negative here and we can't procure more // material because of the minimum interval... data->state->a_date = earliest_next; continue; } // Now the normal reorder check if (current_inventory >= b->getMinimumInventory() && current_date < latest_next) { if (current_date == earliest_next) earliest_next = Date::infinitePast; continue; } // When we are within the minimum interval, we may need to increase the // size of the previous procurements. if (current_date == earliest_next && current_inventory < b->getMinimumInventory() - ROUNDING_ERROR) { for (int cnt=indexProcurements; cnt>=0 && current_inventory < b->getMinimumInventory() - ROUNDING_ERROR; cnt--) { double origqty = procurements[cnt]->getQuantity(); procurements[cnt]->setQuantity( procurements[cnt]->getQuantity() + b->getMinimumInventory() - current_inventory); produced += procurements[cnt]->getQuantity() - origqty; current_inventory = produced - consumed; } if (current_inventory < -ROUNDING_ERROR && data->state->a_date > earliest_next && earliest_next > data->state->q_date && data->getSolver()->isMaterialConstrained() && data->constrainedPlanning) // Resizing didn't work, and we still have shortage (not only compared // to the minimum, but also to 0. data->state->a_date = earliest_next; } // At this point, we know we need to reorder... earliest_next = Date::infinitePast; double order_qty = b->getMaximumInventory() - current_inventory; do { if (order_qty <= 0) { if (latest_next == current_date && b->getSizeMinimum()) // Forced to buy the minumum quantity order_qty = b->getSizeMinimum(); else break; } // Create a procurement or update an existing one indexProcurements++; if (indexProcurements >= countProcurements) { // No existing procurement can be reused. Create a new one. CommandCreateOperationPlan *a = new CommandCreateOperationPlan(b->getOperation(), order_qty, Date::infinitePast, current_date, data->state->curDemand); a->getOperationPlan()->setMotive(data->state->motive); a->getOperationPlan()->insertInOperationplanList(); // TODO Not very nice: unregistered opplan in the list! produced += a->getOperationPlan()->getQuantity(); order_qty -= a->getOperationPlan()->getQuantity(); data->add(a); procurements.push_back(a->getOperationPlan()); ++countProcurements; } else if (procurements[indexProcurements]->getDates().getEnd() == current_date && procurements[indexProcurements]->getQuantity() == order_qty) { // Reuse existing procurement unchanged. produced += order_qty; order_qty = 0; } else { // Update an existing procurement to meet current needs CommandMoveOperationPlan *a = new CommandMoveOperationPlan(procurements[indexProcurements], Date::infinitePast, current_date, order_qty); produced += procurements[indexProcurements]->getQuantity(); order_qty -= procurements[indexProcurements]->getQuantity(); data->add(a); } if (b->getMinimumInterval()) { earliest_next = current_date + b->getMinimumInterval(); break; // Only 1 procurement allowed at this time... } } while (order_qty > 0 && order_qty >= b->getSizeMinimum()); if (b->getMaximumInterval()) { current_inventory = produced - consumed; if (current_inventory >= b->getMaximumInventory() && cur == b->getFlowPlans().end()) // Nothing happens any more further in the future. // Abort procuring based on the max inteval latest_next = Date::infiniteFuture; else latest_next = current_date + b->getMaximumInterval(); } } // Get rid of extra procurements that have become redundant indexProcurements++; while (indexProcurements < countProcurements) data->add(new CommandDeleteOperationPlan(procurements[++indexProcurements])); // Create the answer if (data->constrainedPlanning && (data->getSolver()->isFenceConstrained() || data->getSolver()->isLeadtimeConstrained() || data->getSolver()->isMaterialConstrained())) { // Check if the inventory drops below zero somewhere double shortage = 0; Date startdate; for (Buffer::flowplanlist::const_iterator cur = b->getFlowPlans().begin(); cur != b->getFlowPlans().end(); ++cur) if (cur->getDate() >= data->state->q_date && cur->getOnhand() < -ROUNDING_ERROR && cur->getOnhand() < shortage) { shortage = cur->getOnhand(); if (-shortage >= data->state->q_qty) break; if (startdate == Date::infinitePast) startdate = cur->getDate(); } if (shortage < 0) { // Answer a shorted quantity data->state->a_qty = data->state->q_qty + shortage; // Log a constraint if (data->logConstraints) data->planningDemand->getConstraints().push( ProblemMaterialShortage::metadata, b, startdate, Date::infiniteFuture, // @todo calculate a better end date -shortage); // Nothing to promise... if (data->state->a_qty < 0) data->state->a_qty = 0; // Check the reply date if (data->constrainedPlanning) { if (data->getSolver()->isFenceConstrained() && data->state->q_date < Plan::instance().getCurrent() + b->getFence() && data->state->a_date > Plan::instance().getCurrent() + b->getFence()) data->state->a_date = Plan::instance().getCurrent() + b->getFence(); if (data->getSolver()->isLeadtimeConstrained() && data->state->q_date < Plan::instance().getCurrent() + b->getLeadtime() && data->state->a_date > Plan::instance().getCurrent() + b->getLeadtime()) data->state->a_date = Plan::instance().getCurrent() + b->getLeadtime(); } } else // Answer the full quantity data->state->a_qty = data->state->q_qty; } else // Answer the full quantity data->state->a_qty = data->state->q_qty; // Increment the cost if (b->getItem() && data->state->a_qty > 0.0) data->state->a_cost += data->state->a_qty * b->getItem()->getPrice(); // Message if (data->getSolver()->getLogLevel()>1) logger << indent(b->getLevel()) << " Procurement buffer '" << b << "' answers: " << data->state->a_qty << " " << data->state->a_date << " " << data->state->a_cost << " " << data->state->a_penalty << endl; } } <|endoftext|>
<commit_before>#include <math.h> #include <stdio.h> #include <ratio> #include "pyramid.h" #include "HalideBuffer.h" #include <vector> using std::vector; using namespace Halide; template<bool B, typename T> struct cond { static constexpr bool value = B; using type = T; }; template <typename First, typename... Rest> struct select : std::conditional<First::value, First, typename select<Rest...>::type> { }; template<typename First> struct select<First> { //static_assert(T::value, "No case of select was chosen"); using type = std::conditional<First::value, typename First::type, void>; }; template<int a> struct tester : public select<cond<a == 0, std::ratio<1, 2>>, cond<a == 1, std::ratio<3, 2>>, cond<a == 2, std::ratio<7, 2>>>::type {}; int main(int argc, char **argv) { Image<float> input(1024, 1024); using T0 = tester<0>::type; printf("t0 %d %d\n", (int)T0::num, (int)T0::den); using T1 = tester<1>::type; printf("t0 %d %d\n", (int)T1::num, (int)T1::den); using T2 = tester<2>::type; printf("t0 %d %d\n", (int)T2::num, (int)T2::den); //using T3 = tester<3>::type; printf("t0 %d %d\n", (int)T3::num, (int)T3::den); // Put some junk in the input. Keep it to small integers so the float averaging stays exact. for (int y = 0; y < input.height(); y++) { for (int x = 0; x < input.width(); x++) { input(x, y) = ((x * 17 + y)/8) % 32; } } vector<Image<float>> levels(10); for (int l = 0; l < 10; l++) { levels[l] = Image<float>(1024 >> l, 1024 >> l); } // Will throw a compiler error if we didn't compile the generator with 10 levels. pyramid(input, levels[0], levels[1], levels[2], levels[3], levels[4], levels[5], levels[6], levels[7], levels[8], levels[9]); // The bottom level should be the input for (int y = 0; y < input.height(); y++) { for (int x = 0; x < input.width(); x++) { if (input(x, y) != levels[0](x, y)) { printf("input(%d, %d) = %f, but levels[0](%d, %d) = %f\n", x, y, input(x, y), x, y, levels[0](x, y)); return -1; } } } // The remaining levels should be averaging of the levels above them. for (int l = 1; l < 10; l++) { for (int y = 0; y < input.height() >> l; y++) { for (int x = 0; x < input.width() >> l; x++) { float correct = (levels[l-1](2*x, 2*y) + levels[l-1](2*x+1, 2*y) + levels[l-1](2*x, 2*y+1) + levels[l-1](2*x+1, 2*y+1))/4; float actual = levels[l](x, y); if (correct != actual) { printf("levels[%d](%d, %d) = %f instead of %f\n", l, x, y, actual, correct); return -1; } } } } printf("Success!\n"); return 0; } <commit_msg>remove scalpel left in patient<commit_after>#include <math.h> #include <stdio.h> #include "pyramid.h" #include "HalideBuffer.h" #include <vector> using std::vector; using namespace Halide; int main(int argc, char **argv) { Image<float> input(1024, 1024); // Put some junk in the input. Keep it to small integers so the float averaging stays exact. for (int y = 0; y < input.height(); y++) { for (int x = 0; x < input.width(); x++) { input(x, y) = ((x * 17 + y)/8) % 32; } } vector<Image<float>> levels(10); for (int l = 0; l < 10; l++) { levels[l] = Image<float>(1024 >> l, 1024 >> l); } // Will throw a compiler error if we didn't compile the generator with 10 levels. pyramid(input, levels[0], levels[1], levels[2], levels[3], levels[4], levels[5], levels[6], levels[7], levels[8], levels[9]); // The bottom level should be the input for (int y = 0; y < input.height(); y++) { for (int x = 0; x < input.width(); x++) { if (input(x, y) != levels[0](x, y)) { printf("input(%d, %d) = %f, but levels[0](%d, %d) = %f\n", x, y, input(x, y), x, y, levels[0](x, y)); return -1; } } } // The remaining levels should be averaging of the levels above them. for (int l = 1; l < 10; l++) { for (int y = 0; y < input.height() >> l; y++) { for (int x = 0; x < input.width() >> l; x++) { float correct = (levels[l-1](2*x, 2*y) + levels[l-1](2*x+1, 2*y) + levels[l-1](2*x, 2*y+1) + levels[l-1](2*x+1, 2*y+1))/4; float actual = levels[l](x, y); if (correct != actual) { printf("levels[%d](%d, %d) = %f instead of %f\n", l, x, y, actual, correct); return -1; } } } } printf("Success!\n"); return 0; } <|endoftext|>
<commit_before>// @(#)root/treeplayer:$Id$ // Author: Philippe Canal 06/06/2004 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers and al. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TBranchProxyDescriptor // // // // Hold the processed information about a TBranch while // // TTreeProxyGenerator is parsing the TTree information. // // Also contains the routine use to generate the appropriate code // // fragment in the result of MakeProxy. // // // ////////////////////////////////////////////////////////////////////////// #include "TBranchProxyDescriptor.h" #include "TClonesArray.h" #include "TError.h" #include "TROOT.h" #include "TTreeFormula.h" #include "TFormLeafInfo.h" #include <ctype.h> ClassImp(ROOT::TBranchProxyDescriptor); namespace ROOT { TBranchProxyDescriptor::TBranchProxyDescriptor(const char *dataname, const char *type, const char *branchname, Bool_t split, Bool_t skipped, Bool_t isleaflist) : TNamed(dataname,type),fBranchName(branchname),fIsSplit(split),fBranchIsSkipped(skipped),fIsLeafList(isleaflist) { // Constructor. fDataName = GetName(); if (fDataName.Length() && fDataName[fDataName.Length()-1]=='.') fDataName.Remove(fDataName.Length()-1); fDataName.ReplaceAll(".","_"); fDataName.ReplaceAll("<","_"); fDataName.ReplaceAll(">","_"); if (!isalpha(fDataName[0])) fDataName.Insert(0,"_"); fDataName.ReplaceAll(" ",""); fDataName.ReplaceAll("*","st"); fDataName.ReplaceAll("&","rf"); } const char *TBranchProxyDescriptor::GetDataName() { // Get the name of the data member. return fDataName; } const char *TBranchProxyDescriptor::GetTypeName() { // Get the name of the type of the data member return GetTitle(); } const char *TBranchProxyDescriptor::GetBranchName() { // Get the branch name. return fBranchName.Data(); } Bool_t TBranchProxyDescriptor::IsEquivalent(const TBranchProxyDescriptor *other, Bool_t inClass) { // Return true if this description is the 'same' as the other decription. if ( !other ) return false; if ( other == this ) return true; if ( inClass ) { // If this description belong to a class, the branchname will be // stripped. } else { if ( fBranchName != other->fBranchName ) return false; } if ( fIsSplit != other->fIsSplit ) return false; if ( fBranchIsSkipped != other->fBranchIsSkipped) return false; if ( strcmp(GetName(),other->GetName()) ) return false; if ( strcmp(GetTitle(),other->GetTitle()) ) return false; return true; } Bool_t TBranchProxyDescriptor::IsSplit() const { // Return true if the branch is split return fIsSplit; } void TBranchProxyDescriptor::OutputDecl(FILE *hf, int offset, UInt_t maxVarname) { // Output the declaration corresponding to this proxy fprintf(hf,"%-*s%-*s %s;\n", offset," ", maxVarname, GetTypeName(), GetDataName()); // might want to add a comment } void TBranchProxyDescriptor::OutputInit(FILE *hf, int offset, UInt_t maxVarname, const char *prefix) { // Output the initialization corresponding to this proxy if (fIsSplit) { const char *subbranchname = GetBranchName(); const char *above = ""; if (strncmp(prefix,subbranchname,strlen(prefix))==0 && strcmp(prefix,subbranchname)!=0) { subbranchname += strlen(prefix)+1; // +1 for the dot "." above = "ffPrefix, "; } if (fBranchIsSkipped) { fprintf(hf,"\n%-*s %-*s(director, obj.GetProxy(), \"%s\", %s\"%s\")", offset," ", maxVarname, GetDataName(), GetDataName(), above, subbranchname); } else { if (fIsLeafList) { if (above[0]=='\0') { fprintf(hf,"\n%-*s %-*s(director, \"%s\", \"\", \"%s\")", offset," ", maxVarname, GetDataName(), subbranchname, GetDataName()); } else { fprintf(hf,"\n%-*s %-*s(director, %s\"%s\", \"%s\")", offset," ", maxVarname, GetDataName(), above, subbranchname, GetDataName()); } } else { fprintf(hf,"\n%-*s %-*s(director, %s\"%s\")", offset," ", maxVarname, GetDataName(), above, subbranchname); } } } else { fprintf(hf,"\n%-*s %-*s(director, obj.GetProxy(), \"%s\")", offset," ", maxVarname, GetDataName(), GetBranchName() ); //fprintf(hf,"\n%-*s %-*s(director, ffPrefix, \"\", \"%s\")", // offset," ", maxVarname, GetName(), GetBranchName() ); } } } <commit_msg>In MakeProxy also replace : in the branchname to data member name translation<commit_after>// @(#)root/treeplayer:$Id$ // Author: Philippe Canal 06/06/2004 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers and al. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TBranchProxyDescriptor // // // // Hold the processed information about a TBranch while // // TTreeProxyGenerator is parsing the TTree information. // // Also contains the routine use to generate the appropriate code // // fragment in the result of MakeProxy. // // // ////////////////////////////////////////////////////////////////////////// #include "TBranchProxyDescriptor.h" #include "TClonesArray.h" #include "TError.h" #include "TROOT.h" #include "TTreeFormula.h" #include "TFormLeafInfo.h" #include <ctype.h> ClassImp(ROOT::TBranchProxyDescriptor); namespace ROOT { TBranchProxyDescriptor::TBranchProxyDescriptor(const char *dataname, const char *type, const char *branchname, Bool_t split, Bool_t skipped, Bool_t isleaflist) : TNamed(dataname,type),fBranchName(branchname),fIsSplit(split),fBranchIsSkipped(skipped),fIsLeafList(isleaflist) { // Constructor. fDataName = GetName(); if (fDataName.Length() && fDataName[fDataName.Length()-1]=='.') fDataName.Remove(fDataName.Length()-1); fDataName.ReplaceAll(".","_"); fDataName.ReplaceAll(":","_"); fDataName.ReplaceAll("<","_"); fDataName.ReplaceAll(">","_"); if (!isalpha(fDataName[0])) fDataName.Insert(0,"_"); fDataName.ReplaceAll(" ",""); fDataName.ReplaceAll("*","st"); fDataName.ReplaceAll("&","rf"); } const char *TBranchProxyDescriptor::GetDataName() { // Get the name of the data member. return fDataName; } const char *TBranchProxyDescriptor::GetTypeName() { // Get the name of the type of the data member return GetTitle(); } const char *TBranchProxyDescriptor::GetBranchName() { // Get the branch name. return fBranchName.Data(); } Bool_t TBranchProxyDescriptor::IsEquivalent(const TBranchProxyDescriptor *other, Bool_t inClass) { // Return true if this description is the 'same' as the other decription. if ( !other ) return false; if ( other == this ) return true; if ( inClass ) { // If this description belong to a class, the branchname will be // stripped. } else { if ( fBranchName != other->fBranchName ) return false; } if ( fIsSplit != other->fIsSplit ) return false; if ( fBranchIsSkipped != other->fBranchIsSkipped) return false; if ( strcmp(GetName(),other->GetName()) ) return false; if ( strcmp(GetTitle(),other->GetTitle()) ) return false; return true; } Bool_t TBranchProxyDescriptor::IsSplit() const { // Return true if the branch is split return fIsSplit; } void TBranchProxyDescriptor::OutputDecl(FILE *hf, int offset, UInt_t maxVarname) { // Output the declaration corresponding to this proxy fprintf(hf,"%-*s%-*s %s;\n", offset," ", maxVarname, GetTypeName(), GetDataName()); // might want to add a comment } void TBranchProxyDescriptor::OutputInit(FILE *hf, int offset, UInt_t maxVarname, const char *prefix) { // Output the initialization corresponding to this proxy if (fIsSplit) { const char *subbranchname = GetBranchName(); const char *above = ""; if (strncmp(prefix,subbranchname,strlen(prefix))==0 && strcmp(prefix,subbranchname)!=0) { subbranchname += strlen(prefix)+1; // +1 for the dot "." above = "ffPrefix, "; } if (fBranchIsSkipped) { fprintf(hf,"\n%-*s %-*s(director, obj.GetProxy(), \"%s\", %s\"%s\")", offset," ", maxVarname, GetDataName(), GetDataName(), above, subbranchname); } else { if (fIsLeafList) { if (above[0]=='\0') { fprintf(hf,"\n%-*s %-*s(director, \"%s\", \"\", \"%s\")", offset," ", maxVarname, GetDataName(), subbranchname, GetDataName()); } else { fprintf(hf,"\n%-*s %-*s(director, %s\"%s\", \"%s\")", offset," ", maxVarname, GetDataName(), above, subbranchname, GetDataName()); } } else { fprintf(hf,"\n%-*s %-*s(director, %s\"%s\")", offset," ", maxVarname, GetDataName(), above, subbranchname); } } } else { fprintf(hf,"\n%-*s %-*s(director, obj.GetProxy(), \"%s\")", offset," ", maxVarname, GetDataName(), GetBranchName() ); //fprintf(hf,"\n%-*s %-*s(director, ffPrefix, \"\", \"%s\")", // offset," ", maxVarname, GetName(), GetBranchName() ); } } } <|endoftext|>
<commit_before><commit_msg>only inflate if status from InitDecompress is good<commit_after><|endoftext|>
<commit_before>// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "fplbase/input.h" #include "states/states_common.h" #ifdef ANDROID_CARDBOARD #include "fplbase/renderer_hmd.h" #endif namespace fpl { namespace fpl_project { static const vec4 kGreenishColor(0.05f, 0.2f, 0.1f, 1.0f); static void RenderStereoscopic(Renderer& renderer, World* world, Camera& camera, Camera* cardboard_camera, InputSystem* input_system) { #ifdef ANDROID_CARDBOARD auto render_callback = [&renderer, world, &camera, cardboard_camera]( const mat4& hmd_viewport_transform) { // Update the Cardboard camera with the translation changes from the given // transform, which contains the shifts for the eyes. const vec3 hmd_translation = (hmd_viewport_transform * mathfu::kAxisW4f * hmd_viewport_transform).xyz(); const vec3 corrected_translation = vec3(hmd_translation.x(), -hmd_translation.z(), hmd_translation.y()); cardboard_camera->set_position(camera.position() + corrected_translation); cardboard_camera->set_facing(camera.facing()); cardboard_camera->set_up(camera.up()); world->world_renderer->RenderWorld(*cardboard_camera, renderer, world); }; HeadMountedDisplayRender(input_system, &renderer, kGreenishColor, render_callback); #else (void)renderer; (void)world; (void)camera; (void)cardboard_camera; (void)input_system; #endif // ANDROID_CARDBOARD } void RenderWorld(Renderer& renderer, World* world, Camera& camera, Camera* cardboard_camera, InputSystem* input_system) { vec2 window_size = vec2(renderer.window_size()); world->river_component.UpdateRiverMeshes(); if (world->is_in_cardboard) { window_size.x() = window_size.x() / 2; cardboard_camera->set_viewport_resolution(window_size); } camera.set_viewport_resolution(window_size); if (world->is_in_cardboard) { // This takes care of setting/clearing the framebuffer for us. RenderStereoscopic(renderer, world, camera, cardboard_camera, input_system); } else { // Always clear the framebuffer, even though we overwrite it with the // skybox, since it's a speedup on tile-based architectures, see .e.g.: // http://www.seas.upenn.edu/~pcozzi/OpenGLInsights/OpenGLInsights-TileBasedArchitectures.pdf renderer.ClearFrameBuffer(mathfu::kZeros4f); world->world_renderer->RenderWorld(camera, renderer, world); } } void UpdateMainCamera(Camera* main_camera, World* world) { auto player = world->player_component.begin()->entity; auto transform_component = &world->transform_component; main_camera->set_position(transform_component->WorldPosition(player)); main_camera->set_facing( transform_component->WorldOrientation(player).Inverse() * mathfu::kAxisY3f); auto player_data = world->entity_manager.GetComponentData<PlayerData>(player); auto raft_orientation = transform_component->WorldOrientation( world->entity_manager.GetComponent<ServicesComponent>()->raft_entity()); main_camera->set_up(raft_orientation.Inverse() * player_data->GetUp()); } gui::Event ImageButtonWithLabel(const Texture& tex, float size, const gui::Margin& margin, const char* label) { gui::StartGroup(gui::kLayoutVerticalLeft, size, "ImageButtonWithLabel"); gui::SetMargin(margin); auto event = gui::CheckEvent(); gui::ImageBackground(tex); gui::Label(label, size); gui::EndGroup(); return event; } } // fpl_project } // fpl <commit_msg>Disabling the default undistortion in Cardboard.<commit_after>// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "fplbase/input.h" #include "states/states_common.h" #ifdef ANDROID_CARDBOARD #include "fplbase/renderer_hmd.h" #endif namespace fpl { namespace fpl_project { static const vec4 kGreenishColor(0.05f, 0.2f, 0.1f, 1.0f); static void RenderStereoscopic(Renderer& renderer, World* world, Camera& camera, Camera* cardboard_camera, InputSystem* input_system) { #ifdef ANDROID_CARDBOARD auto render_callback = [&renderer, world, &camera, cardboard_camera]( const mat4& hmd_viewport_transform) { // Update the Cardboard camera with the translation changes from the given // transform, which contains the shifts for the eyes. const vec3 hmd_translation = (hmd_viewport_transform * mathfu::kAxisW4f * hmd_viewport_transform).xyz(); const vec3 corrected_translation = vec3(hmd_translation.x(), -hmd_translation.z(), hmd_translation.y()); cardboard_camera->set_position(camera.position() + corrected_translation); cardboard_camera->set_facing(camera.facing()); cardboard_camera->set_up(camera.up()); world->world_renderer->RenderWorld(*cardboard_camera, renderer, world); }; HeadMountedDisplayRender(input_system, &renderer, kGreenishColor, render_callback, false); #else (void)renderer; (void)world; (void)camera; (void)cardboard_camera; (void)input_system; #endif // ANDROID_CARDBOARD } void RenderWorld(Renderer& renderer, World* world, Camera& camera, Camera* cardboard_camera, InputSystem* input_system) { vec2 window_size = vec2(renderer.window_size()); world->river_component.UpdateRiverMeshes(); if (world->is_in_cardboard) { window_size.x() = window_size.x() / 2; cardboard_camera->set_viewport_resolution(window_size); } camera.set_viewport_resolution(window_size); if (world->is_in_cardboard) { // This takes care of setting/clearing the framebuffer for us. RenderStereoscopic(renderer, world, camera, cardboard_camera, input_system); } else { // Always clear the framebuffer, even though we overwrite it with the // skybox, since it's a speedup on tile-based architectures, see .e.g.: // http://www.seas.upenn.edu/~pcozzi/OpenGLInsights/OpenGLInsights-TileBasedArchitectures.pdf renderer.ClearFrameBuffer(mathfu::kZeros4f); world->world_renderer->RenderWorld(camera, renderer, world); } } void UpdateMainCamera(Camera* main_camera, World* world) { auto player = world->player_component.begin()->entity; auto transform_component = &world->transform_component; main_camera->set_position(transform_component->WorldPosition(player)); main_camera->set_facing( transform_component->WorldOrientation(player).Inverse() * mathfu::kAxisY3f); auto player_data = world->entity_manager.GetComponentData<PlayerData>(player); auto raft_orientation = transform_component->WorldOrientation( world->entity_manager.GetComponent<ServicesComponent>()->raft_entity()); main_camera->set_up(raft_orientation.Inverse() * player_data->GetUp()); } gui::Event ImageButtonWithLabel(const Texture& tex, float size, const gui::Margin& margin, const char* label) { gui::StartGroup(gui::kLayoutVerticalLeft, size, "ImageButtonWithLabel"); gui::SetMargin(margin); auto event = gui::CheckEvent(); gui::ImageBackground(tex); gui::Label(label, size); gui::EndGroup(); return event; } } // fpl_project } // fpl <|endoftext|>
<commit_before>#pragma once #include <cassert> #include <iostream> #include <string> #include <vector> #include <Python.h> //------------------------------------------------------------------------------ namespace py { class Long; class Object; class Unicode; // FIXME: Remove this. constexpr PyGetSetDef GETSETDEF_END {nullptr, nullptr, nullptr, nullptr, nullptr}; //------------------------------------------------------------------------------ class Exception { public: Exception() {} Exception(PyObject* exception, char const* message) { PyErr_SetString(exception, message); } template<typename A> Exception(PyObject* exception, A&& message) { PyErr_SetString(exception, std::string(std::forward<A>(message)).c_str()); } /** * Clears up the Python exception state. */ static void Clear() { PyErr_Clear(); } }; /** * Template wrapper for a specific Python exception type. */ template<PyObject** EXC> class ExceptionWrapper : public Exception { public: template<typename A> ExceptionWrapper(A&& message) : Exception(*EXC, std::forward<A>(message)) {} }; using ArithmeticError = ExceptionWrapper<&PyExc_ArithmeticError>; using AttributeError = ExceptionWrapper<&PyExc_AttributeError>; using EnvironmentError = ExceptionWrapper<&PyExc_EnvironmentError>; using FileExistsError = ExceptionWrapper<&PyExc_FileExistsError>; using FileNotFoundError = ExceptionWrapper<&PyExc_FileNotFoundError>; using IOError = ExceptionWrapper<&PyExc_IOError>; using IndexError = ExceptionWrapper<&PyExc_IndexError>; using InterruptedError = ExceptionWrapper<&PyExc_InterruptedError>; using IsADirectoryError = ExceptionWrapper<&PyExc_IsADirectoryError>; using KeyError = ExceptionWrapper<&PyExc_KeyError>; using LookupError = ExceptionWrapper<&PyExc_LookupError>; using NameError = ExceptionWrapper<&PyExc_NameError>; using NotADirectoryError = ExceptionWrapper<&PyExc_NotADirectoryError>; using NotImplementedError = ExceptionWrapper<&PyExc_NotImplementedError>; using OverflowError = ExceptionWrapper<&PyExc_OverflowError>; using PermissionError = ExceptionWrapper<&PyExc_PermissionError>; using ReferenceError = ExceptionWrapper<&PyExc_ReferenceError>; using RuntimeError = ExceptionWrapper<&PyExc_RuntimeError>; using StopIteration = ExceptionWrapper<&PyExc_StopIteration>; using SystemExit = ExceptionWrapper<&PyExc_SystemExit>; using TimeoutError = ExceptionWrapper<&PyExc_TimeoutError>; using TypeError = ExceptionWrapper<&PyExc_TypeError>; using ValueError = ExceptionWrapper<&PyExc_ValueError>; using ZeroDivisionError = ExceptionWrapper<&PyExc_ZeroDivisionError>; /** * Raises 'Exception' if value is not zero. */ inline void check_zero(int value) { assert(value == 0 || value == -1); if (value != 0) throw Exception(); } /** * Raises 'Exception' if value is not true. */ inline void check_true(int value) { if (value == 0) throw Exception(); } //------------------------------------------------------------------------------ template<typename T> inline T* cast(PyObject* obj) { assert(T::Check(obj)); // FIXME: TypeError? return static_cast<T*>(obj); } //------------------------------------------------------------------------------ inline PyObject* incref(PyObject* obj) { Py_INCREF(obj); return obj; } inline PyObject* decref(PyObject* obj) { Py_DECREF(obj); return obj; } template<typename T> class ref { public: /** * Takes an existing reference. * * Call this method on an object pointer that comes with an assumed reference, * such as the return value of an API call that returns ownership. */ static ref<T> take(PyObject* obj) { return ref(cast<T>(obj)); } /** * Creates a new reference. */ static ref<T> of(ref<T> obj_ref) { return of(obj_ref.obj_); } /** * Creates a new reference. */ static ref<T> of(T* obj) { incref(obj); return ref{obj}; } /** * Creates a new reference, casting. */ static ref<T> of(PyObject* obj) { return of(cast<T>(obj)); } /** * Default ctor: null reference. */ ref() : obj_(nullptr) {} /** * Move ctor. */ ref(ref<T>&& ref) : obj_(ref.release()) {} /** * Move ctor from another ref type. */ template<typename U> ref(ref<U>&& ref) : obj_(ref.release()) {} ~ref() { clear(); } void operator=(ref<T>&& ref) { clear(); obj_ = ref.release(); } operator T*() const { return obj_; } T* operator->() const { return obj_; } T* release() { auto obj = obj_; obj_ = nullptr; return obj; } void clear() { if (obj_ != nullptr) decref(obj_); } private: ref(T* obj) : obj_(obj) {} T* obj_; }; inline ref<Object> none_ref() { return ref<Object>::of(Py_None); } //============================================================================== class Object : public PyObject { public: static bool Check(PyObject* obj) { return true; } auto Length() { return PyObject_Length(this); } auto Repr() { return ref<Unicode>::take(PyObject_Repr(this)); } auto Str() { return ref<Unicode>::take(PyObject_Str(this)); } ref<py::Long> Long(); long long_value(); }; template<typename T> inline std::ostream& operator<<(std::ostream& os, ref<T>& ref) { os << ref->Str()->as_utf8(); return os; } //------------------------------------------------------------------------------ class Dict : public Object { public: static bool Check(PyObject* obj) { return PyDict_Check(obj); } }; //------------------------------------------------------------------------------ class Bool : public Object { public: static ref<Bool> const TRUE; static ref<Bool> const FALSE; static bool Check(PyObject* obj) { return PyBool_Check(obj); } static auto from(bool value) { return ref<Bool>::of(value ? Py_True : Py_False); } operator bool() { return this == Py_True; } }; //------------------------------------------------------------------------------ class Long : public Object { public: static bool Check(PyObject* obj) { return PyLong_Check(obj); } static auto FromLong(long val) { return ref<Long>::take(PyLong_FromLong(val)); } operator long() { return PyLong_AsLong(this); } }; //------------------------------------------------------------------------------ class Float : public Object { public: static bool Check(PyObject* obj) { return PyFloat_Check(obj); } static auto FromDouble(double val) { return ref<Float>::take(PyFloat_FromDouble(val)); } operator double() { return PyFloat_AsDouble(this); } }; //------------------------------------------------------------------------------ class Module : public Object { public: static bool Check(PyObject* obj) { return PyModule_Check(obj); } static auto Create(PyModuleDef* def) { return ref<Module>::take(PyModule_Create(def)); } void AddObject(char const* name, PyObject* val) { check_zero(PyModule_AddObject(this, name, incref(val))); } void add(PyTypeObject* type) { // Make sure the qualified name of the type includes this module's name. std::string const qualname = type->tp_name; std::string const mod_name = PyModule_GetName(this); auto dot = qualname.find_last_of('.'); assert(dot != std::string::npos); assert(qualname.compare(0, dot, mod_name) == 1); // Add it, under its unqualified name. AddObject(qualname.substr(dot + 1).c_str(), (PyObject*) type); } }; //------------------------------------------------------------------------------ class Tuple : public Object { public: static bool Check(PyObject* obj) { return PyTuple_Check(obj); } }; //------------------------------------------------------------------------------ class Type : public PyTypeObject { public: Type(PyTypeObject o) : PyTypeObject(o) {} void Ready() { check_zero(PyType_Ready(this)); } }; //------------------------------------------------------------------------------ class Unicode : public Object { public: static bool Check(PyObject* obj) { return PyUnicode_Check(obj); } static auto FromString(char* utf8) { return ref<Unicode>::take(PyUnicode_FromString(utf8)); } // FIXME: Cast on const here? static auto FromStringAndSize(char* utf8, size_t length) { return ref<Unicode>::take(PyUnicode_FromStringAndSize(utf8, length)); } static auto from(std::string const& str) { return FromStringAndSize(const_cast<char*>(str.c_str()), str.length()); } static auto from(char character) { return FromStringAndSize(&character, 1); } char* as_utf8() { return PyUnicode_AsUTF8(this); } std::string as_utf8_string() { Py_ssize_t length; char* const utf8 = PyUnicode_AsUTF8AndSize(this, &length); if (utf8 == nullptr) throw Exception(); else return std::string(utf8, length); } }; template<> inline std::ostream& operator<<(std::ostream& os, ref<Unicode>& ref) { os << ref->as_utf8(); return os; } //============================================================================== inline ref<Long> Object::Long() { // FIXME: Check errors. return ref<py::Long>::take(PyNumber_Long(this)); } inline long Object::long_value() { return (long) *Long(); } //============================================================================== namespace Arg { inline void ParseTupleAndKeywords( Tuple* args, Dict* kw_args, char const* format, char const* const* keywords, ...) { va_list vargs; va_start(vargs, keywords); auto result = PyArg_VaParseTupleAndKeywords( args, kw_args, (char*) format, (char**) keywords, vargs); va_end(vargs); check_true(result); } } // namespace Arg //============================================================================== class ExtensionType : public Object { public: PyObject_HEAD }; //============================================================================== // Buffer objects // See https://docs.python.org/3/c-api/buffer.html. /** * A unique reference view to a buffer object. * * Supports move semantics only; no copy. */ class BufferRef { public: /** * Creates a buffer view of an object. The ref holds a reference to the * object. */ BufferRef(PyObject* obj, int flags) { if (PyObject_GetBuffer(obj, &buffer_, flags) != 0) throw Exception(); assert(buffer_.obj != nullptr); } BufferRef(Py_buffer&& buffer) : buffer_(buffer) {} BufferRef(BufferRef&& ref) : buffer_(ref.buffer_) { ref.buffer_.obj = nullptr; } ~BufferRef() { // Only releases if buffer_.obj is not null. PyBuffer_Release(&buffer_); assert(buffer_.obj == nullptr); } BufferRef(BufferRef const&) = delete; void operator=(BufferRef const&) = delete; Py_buffer* operator->() { return &buffer_; } private: Py_buffer buffer_; }; //============================================================================== template<typename CLASS> using MethodPtr = ref<Object> (*)(CLASS* self, Tuple* args, Dict* kw_args); /** * Wraps a method that takes args and kw_args and returns an object. */ template<typename CLASS, MethodPtr<CLASS> METHOD> PyObject* wrap(PyObject* self, PyObject* args, PyObject* kw_args) { ref<Object> result; try { result = METHOD( reinterpret_cast<CLASS*>(self), reinterpret_cast<Tuple*>(args), reinterpret_cast<Dict*>(kw_args)); } catch (Exception) { return nullptr; } assert(result != nullptr); return result.release(); } template<typename CLASS> class Methods { public: Methods() : done_(false) {} template<MethodPtr<CLASS> METHOD> Methods& add(char const* name, char const* doc=nullptr) { assert(name != nullptr); assert(!done_); methods_.push_back({ name, (PyCFunction) wrap<CLASS, METHOD>, METH_VARARGS | METH_KEYWORDS, doc }); return *this; } operator PyMethodDef*() { if (!done_) { // Add the sentry. methods_.push_back({nullptr, nullptr, 0, nullptr}); done_ = true; } return &methods_[0]; } private: bool done_; std::vector<PyMethodDef> methods_; }; //------------------------------------------------------------------------------ template<typename CLASS> using GetPtr = ref<Object> (*)(CLASS* self, void* closure); template<typename CLASS, GetPtr<CLASS> METHOD> PyObject* wrap_get(PyObject* self, void* closure) { ref<Object> result; try { result = METHOD(reinterpret_cast<CLASS*>(self), closure); } catch (Exception) { return nullptr; } assert(result != nullptr); return result.release(); } template<typename CLASS> class GetSets { public: GetSets() : done_(false) {} template<GetPtr<CLASS> METHOD> GetSets& add_get(char const* name, char const* doc=nullptr, void* closure=nullptr) { assert(name != nullptr); assert(!done_); getsets_.push_back({ (char*) name, (getter) wrap_get<CLASS, METHOD>, (setter) nullptr, (char*) doc, (void*) closure, }); return *this; } operator PyGetSetDef*() { if (!done_) { // Add the sentry. getsets_.push_back({nullptr, nullptr, nullptr, nullptr, nullptr}); done_ = true; } return &getsets_[0]; } private: bool done_; std::vector<PyGetSetDef> getsets_; }; //------------------------------------------------------------------------------ } // namespace py <commit_msg>Factor out ref base class.<commit_after>#pragma once #include <cassert> #include <iostream> #include <string> #include <vector> #include <Python.h> //------------------------------------------------------------------------------ namespace py { class Long; class Object; class Unicode; // FIXME: Remove this. constexpr PyGetSetDef GETSETDEF_END {nullptr, nullptr, nullptr, nullptr, nullptr}; //------------------------------------------------------------------------------ class Exception { public: Exception() {} Exception(PyObject* exception, char const* message) { PyErr_SetString(exception, message); } template<typename A> Exception(PyObject* exception, A&& message) { PyErr_SetString(exception, std::string(std::forward<A>(message)).c_str()); } /** * Clears up the Python exception state. */ static void Clear() { PyErr_Clear(); } }; /** * Template wrapper for a specific Python exception type. */ template<PyObject** EXC> class ExceptionWrapper : public Exception { public: template<typename A> ExceptionWrapper(A&& message) : Exception(*EXC, std::forward<A>(message)) {} }; using ArithmeticError = ExceptionWrapper<&PyExc_ArithmeticError>; using AttributeError = ExceptionWrapper<&PyExc_AttributeError>; using EnvironmentError = ExceptionWrapper<&PyExc_EnvironmentError>; using FileExistsError = ExceptionWrapper<&PyExc_FileExistsError>; using FileNotFoundError = ExceptionWrapper<&PyExc_FileNotFoundError>; using IOError = ExceptionWrapper<&PyExc_IOError>; using IndexError = ExceptionWrapper<&PyExc_IndexError>; using InterruptedError = ExceptionWrapper<&PyExc_InterruptedError>; using IsADirectoryError = ExceptionWrapper<&PyExc_IsADirectoryError>; using KeyError = ExceptionWrapper<&PyExc_KeyError>; using LookupError = ExceptionWrapper<&PyExc_LookupError>; using NameError = ExceptionWrapper<&PyExc_NameError>; using NotADirectoryError = ExceptionWrapper<&PyExc_NotADirectoryError>; using NotImplementedError = ExceptionWrapper<&PyExc_NotImplementedError>; using OverflowError = ExceptionWrapper<&PyExc_OverflowError>; using PermissionError = ExceptionWrapper<&PyExc_PermissionError>; using ReferenceError = ExceptionWrapper<&PyExc_ReferenceError>; using RuntimeError = ExceptionWrapper<&PyExc_RuntimeError>; using StopIteration = ExceptionWrapper<&PyExc_StopIteration>; using SystemExit = ExceptionWrapper<&PyExc_SystemExit>; using TimeoutError = ExceptionWrapper<&PyExc_TimeoutError>; using TypeError = ExceptionWrapper<&PyExc_TypeError>; using ValueError = ExceptionWrapper<&PyExc_ValueError>; using ZeroDivisionError = ExceptionWrapper<&PyExc_ZeroDivisionError>; /** * Raises 'Exception' if value is not zero. */ inline void check_zero(int value) { assert(value == 0 || value == -1); if (value != 0) throw Exception(); } /** * Raises 'Exception' if value is not true. */ inline void check_true(int value) { if (value == 0) throw Exception(); } //------------------------------------------------------------------------------ template<typename T> inline T* cast(PyObject* obj) { assert(T::Check(obj)); // FIXME: TypeError? return static_cast<T*>(obj); } //------------------------------------------------------------------------------ inline PyObject* incref(PyObject* obj) { Py_INCREF(obj); return obj; } inline PyObject* decref(PyObject* obj) { Py_DECREF(obj); return obj; } //------------------------------------------------------------------------------ /** * Type-generic base class for references. * * An instance of this class owns a reference to a Python object. */ class baseref { public: ~baseref() { clear(); } Object* release() { auto obj = obj_; obj_ = nullptr; return obj; } void clear(); protected: baseref(Object* obj) : obj_(obj) {} Object* obj_; }; template<typename T> class ref : public baseref { public: /** * Takes an existing reference. * * Call this method on an object pointer that comes with an assumed reference, * such as the return value of an API call that returns ownership. */ static ref<T> take(PyObject* obj) { return ref(cast<T>(obj)); } /** * Creates a new reference. */ static ref<T> of(ref<T> obj_ref) { return of(obj_ref.obj_); } /** * Creates a new reference. */ static ref<T> of(T* obj) { incref(obj); return ref{obj}; } /** * Creates a new reference, casting. */ static ref<T> of(PyObject* obj) { return of(cast<T>(obj)); } /** * Default ctor: null reference. */ ref() : baseref(nullptr) {} /** * Move ctor. */ ref(ref<T>&& ref) : baseref(ref.release()) {} /** * Move ctor from another ref type. */ template<typename U> ref(ref<U>&& ref) : baseref(ref.release()) {} void operator=(ref<T>&& ref) { clear(); obj_ = ref.release(); } operator T*() const { return (T*) obj_; } T* operator->() const { return (T*) obj_; } T* release() { return (T*) baseref::release(); } private: ref(T* obj) : baseref(obj) {} }; inline ref<Object> none_ref() { return ref<Object>::of(Py_None); } //============================================================================== class Object : public PyObject { public: static bool Check(PyObject* obj) { return true; } auto Length() { return PyObject_Length(this); } auto Repr() { return ref<Unicode>::take(PyObject_Repr(this)); } auto Str() { return ref<Unicode>::take(PyObject_Str(this)); } ref<py::Long> Long(); long long_value(); }; template<typename T> inline std::ostream& operator<<(std::ostream& os, ref<T>& ref) { os << ref->Str()->as_utf8(); return os; } //------------------------------------------------------------------------------ class Dict : public Object { public: static bool Check(PyObject* obj) { return PyDict_Check(obj); } }; //------------------------------------------------------------------------------ class Bool : public Object { public: static ref<Bool> const TRUE; static ref<Bool> const FALSE; static bool Check(PyObject* obj) { return PyBool_Check(obj); } static auto from(bool value) { return ref<Bool>::of(value ? Py_True : Py_False); } operator bool() { return this == Py_True; } }; //------------------------------------------------------------------------------ class Long : public Object { public: static bool Check(PyObject* obj) { return PyLong_Check(obj); } static auto FromLong(long val) { return ref<Long>::take(PyLong_FromLong(val)); } operator long() { return PyLong_AsLong(this); } }; //------------------------------------------------------------------------------ class Float : public Object { public: static bool Check(PyObject* obj) { return PyFloat_Check(obj); } static auto FromDouble(double val) { return ref<Float>::take(PyFloat_FromDouble(val)); } operator double() { return PyFloat_AsDouble(this); } }; //------------------------------------------------------------------------------ class Module : public Object { public: static bool Check(PyObject* obj) { return PyModule_Check(obj); } static auto Create(PyModuleDef* def) { return ref<Module>::take(PyModule_Create(def)); } void AddObject(char const* name, PyObject* val) { check_zero(PyModule_AddObject(this, name, incref(val))); } void add(PyTypeObject* type) { // Make sure the qualified name of the type includes this module's name. std::string const qualname = type->tp_name; std::string const mod_name = PyModule_GetName(this); auto dot = qualname.find_last_of('.'); assert(dot != std::string::npos); assert(qualname.compare(0, dot, mod_name) == 1); // Add it, under its unqualified name. AddObject(qualname.substr(dot + 1).c_str(), (PyObject*) type); } }; //------------------------------------------------------------------------------ class Tuple : public Object { public: static bool Check(PyObject* obj) { return PyTuple_Check(obj); } }; //------------------------------------------------------------------------------ class Type : public PyTypeObject { public: Type(PyTypeObject o) : PyTypeObject(o) {} void Ready() { check_zero(PyType_Ready(this)); } }; //------------------------------------------------------------------------------ class Unicode : public Object { public: static bool Check(PyObject* obj) { return PyUnicode_Check(obj); } static auto FromString(char* utf8) { return ref<Unicode>::take(PyUnicode_FromString(utf8)); } // FIXME: Cast on const here? static auto FromStringAndSize(char* utf8, size_t length) { return ref<Unicode>::take(PyUnicode_FromStringAndSize(utf8, length)); } static auto from(std::string const& str) { return FromStringAndSize(const_cast<char*>(str.c_str()), str.length()); } static auto from(char character) { return FromStringAndSize(&character, 1); } char* as_utf8() { return PyUnicode_AsUTF8(this); } std::string as_utf8_string() { Py_ssize_t length; char* const utf8 = PyUnicode_AsUTF8AndSize(this, &length); if (utf8 == nullptr) throw Exception(); else return std::string(utf8, length); } }; template<> inline std::ostream& operator<<(std::ostream& os, ref<Unicode>& ref) { os << ref->as_utf8(); return os; } //============================================================================== inline void baseref::clear() { if (obj_ != nullptr) decref(obj_); } inline ref<Long> Object::Long() { // FIXME: Check errors. return ref<py::Long>::take(PyNumber_Long(this)); } inline long Object::long_value() { return (long) *Long(); } //============================================================================== namespace Arg { inline void ParseTupleAndKeywords( Tuple* args, Dict* kw_args, char const* format, char const* const* keywords, ...) { va_list vargs; va_start(vargs, keywords); auto result = PyArg_VaParseTupleAndKeywords( args, kw_args, (char*) format, (char**) keywords, vargs); va_end(vargs); check_true(result); } } // namespace Arg //============================================================================== class ExtensionType : public Object { public: PyObject_HEAD }; //============================================================================== // Buffer objects // See https://docs.python.org/3/c-api/buffer.html. /** * A unique reference view to a buffer object. * * Supports move semantics only; no copy. */ class BufferRef { public: /** * Creates a buffer view of an object. The ref holds a reference to the * object. */ BufferRef(PyObject* obj, int flags) { if (PyObject_GetBuffer(obj, &buffer_, flags) != 0) throw Exception(); assert(buffer_.obj != nullptr); } BufferRef(Py_buffer&& buffer) : buffer_(buffer) {} BufferRef(BufferRef&& ref) : buffer_(ref.buffer_) { ref.buffer_.obj = nullptr; } ~BufferRef() { // Only releases if buffer_.obj is not null. PyBuffer_Release(&buffer_); assert(buffer_.obj == nullptr); } BufferRef(BufferRef const&) = delete; void operator=(BufferRef const&) = delete; Py_buffer* operator->() { return &buffer_; } private: Py_buffer buffer_; }; //============================================================================== template<typename CLASS> using MethodPtr = ref<Object> (*)(CLASS* self, Tuple* args, Dict* kw_args); /** * Wraps a method that takes args and kw_args and returns an object. */ template<typename CLASS, MethodPtr<CLASS> METHOD> PyObject* wrap(PyObject* self, PyObject* args, PyObject* kw_args) { ref<Object> result; try { result = METHOD( reinterpret_cast<CLASS*>(self), reinterpret_cast<Tuple*>(args), reinterpret_cast<Dict*>(kw_args)); } catch (Exception) { return nullptr; } assert(result != nullptr); return result.release(); } template<typename CLASS> class Methods { public: Methods() : done_(false) {} template<MethodPtr<CLASS> METHOD> Methods& add(char const* name, char const* doc=nullptr) { assert(name != nullptr); assert(!done_); methods_.push_back({ name, (PyCFunction) wrap<CLASS, METHOD>, METH_VARARGS | METH_KEYWORDS, doc }); return *this; } operator PyMethodDef*() { if (!done_) { // Add the sentry. methods_.push_back({nullptr, nullptr, 0, nullptr}); done_ = true; } return &methods_[0]; } private: bool done_; std::vector<PyMethodDef> methods_; }; //------------------------------------------------------------------------------ template<typename CLASS> using GetPtr = ref<Object> (*)(CLASS* self, void* closure); template<typename CLASS, GetPtr<CLASS> METHOD> PyObject* wrap_get(PyObject* self, void* closure) { ref<Object> result; try { result = METHOD(reinterpret_cast<CLASS*>(self), closure); } catch (Exception) { return nullptr; } assert(result != nullptr); return result.release(); } template<typename CLASS> class GetSets { public: GetSets() : done_(false) {} template<GetPtr<CLASS> METHOD> GetSets& add_get(char const* name, char const* doc=nullptr, void* closure=nullptr) { assert(name != nullptr); assert(!done_); getsets_.push_back({ (char*) name, (getter) wrap_get<CLASS, METHOD>, (setter) nullptr, (char*) doc, (void*) closure, }); return *this; } operator PyGetSetDef*() { if (!done_) { // Add the sentry. getsets_.push_back({nullptr, nullptr, nullptr, nullptr, nullptr}); done_ = true; } return &getsets_[0]; } private: bool done_; std::vector<PyGetSetDef> getsets_; }; //------------------------------------------------------------------------------ } // namespace py <|endoftext|>
<commit_before>#include "MOS6522.h" #include <iostream> MOS6522::MOS6522() : IC() , keyPressed(0) , shiftPressed(false) , cbmPressed(false) { // Set clock speed this->setClockSpeed(2000000); } MOS6522::~MOS6522() { } void MOS6522::setMemory(MOS6502Memory *memory) { this->memory = memory; // Create callbacks //this->createCallBacks(); } void MOS6522::setCpu(MOS6502 *mos6502) { this->mos6502 = mos6502; } void MOS6522::setKeyPressed(uint16_t key) { /* Store high byte first = 0x9120 << 8 | 0x9121 */ keyPressed = key; } void MOS6522::setShiftPressed(bool state) { this->shiftPressed = state; } void MOS6522::setCbmPressed(bool state) { this->cbmPressed = state; } void MOS6522::setJoyStickPressed(Vic20JoyStickButton button, bool state) { this->joyStick[button] = state; } void MOS6522::initialize() { // Clear joystick memory this->memory->writeWord(0x9111, 0xFF); } void MOS6522::tick() { // Tick timer cycle this->tickTimers(); // Handle input in this cycle this->tickInput(); // Increment cycles counter this->cycles += 1; } void MOS6522::tickInput() { // Handle keyboard input // Get keyboard column selection value uint8_t via2PortBValue = this->memory->readWord(this->PORTB); // Get row and column of key press uint8_t column = (keyPressed >> 8) & 0xFF; uint8_t row = keyPressed & 0xFF; // Check whether keyboard should be scanned if (via2PortBValue == 0) { // If port b is 0 then the vic is asking whether any keys are pressed on the keyboard this->memory->silentWriteWord(this->PORTA, keyPressed == 0 ? 0xFF : row); this->memory->silentWriteWord(this->PORTAMIRROR, keyPressed == 0 ? 0xFF : row); } else { // Return keyboard row depending on column state this->memory->silentWriteWord(this->PORTA, (via2PortBValue == column ? (row == 0 ? 0xFF : row) : 0xFF)); this->memory->silentWriteWord(this->PORTAMIRROR, (via2PortBValue == column ? (row == 0 ? 0xFF : row) : 0xFF)); } if ((via2PortBValue == 0xF7) && shiftPressed) { // Return row of shift key this->memory->silentWriteWord(this->PORTA, 0xFD & (keyPressed == 0 ? 0xFF : (column == 0xF7 ? row : 0xFF))); this->memory->silentWriteWord(this->PORTAMIRROR, 0xFD & (keyPressed == 0 ? 0xFF : (column == 0xF7 ? row : 0xFF))); } else if (via2PortBValue == 0xDF && cbmPressed) { // Return row of cbm key this->memory->silentWriteWord(this->PORTA, 0xFE & (keyPressed == 0 ? 0xFF : (column == 0xDF ? row : 0xFF))); this->memory->silentWriteWord(this->PORTAMIRROR, 0xFE & (keyPressed == 0 ? 0xFF : (column == 0xDF ? row : 0xFF))); } // Handle joystick input this->memory->silentWriteWord(via1PORTA, 0xFF); this->memory->silentWriteWord(via1PORTAMIRROR, 0xFF); // If this bit is input, set it to default value, else leave it as it is so it won't mess up keyboard input if (!(this->memory->readWord(via2PortBDDR) & 0x80)) { this->memory->silentWriteWord(PORTB, this->memory->silentReadWord(PORTB) | 0x80); } if (joyStick[Vic20JoyStickButton::Fire]) { this->memory->silentWriteWord(via1PORTA, this->memory->silentReadWord(via1PORTA) & ~0x20); this->memory->silentWriteWord(via1PORTAMIRROR, this->memory->silentReadWord(via1PORTA) & ~0x20); } if (joyStick[Vic20JoyStickButton::Up]) { this->memory->silentWriteWord(via1PORTA, this->memory->silentReadWord(via1PORTA) & ~0x4); this->memory->silentWriteWord(via1PORTAMIRROR, this->memory->silentReadWord(via1PORTA) & ~0x4); } if (joyStick[Vic20JoyStickButton::Down]) { this->memory->silentWriteWord(via1PORTA, this->memory->silentReadWord(via1PORTA) & ~0x8); this->memory->silentWriteWord(via1PORTAMIRROR, this->memory->silentReadWord(via1PORTA) & ~0x8); } if (joyStick[Vic20JoyStickButton::Left]) { this->memory->silentWriteWord(via1PORTA, this->memory->silentReadWord(via1PORTA) & ~0x10); this->memory->silentWriteWord(via1PORTAMIRROR, this->memory->silentReadWord(via1PORTA) & ~0x10); } if (joyStick[Vic20JoyStickButton::Right]) { this->memory->silentWriteWord(PORTB, this->memory->silentReadWord(0x9120) & ~0x80); } } void MOS6522::tickTimers() { // Grab values of timer related registers uint8_t interruptEnable = this->memory->readWord(this->irqEnableAddress); uint8_t interruptFlags = this->memory->readWord(this->irqFlagsAddress); uint8_t auxControl = this->memory->readWord(this->auxControlAddress); // Get timer values uint16_t timer1 = this->memory->silentReadDWord(this->timer1DAddress); uint16_t timer2 = this->memory->silentReadDWord(this->timer2DAddress); // If timer is active, decrement it if (timer1 > 0) this->memory->silentWriteDWord(this->timer1DAddress, --timer1); if (timer2 > 0 && this->memory->silentReadWord(this->timer2HighByteLatch) != 0) { // Decrement t2 this->memory->silentWriteDWord(this->timer2DAddress, --timer2); } // If timeout if (timer1 == 0) { // Set interrupt flag this->memory->silentWriteWord(this->irqFlagsAddress, interruptFlags | 0x40); interruptFlags = this->memory->readWord(this->irqFlagsAddress); } if (timer2 == 0) { // Reset high byte latch if (this->memory->readWord(this->timer2HighByteLatch) != 0) { this->memory->silentWriteDWord(this->timer2DAddress, this->memory->silentReadDWord(this->timer2LowByteLatch)); this->memory->silentWriteDWord(this->timer2HighByteLatch, 0); // Set interrupt flag this->memory->silentWriteWord(this->irqFlagsAddress, interruptFlags | 0x20); interruptFlags = this->memory->readWord(this->irqFlagsAddress); } } // Check if an interrupt request exists in the system if (interruptFlags & interruptEnable & 0x7F) { // Send an interrupt request to the cpu if (mos6502->interrupt()) { // Post interrupt operation if (timer1 == 0) { // Determine what to do with timer based on auxiliary control register if (auxControl & 0x40) { // Continuous interrupt this->memory->silentWriteDWord(this->timer1DAddress, this->memory->silentReadDWord(this->timer1LowByteLatch)); } // Reset interrupt flag this->memory->silentWriteWord(irqFlagsAddress, this->memory->silentReadWord(irqFlagsAddress) & ~0x40); } if (timer2 == 0) { // Reset interrupt flag this->memory->silentWriteWord(irqFlagsAddress, this->memory->silentReadWord(irqFlagsAddress) & ~0x20); } } } } void MOS6522::createCallBacks() { /* class Via1PortACallBack : public MOS6502MemoryCallBack { public: Via1PortACallBack(MOS6502Memory *memory) : MOS6502MemoryCallBack(memory, via1PORTA) {} uint8_t Via1PortACallBack::executeRead() { // If this register is read, bit 7 is set return this->memory->silentReadWord(this->address); } void Via1PortACallBack::executeWrite(uint8_t value) { this->memory->silentWriteWord(via1PORTA, value); this->memory->silentWriteWord(via1PORTAMIRROR, value); } }; Via1PortACallBack *via1PortACallBack = new Via1PortACallBack(this->memory); this->memory->addCallBack(via1PortACallBack); class Via1PortAMirrorCallBack : public MOS6502MemoryCallBack { public: Via1PortAMirrorCallBack(MOS6502Memory *memory) : MOS6502MemoryCallBack(memory, via1PORTAMIRROR) {} uint8_t Via1PortAMirrorCallBack::executeRead() { // If this register is read, bit 7 is set return this->memory->silentReadWord(this->address); } void Via1PortAMirrorCallBack::executeWrite(uint8_t value) { this->memory->silentWriteWord(via1PORTA, value); this->memory->silentWriteWord(via1PORTAMIRROR, value); } }; Via1PortAMirrorCallBack *via1PortAMirrorCallBack = new Via1PortAMirrorCallBack(this->memory); this->memory->addCallBack(via1PortAMirrorCallBack); class Via2PortACallBack : public MOS6502MemoryCallBack { public: Via2PortACallBack(MOS6502Memory *memory) : MOS6502MemoryCallBack(memory, PORTA) {} uint8_t Via2PortACallBack::executeRead() { // If this register is read, bit 7 is set return this->memory->silentReadWord(this->address); } void Via2PortACallBack::executeWrite(uint8_t value) { this->memory->silentWriteWord(PORTA, value); this->memory->silentWriteWord(PORTAMIRROR, value); } }; Via2PortACallBack *via2PortACallBack = new Via2PortACallBack(this->memory); this->memory->addCallBack(via2PortACallBack); class Via2PortAMirrorCallBack : public MOS6502MemoryCallBack { public: Via2PortAMirrorCallBack(MOS6502Memory *memory) : MOS6502MemoryCallBack(memory, PORTAMIRROR) {} uint8_t Via2PortAMirrorCallBack::executeRead() { // If this register is read, bit 7 is set return this->memory->silentReadWord(this->address); } void Via2PortAMirrorCallBack::executeWrite(uint8_t value) { this->memory->silentWriteWord(PORTA, value); this->memory->silentWriteWord(PORTAMIRROR, value); } }; Via2PortAMirrorCallBack *via2PortAMirrorCallBack = new Via2PortAMirrorCallBack(this->memory); this->memory->addCallBack(via2PortAMirrorCallBack); // Create a callback that performs correct operations on writes to the interrupt enable register class InterruptEnableCallBack : public MOS6502MemoryCallBack { public: InterruptEnableCallBack(MOS6502Memory *memory) : MOS6502MemoryCallBack(memory, irqEnableAddress) {} uint8_t InterruptEnableCallBack::executeRead() { // If this register is read, bit 7 is set return this->memory->silentReadWord(this->address) | 0x80; } void InterruptEnableCallBack::executeWrite(uint8_t value) { // If the 7th bit is 1 during a write, each 1 in bits 0-6 sets the corresponding bit in IER if (value & 0x80) { this->memory->silentWriteWord(this->address, this->memory->silentReadWord(irqEnableAddress) | value); } // If the 7th bit is 0 during a write, each 1 in bits 0-6 clears the corresponding bit in IER else { this->memory->silentWriteWord(this->address, this->memory->silentReadWord(irqEnableAddress) & ~value); } } }; InterruptEnableCallBack *interruptEnableCallBack = new InterruptEnableCallBack(this->memory); this->memory->addCallBack(interruptEnableCallBack); class InterruptFlagsCallBack : public MOS6502MemoryCallBack { public: InterruptFlagsCallBack(MOS6502Memory *memory) : MOS6502MemoryCallBack(memory, irqFlagsAddress) {} uint8_t InterruptFlagsCallBack::executeRead() { // If any bit in IFR is set then top bit must be set if (this->memory->silentReadWord(irqFlagsAddress) != 0) { return this->memory->silentReadWord(irqFlagsAddress) | 0x80; } else return this->memory->silentReadWord(irqFlagsAddress); } void InterruptFlagsCallBack::executeWrite(uint8_t value) { // individual flag bits may be cleared by writing a "1" into the appropriate bit of the IFR. this->memory->silentWriteWord(address, this->memory->readWord(this->address) & ~value); } }; InterruptFlagsCallBack *interruptFlagsCallBack = new InterruptFlagsCallBack(this->memory); this->memory->addCallBack(interruptFlagsCallBack); // Create a callback that moves contents of low and high latch to timer on write to high latch class Timer1HighLatchCallBack : public MOS6502MemoryCallBack { public: Timer1HighLatchCallBack(MOS6502Memory *memory) : MOS6502MemoryCallBack(memory, timer1HighByteLatch) {} uint8_t Timer1HighLatchCallBack::executeRead() { return this->memory->silentReadWord(this->address); } void Timer1HighLatchCallBack::executeWrite(uint8_t value) { // On write to high byte latch, transfer latch contents to timer and activate the timer. this->memory->silentWriteWord(this->address, value); // Move contents this->memory->silentWriteDWord(timer1DAddress, memory->silentReadDWord(timer1LowByteLatch)); // Enable timer this->memory->silentWriteWord(irqFlagsAddress, this->memory->silentReadWord(irqFlagsAddress) & ~0x40); } }; Timer1HighLatchCallBack *highByteLatchCallBack = new Timer1HighLatchCallBack(this->memory); this->memory->addCallBack(highByteLatchCallBack); // Create a callback that resets timer 1 on read of low byte class Timer1LowByteCallBack : public MOS6502MemoryCallBack { public: Timer1LowByteCallBack(MOS6502Memory *memory) : MOS6502MemoryCallBack(memory, timer1DAddress) {} uint8_t Timer1LowByteCallBack::executeRead() { // On read of low byte, the timer interrupt enable is reset this->memory->silentWriteWord(irqFlagsAddress, this->memory->silentReadWord(irqFlagsAddress) & ~0x40); return this->memory->silentReadWord(this->address); } void Timer1LowByteCallBack::executeWrite(uint8_t value) { this->memory->silentWriteWord(this->address, value); } }; Timer1LowByteCallBack *lowByteCallBack = new Timer1LowByteCallBack(this->memory); this->memory->addCallBack(lowByteCallBack); */ }<commit_msg>Update MOS6522.cpp<commit_after>#include "MOS6522.h" #include <iostream> MOS6522::MOS6522() : IC() , keyPressed(0) , shiftPressed(false) , cbmPressed(false) { // Set clock speed this->setClockSpeed(2000000); } MOS6522::~MOS6522() { } void MOS6522::setMemory(MOS6502Memory *memory) { this->memory = memory; } void MOS6522::setCpu(MOS6502 *mos6502) { this->mos6502 = mos6502; } void MOS6522::setKeyPressed(uint16_t key) { /* Store high byte first = 0x9120 << 8 | 0x9121 */ keyPressed = key; } void MOS6522::setShiftPressed(bool state) { this->shiftPressed = state; } void MOS6522::setCbmPressed(bool state) { this->cbmPressed = state; } void MOS6522::setJoyStickPressed(Vic20JoyStickButton button, bool state) { this->joyStick[button] = state; } void MOS6522::initialize() { // Clear joystick memory this->memory->writeWord(0x9111, 0xFF); } void MOS6522::tick() { // Tick timer cycle this->tickTimers(); // Handle input in this cycle this->tickInput(); // Increment cycles counter this->cycles += 1; } void MOS6522::tickInput() { // Handle keyboard input // Get keyboard column selection value uint8_t via2PortBValue = this->memory->readWord(this->PORTB); // Get row and column of key press uint8_t column = (keyPressed >> 8) & 0xFF; uint8_t row = keyPressed & 0xFF; // Check whether keyboard should be scanned if (via2PortBValue == 0) { // If port b is 0 then the vic is asking whether any keys are pressed on the keyboard this->memory->silentWriteWord(this->PORTA, keyPressed == 0 ? 0xFF : row); this->memory->silentWriteWord(this->PORTAMIRROR, keyPressed == 0 ? 0xFF : row); } else { // Return keyboard row depending on column state this->memory->silentWriteWord(this->PORTA, (via2PortBValue == column ? (row == 0 ? 0xFF : row) : 0xFF)); this->memory->silentWriteWord(this->PORTAMIRROR, (via2PortBValue == column ? (row == 0 ? 0xFF : row) : 0xFF)); } if ((via2PortBValue == 0xF7) && shiftPressed) { // Return row of shift key this->memory->silentWriteWord(this->PORTA, 0xFD & (keyPressed == 0 ? 0xFF : (column == 0xF7 ? row : 0xFF))); this->memory->silentWriteWord(this->PORTAMIRROR, 0xFD & (keyPressed == 0 ? 0xFF : (column == 0xF7 ? row : 0xFF))); } else if (via2PortBValue == 0xDF && cbmPressed) { // Return row of cbm key this->memory->silentWriteWord(this->PORTA, 0xFE & (keyPressed == 0 ? 0xFF : (column == 0xDF ? row : 0xFF))); this->memory->silentWriteWord(this->PORTAMIRROR, 0xFE & (keyPressed == 0 ? 0xFF : (column == 0xDF ? row : 0xFF))); } // Handle joystick input this->memory->silentWriteWord(via1PORTA, 0xFF); this->memory->silentWriteWord(via1PORTAMIRROR, 0xFF); // If this bit is input, set it to default value, else leave it as it is so it won't mess up keyboard input if (!(this->memory->readWord(via2PortBDDR) & 0x80)) { this->memory->silentWriteWord(PORTB, this->memory->silentReadWord(PORTB) | 0x80); } if (joyStick[Vic20JoyStickButton::Fire]) { this->memory->silentWriteWord(via1PORTA, this->memory->silentReadWord(via1PORTA) & ~0x20); this->memory->silentWriteWord(via1PORTAMIRROR, this->memory->silentReadWord(via1PORTA) & ~0x20); } if (joyStick[Vic20JoyStickButton::Up]) { this->memory->silentWriteWord(via1PORTA, this->memory->silentReadWord(via1PORTA) & ~0x4); this->memory->silentWriteWord(via1PORTAMIRROR, this->memory->silentReadWord(via1PORTA) & ~0x4); } if (joyStick[Vic20JoyStickButton::Down]) { this->memory->silentWriteWord(via1PORTA, this->memory->silentReadWord(via1PORTA) & ~0x8); this->memory->silentWriteWord(via1PORTAMIRROR, this->memory->silentReadWord(via1PORTA) & ~0x8); } if (joyStick[Vic20JoyStickButton::Left]) { this->memory->silentWriteWord(via1PORTA, this->memory->silentReadWord(via1PORTA) & ~0x10); this->memory->silentWriteWord(via1PORTAMIRROR, this->memory->silentReadWord(via1PORTA) & ~0x10); } if (joyStick[Vic20JoyStickButton::Right]) { this->memory->silentWriteWord(PORTB, this->memory->silentReadWord(0x9120) & ~0x80); } } void MOS6522::tickTimers() { // Grab values of timer related registers uint8_t interruptEnable = this->memory->readWord(this->irqEnableAddress); uint8_t interruptFlags = this->memory->readWord(this->irqFlagsAddress); uint8_t auxControl = this->memory->readWord(this->auxControlAddress); // Get timer values uint16_t timer1 = this->memory->silentReadDWord(this->timer1DAddress); uint16_t timer2 = this->memory->silentReadDWord(this->timer2DAddress); // If timer is active, decrement it if (timer1 > 0) this->memory->silentWriteDWord(this->timer1DAddress, --timer1); if (timer2 > 0 && this->memory->silentReadWord(this->timer2HighByteLatch) != 0) { // Decrement t2 this->memory->silentWriteDWord(this->timer2DAddress, --timer2); } // If timeout if (timer1 == 0) { // Set interrupt flag this->memory->silentWriteWord(this->irqFlagsAddress, interruptFlags | 0x40); interruptFlags = this->memory->readWord(this->irqFlagsAddress); } if (timer2 == 0) { // Reset high byte latch if (this->memory->readWord(this->timer2HighByteLatch) != 0) { this->memory->silentWriteDWord(this->timer2DAddress, this->memory->silentReadDWord(this->timer2LowByteLatch)); this->memory->silentWriteDWord(this->timer2HighByteLatch, 0); // Set interrupt flag this->memory->silentWriteWord(this->irqFlagsAddress, interruptFlags | 0x20); interruptFlags = this->memory->readWord(this->irqFlagsAddress); } } // Check if an interrupt request exists in the system if (interruptFlags & interruptEnable & 0x7F) { // Send an interrupt request to the cpu if (mos6502->interrupt()) { // Post interrupt operation if (timer1 == 0) { // Determine what to do with timer based on auxiliary control register if (auxControl & 0x40) { // Continuous interrupt this->memory->silentWriteDWord(this->timer1DAddress, this->memory->silentReadDWord(this->timer1LowByteLatch)); } // Reset interrupt flag this->memory->silentWriteWord(irqFlagsAddress, this->memory->silentReadWord(irqFlagsAddress) & ~0x40); } if (timer2 == 0) { // Reset interrupt flag this->memory->silentWriteWord(irqFlagsAddress, this->memory->silentReadWord(irqFlagsAddress) & ~0x20); } } } } <|endoftext|>
<commit_before>/// @file AesopWorldState.cpp /// @brief Implementation of WorldState class as defined in Aesop.h #include <algorithm> #include "Aesop.h" namespace ae { /// @class WorldState /// /// This class represents a set of knowledge (facts, or predicates) about /// the state of the world that we are planning within. A WorldState can be /// used by individual characters as a representation of their knowledge, /// but is also used internally in planning. WorldState::WorldState() { mHash = 0; } WorldState::~WorldState() { } bool WorldState::predicateSet(PName pred) const { worldrep::const_iterator it = mState.find(pred); return it == mState.end(); } PVal WorldState::getPredicate(PName pred) const { worldrep::const_iterator it = mState.find(pred); if(it == mState.end()) return 0; return getPVal(it); } void WorldState::setPredicate(PName pred, PVal val) { _setPredicate(pred, val); updateHash(); } void WorldState::_setPredicate(PName pred, PVal val) { mState[pred] = val; } void WorldState::unsetPredicate(PName pred) { _unsetPredicate(pred); updateHash(); } void WorldState::_unsetPredicate(PName pred) { worldrep::iterator it = mState.find(pred); if(it != mState.end()) mState.erase(it); } /// This method is responsible for setting the parameters in the paramlist /// that are required to be a certain value in order to match this state. void WorldState::actionGetParams(const Action *ac, paramlist &params) const { params.resize(ac->getNumParams()); // Each parameter that sets a predicate must have the correct value. const actionparams &spl = ac->getSetParams(); actionparams::const_iterator sit; for(sit = spl.begin(); sit != spl.end(); sit++) params[sit->second] = getPredicate(sit->first); // Each predicate required and not set must have the correct value. const actionparams &rpl = ac->getRequiredParams(); actionparams::const_iterator rit; for(rit = rpl.begin(); rit != rpl.end(); rit++) { const worldrep &set = ac->getSet(); if(set.find(rit->first) == set.end() && spl.find(rit->first) == spl.end()) params[rit->second] = getPredicate(rit->first); } } /// For a 'pre-match' to be valid, we compare the Action's required /// predicates to the values in the current world state. All values must /// match for the Action to be valid. bool WorldState::actionPreMatch(const Action *ac, const paramlist *params) const { // Check static predicates. const worldrep &awr = ac->getRequired(); worldrep::const_iterator it; for(it = awr.begin(); it != awr.end(); it++) { // If we don't have a mapping for this predicate then we fail. if(!predicateSet(getPName(it))) return false; // If the predicate isn't set to the right value, we fail. if(getPredicate(getPName(it)) != getPVal(it)) return false; } // Check parameter predicates. if(params && params->size() == ac->getNumParams()) { const actionparams &apl = ac->getRequiredParams(); actionparams::const_iterator pit; for(pit = apl.begin(); pit != apl.end(); pit++) { if(!predicateSet(pit->first)) return false; // If the predicate is set to the wrong value, fail. if(getPredicate(pit->first) != params->at(pit->second)) return false; } } return true; } /// This method compares a desired world state with an action's results. The /// comparison returns true if each predicate in our current state is either /// set by the Action, or required by it and not changed. /// In this method, params is an output argument. The method fills in the /// values of each parameter required for the Action to result in the given /// world state. /// @todo Review complexity of this method. bool WorldState::actionPostMatch(const Action *ac, const paramlist *params) const { worldrep::const_iterator it; worldrep::const_iterator ait; worldrep::const_iterator rit; actionparams::const_iterator plit; const worldrep &set = ac->getSet(); const worldrep &req = ac->getRequired(); const actionparams &preq = ac->getRequiredParams(); const actionparams &pset = ac->getSetParams(); unsigned int matched = 0; // Check each of our predicates. for(it = mState.begin(); it != mState.end(); it++) { // Does this Action set this predicate to some value? ait = set.find(getPName(it)); if(ait != set.end()) { // Action touches this predicate; check value is correct. if(getPVal(ait) == getPredicate(getPName(ait))) { matched++; continue; } else return false; } else { // Action does not set this predicate to a constant. Check params. plit = pset.find(getPName(it)); if(plit != pset.end()) { // Check if value matches. if(params && params->size() == ac->getNumParams() && params->at(plit->second) == getPredicate(plit->first)) { matched++; continue; } else return false; } else { // Predicate is not set anywhere. Is it required? rit = req.find(getPName(it)); if(rit != req.end()) { // Check to see if is is required to be the right value. if(rit->second == getPredicate(rit->first)) { matched++; continue; } else return false; } else { // Check to see if required to a parameter. plit = preq.find(getPName(it)); if(plit != preq.end()) { if(params && params->size() == ac->getNumParams() && params->at(plit->second) == getPredicate(plit->first)) { matched++; continue; } else return false; } } } } } return matched != 0; } /// Apply an Action to the current world state. The Action's effects are /// applied to the current set of predicates. void WorldState::applyActionForward(const Action *ac, const paramlist *params) { worldrep::const_iterator sit; pnamelist::const_iterator pit; // Predicates set by this Action. const worldrep &st = ac->getSet(); for(sit = st.begin(); sit != st.end(); sit++) _setPredicate(getPName(sit), getPVal(sit)); // Predicates unset. const pnamelist &pr = ac->getCleared(); for(pit = pr.begin(); pit != pr.end(); pit++) _unsetPredicate(*pit); // Predicate set to a parameter. if(params && params->size() == ac->getNumParams()) { const actionparams &pl = ac->getSetParams(); actionparams::const_iterator plit; for(plit = pl.begin(); plit != pl.end(); plit++) _setPredicate(plit->first, params->at(plit->second)); } updateHash(); } /// This method applies an Action to a WorldState in reverse. In effect, /// it determines the state of the world required that when this Action is /// applied to it, the result is the current state. /// This involves making sure that the new state's predicates match the /// Action's prerequisites, and clearing any predicates that the Action /// sets. void WorldState::applyActionReverse(const Action *ac, const paramlist *params) { worldrep::const_iterator sit; pnamelist::const_iterator pit; actionparams::const_iterator plit; // Predicates that are touched by the Action are unset. const worldrep &set = ac->getSet(); for(sit = set.begin(); sit != set.end(); sit++) _unsetPredicate(getPName(sit)); const pnamelist &pr = ac->getCleared(); for(pit = pr.begin(); pit != pr.end(); pit++) _unsetPredicate(*pit); if(params && params->size() == ac->getNumParams()) { const actionparams &pl = ac->getSetParams(); for(plit = pl.begin(); plit != pl.end(); plit++) _unsetPredicate(plit->first); } // Predicates that must be some value. This may re-set some of the // predicates that were unset above. const worldrep &req = ac->getRequired(); for(sit = req.begin(); sit != req.end(); sit++) _setPredicate(getPName(sit), getPVal(sit)); if(params && params->size() == ac->getNumParams()) { const actionparams &pl = ac->getRequiredParams(); for(plit = pl.begin(); plit != pl.end(); plit++) _setPredicate(plit->first, params->at(plit->second)); } updateHash(); } /// This hash method sums the string hashes of all the predicate names in /// this state, XORing certain bits based on the values of each predicate. /// @todo Is there a better hash func to use? Should do some unit testing. void WorldState::updateHash() { mHash = 0; worldrep::const_iterator it; for(it = mState.begin(); it != mState.end(); it++) { unsigned int l = getPName(it).length(); while(l) mHash = 31 * mHash + getPName(it)[--l]; mHash ^= getPVal(it) << getPName(it).length() % (sizeof(unsigned int) - sizeof(PVal)); } } /// The difference score between two WorldStates is equal to the number of /// predicates which they both have defined, but to different values. /// Predicates that are not defined in one state, or are flagged as unset /// in either, are not considered. unsigned int WorldState::comp(const WorldState &ws1, const WorldState &ws2) { int score = 0; // Iterators run from lowest to highest key values. worldrep::const_iterator p1 = ws1.mState.begin(); worldrep::const_iterator p2 = ws2.mState.begin(); while(p1 != ws1.mState.end() || p2 != ws2.mState.end()) { // One state may have run out of keys. if(p1 == ws1.mState.end()) { score++; p2++; continue; } if(p2 == ws2.mState.end()) { score++; p1++; continue; } // Compare names of predicates (keys). int cmp = getPName(p1).compare(getPName(p2)); if(cmp == 0) { // Names are equal. Check for different values. if(getPVal(p1) != getPVal(p2)) score++; p1++; p2++; } else if(cmp > 0) { // Key 1 is greater. score++; p2++; } else // if(cmp < 0) { // Key 2 is greater. score++; p1++; } } return score; } }; <commit_msg>Fixed a bug in WorldState::predicateSet. Not sure how that ended up in there...<commit_after>/// @file AesopWorldState.cpp /// @brief Implementation of WorldState class as defined in Aesop.h #include <algorithm> #include "Aesop.h" namespace ae { /// @class WorldState /// /// This class represents a set of knowledge (facts, or predicates) about /// the state of the world that we are planning within. A WorldState can be /// used by individual characters as a representation of their knowledge, /// but is also used internally in planning. WorldState::WorldState() { mHash = 0; } WorldState::~WorldState() { } bool WorldState::predicateSet(PName pred) const { worldrep::const_iterator it = mState.find(pred); return it != mState.end(); } PVal WorldState::getPredicate(PName pred) const { worldrep::const_iterator it = mState.find(pred); if(it == mState.end()) return 0; return getPVal(it); } void WorldState::setPredicate(PName pred, PVal val) { _setPredicate(pred, val); updateHash(); } void WorldState::_setPredicate(PName pred, PVal val) { mState[pred] = val; } void WorldState::unsetPredicate(PName pred) { _unsetPredicate(pred); updateHash(); } void WorldState::_unsetPredicate(PName pred) { worldrep::iterator it = mState.find(pred); if(it != mState.end()) mState.erase(it); } /// This method is responsible for setting the parameters in the paramlist /// that are required to be a certain value in order to match this state. void WorldState::actionGetParams(const Action *ac, paramlist &params) const { params.resize(ac->getNumParams()); // Each parameter that sets a predicate must have the correct value. const actionparams &spl = ac->getSetParams(); actionparams::const_iterator sit; for(sit = spl.begin(); sit != spl.end(); sit++) params[sit->second] = getPredicate(sit->first); // Each predicate required and not set must have the correct value. const actionparams &rpl = ac->getRequiredParams(); actionparams::const_iterator rit; for(rit = rpl.begin(); rit != rpl.end(); rit++) { const worldrep &set = ac->getSet(); if(set.find(rit->first) == set.end() && spl.find(rit->first) == spl.end()) params[rit->second] = getPredicate(rit->first); } } /// For a 'pre-match' to be valid, we compare the Action's required /// predicates to the values in the current world state. All values must /// match for the Action to be valid. bool WorldState::actionPreMatch(const Action *ac, const paramlist *params) const { // Check static predicates. const worldrep &awr = ac->getRequired(); worldrep::const_iterator it; for(it = awr.begin(); it != awr.end(); it++) { // If we don't have a mapping for this predicate then we fail. if(!predicateSet(getPName(it))) return false; // If the predicate isn't set to the right value, we fail. if(getPredicate(getPName(it)) != getPVal(it)) return false; } // Check parameter predicates. if(params && params->size() == ac->getNumParams()) { const actionparams &apl = ac->getRequiredParams(); actionparams::const_iterator pit; for(pit = apl.begin(); pit != apl.end(); pit++) { if(!predicateSet(pit->first)) return false; // If the predicate is set to the wrong value, fail. if(getPredicate(pit->first) != params->at(pit->second)) return false; } } return true; } /// This method compares a desired world state with an action's results. The /// comparison returns true if each predicate in our current state is either /// set by the Action, or required by it and not changed. /// In this method, params is an output argument. The method fills in the /// values of each parameter required for the Action to result in the given /// world state. /// @todo Review complexity of this method. bool WorldState::actionPostMatch(const Action *ac, const paramlist *params) const { worldrep::const_iterator it; worldrep::const_iterator ait; worldrep::const_iterator rit; actionparams::const_iterator plit; const worldrep &set = ac->getSet(); const worldrep &req = ac->getRequired(); const actionparams &preq = ac->getRequiredParams(); const actionparams &pset = ac->getSetParams(); unsigned int matched = 0; // Check each of our predicates. for(it = mState.begin(); it != mState.end(); it++) { // Does this Action set this predicate to some value? ait = set.find(getPName(it)); if(ait != set.end()) { // Action touches this predicate; check value is correct. if(getPVal(ait) == getPredicate(getPName(ait))) { matched++; continue; } else return false; } else { // Action does not set this predicate to a constant. Check params. plit = pset.find(getPName(it)); if(plit != pset.end()) { // Check if value matches. if(params && params->size() == ac->getNumParams() && params->at(plit->second) == getPredicate(plit->first)) { matched++; continue; } else return false; } else { // Predicate is not set anywhere. Is it required? rit = req.find(getPName(it)); if(rit != req.end()) { // Check to see if is is required to be the right value. if(rit->second == getPredicate(rit->first)) { matched++; continue; } else return false; } else { // Check to see if required to a parameter. plit = preq.find(getPName(it)); if(plit != preq.end()) { if(params && params->size() == ac->getNumParams() && params->at(plit->second) == getPredicate(plit->first)) { matched++; continue; } else return false; } } } } } return matched != 0; } /// Apply an Action to the current world state. The Action's effects are /// applied to the current set of predicates. void WorldState::applyActionForward(const Action *ac, const paramlist *params) { worldrep::const_iterator sit; pnamelist::const_iterator pit; // Predicates set by this Action. const worldrep &st = ac->getSet(); for(sit = st.begin(); sit != st.end(); sit++) _setPredicate(getPName(sit), getPVal(sit)); // Predicates unset. const pnamelist &pr = ac->getCleared(); for(pit = pr.begin(); pit != pr.end(); pit++) _unsetPredicate(*pit); // Predicate set to a parameter. if(params && params->size() == ac->getNumParams()) { const actionparams &pl = ac->getSetParams(); actionparams::const_iterator plit; for(plit = pl.begin(); plit != pl.end(); plit++) _setPredicate(plit->first, params->at(plit->second)); } updateHash(); } /// This method applies an Action to a WorldState in reverse. In effect, /// it determines the state of the world required that when this Action is /// applied to it, the result is the current state. /// This involves making sure that the new state's predicates match the /// Action's prerequisites, and clearing any predicates that the Action /// sets. void WorldState::applyActionReverse(const Action *ac, const paramlist *params) { worldrep::const_iterator sit; pnamelist::const_iterator pit; actionparams::const_iterator plit; // Predicates that are touched by the Action are unset. const worldrep &set = ac->getSet(); for(sit = set.begin(); sit != set.end(); sit++) _unsetPredicate(getPName(sit)); const pnamelist &pr = ac->getCleared(); for(pit = pr.begin(); pit != pr.end(); pit++) _unsetPredicate(*pit); if(params && params->size() == ac->getNumParams()) { const actionparams &pl = ac->getSetParams(); for(plit = pl.begin(); plit != pl.end(); plit++) _unsetPredicate(plit->first); } // Predicates that must be some value. This may re-set some of the // predicates that were unset above. const worldrep &req = ac->getRequired(); for(sit = req.begin(); sit != req.end(); sit++) _setPredicate(getPName(sit), getPVal(sit)); if(params && params->size() == ac->getNumParams()) { const actionparams &pl = ac->getRequiredParams(); for(plit = pl.begin(); plit != pl.end(); plit++) _setPredicate(plit->first, params->at(plit->second)); } updateHash(); } /// This hash method sums the string hashes of all the predicate names in /// this state, XORing certain bits based on the values of each predicate. /// @todo Is there a better hash func to use? Should do some unit testing. void WorldState::updateHash() { mHash = 0; worldrep::const_iterator it; for(it = mState.begin(); it != mState.end(); it++) { unsigned int l = getPName(it).length(); while(l) mHash = 31 * mHash + getPName(it)[--l]; mHash ^= getPVal(it) << getPName(it).length() % (sizeof(unsigned int) - sizeof(PVal)); } } /// The difference score between two WorldStates is equal to the number of /// predicates which they both have defined, but to different values. /// Predicates that are not defined in one state, or are flagged as unset /// in either, are not considered. unsigned int WorldState::comp(const WorldState &ws1, const WorldState &ws2) { int score = 0; // Iterators run from lowest to highest key values. worldrep::const_iterator p1 = ws1.mState.begin(); worldrep::const_iterator p2 = ws2.mState.begin(); while(p1 != ws1.mState.end() || p2 != ws2.mState.end()) { // One state may have run out of keys. if(p1 == ws1.mState.end()) { score++; p2++; continue; } if(p2 == ws2.mState.end()) { score++; p1++; continue; } // Compare names of predicates (keys). int cmp = getPName(p1).compare(getPName(p2)); if(cmp == 0) { // Names are equal. Check for different values. if(getPVal(p1) != getPVal(p2)) score++; p1++; p2++; } else if(cmp > 0) { // Key 1 is greater. score++; p2++; } else // if(cmp < 0) { // Key 2 is greater. score++; p1++; } } return score; } }; <|endoftext|>
<commit_before>#include "ConnectionNonBlocking.h" #include <iostream> namespace ThorsAnvil { namespace NisseSQL { class MySQLConnectionHandler: public ThorsAnvil::Nisse::NisseHandler { CoRoutine worker; public: MySQLConnectionHandler(ThorsAnvil::Nisse::NisseService& service, ConnectionNonBlocking& connection, ThorsAnvil::MySQL::MySQLStream& stream, std::string const& username, std::string const& password, std::string const& database, ThorsAnvil::SQL::Options const& options) : NisseHandler(service, stream.getSocketId(), EV_READ | EV_WRITE) , worker([&connection, &stream, &username, &password, &database, &options](Yield& yield) { yield(EV_WRITE); stream.setYield([&yield](){yield(EV_READ);}, [&yield](){yield(EV_WRITE);}); connection.doConectToServer(username, password, database, options); stream.setYield([](){}, [](){}); }) { } virtual short eventActivate(ThorsAnvil::Nisse::LibSocketId /*sockId*/, short /*eventType*/) { if (!worker()) { dropHandler(); return 0; } return worker.get(); } }; } } using namespace ThorsAnvil::NisseSQL; ConnectionNonBlocking::ConnectionNonBlocking( ThorsAnvil::MySQL::MySQLStream& stream, std::string const& username, std::string const& password, std::string const& database, ThorsAnvil::SQL::Options const& options, ThorsAnvil::MySQL::ConectReader& packageReader, ThorsAnvil::MySQL::ConectWriter& packageWriter ) : Connection(username, password, database, options, packageReader, packageWriter) , stream(stream) { auto& service = ThorsAnvil::Nisse::NisseService::getCurrentHandler(); service.transferHandler<MySQLConnectionHandler>(*this, stream, username, password, database, options); } void ConnectionNonBlocking::doConectToServer( std::string const& username, std::string const& password, std::string const& database, ThorsAnvil::SQL::Options const& options ) { conectToServer(username, password, database, options); } <commit_msg>Remove redundant code<commit_after>#include "ConnectionNonBlocking.h" #include <iostream> namespace ThorsAnvil { namespace NisseSQL { class MySQLConnectionHandler: public ThorsAnvil::Nisse::NisseHandler { CoRoutine worker; public: MySQLConnectionHandler(ThorsAnvil::Nisse::NisseService& service, ConnectionNonBlocking& connection, ThorsAnvil::MySQL::MySQLStream& stream, std::string const& username, std::string const& password, std::string const& database, ThorsAnvil::SQL::Options const& options) : NisseHandler(service, stream.getSocketId(), EV_READ | EV_WRITE) , worker([&connection, &stream, &username, &password, &database, &options](Yield& yield) { yield(EV_WRITE); stream.setYield([&yield](){yield(EV_READ);}, [&yield](){yield(EV_WRITE);}); connection.doConectToServer(username, password, database, options); stream.setYield([](){}, [](){}); }) { } virtual short eventActivate(ThorsAnvil::Nisse::LibSocketId /*sockId*/, short /*eventType*/) { if (!worker()) { dropHandler(); return 0; } return worker.get(); } }; } } using namespace ThorsAnvil::NisseSQL; ConnectionNonBlocking::ConnectionNonBlocking( ThorsAnvil::MySQL::MySQLStream& stream, std::string const& username, std::string const& password, std::string const& database, ThorsAnvil::SQL::Options const& options, ThorsAnvil::MySQL::ConectReader& packageReader, ThorsAnvil::MySQL::ConectWriter& packageWriter ) : Connection(username, password, database, options, packageReader, packageWriter) { auto& service = ThorsAnvil::Nisse::NisseService::getCurrentHandler(); service.transferHandler<MySQLConnectionHandler>(*this, stream, username, password, database, options); } void ConnectionNonBlocking::doConectToServer( std::string const& username, std::string const& password, std::string const& database, ThorsAnvil::SQL::Options const& options ) { conectToServer(username, password, database, options); } <|endoftext|>
<commit_before>#include "QOsgViewer.h" #include <osgGA/TrackballManipulator> #include <osgViewer/ViewerEventHandlers> #include <osgDB/ReadFile> #include "xo/system/log.h" #include "qevent.h" #include "osg/MatrixTransform" #include "xo/geometry/quat.h" #include "osg/Material" #include "osg/PositionAttitudeTransform" #include "osgUtil/LineSegmentIntersector" // class for routing GUI events to QOsgViewer // This is needed because QOsgViewer can't derive from GUIEventHandler directly // because both are derived from osg::Object (basically, because of bad design) class QOsgEventHandler : public osgGA::GUIEventHandler { public: QOsgEventHandler( QOsgViewer& viewer ) : viewer_( viewer ) {} virtual bool handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa ) { return viewer_.handle( ea, aa ); } private: QOsgViewer& viewer_; }; QOsgViewer::QOsgViewer( QWidget* parent /*= 0*/, Qt::WindowFlags f /*= 0*/, osgViewer::ViewerBase::ThreadingModel threadingModel/*=osgViewer::CompositeViewer::SingleThreaded*/ ) : QWidget( parent, f ), frame_count_( 0 ), capture_handler_( nullptr ), scene_light_offset_( -2, 8, 3 ), current_frame_time_( -1 ), mouse_drag_count_( 0 ), mouse_hover_allowed_( false ), mouse_hover_duration_( xo::time_from_milliseconds( 100 ) ) { setThreadingModel( threadingModel ); // disable the default setting of viewer.done() by pressing Escape. setKeyEventSetsDone( 0 ); // setup viewer grid view_widget_ = addViewWidget( createGraphicsWindow( 0, 0, 100, 100, "", true ) ); auto* grid = new QGridLayout; grid->addWidget( view_widget_ ); setLayout( grid ); grid->setMargin( 1 ); // start timer that checks for updates in the camera manager connect( &timer_, SIGNAL( timeout() ), this, SLOT( timerUpdate() ) ); startTimer(); // this allows us to detect events, and update the viewer accordingly // overriding mouseMoveEvent, etc. does not work, because they are send directly to GLWidget //QCoreApplication::instance()->installEventFilter( this ); } osgQt::GLWidget* QOsgViewer::addViewWidget( osgQt::GraphicsWindowQt* gw ) { view_ = new osgViewer::View; addView( view_ ); osg::Camera* cam = view_->getCamera(); cam->setGraphicsContext( gw ); const osg::GraphicsContext::Traits* traits = gw->getTraits(); cam->setClearColor( osg::Vec4( 0.55, 0.55, 0.55, 1.0 ) ); cam->setViewport( new osg::Viewport( 0, 0, traits->width, traits->height ) ); cam->setProjectionMatrixAsPerspective( 30.0f, static_cast<double>( traits->width ) / static_cast<double>( traits->height ), 1.0f, 10000.0f ); // add event handlers view_->addEventHandler( new osgViewer::StatsHandler ); view_->addEventHandler( new QOsgEventHandler( *this ) ); // disable lighting by default view_->setLightingMode( osg::View::NO_LIGHT ); // setup camera manipulator gw->setTouchEventsEnabled( true ); camera_man_ = new vis::osg_camera_man(); camera_man_->setVerticalAxisFixed( false ); view_->setCameraManipulator( camera_man_ ); return gw->getGLWidget(); } osgQt::GraphicsWindowQt* QOsgViewer::createGraphicsWindow( int x, int y, int w, int h, const std::string& name/*=""*/, bool windowDecoration/*=false */ ) { osg::DisplaySettings* ds = osg::DisplaySettings::instance().get(); ds->setNumMultiSamples( 2 ); osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->windowName = name; traits->windowDecoration = windowDecoration; traits->x = x; traits->y = y; traits->width = w; traits->height = h; traits->doubleBuffer = true; traits->alpha = ds->getMinimumNumAlphaBits(); traits->stencil = ds->getMinimumNumStencilBits(); traits->sampleBuffers = ds->getMultiSamples(); traits->samples = ds->getNumMultiSamples(); width_ = w; height_ = h; return new osgQt::GraphicsWindowQt( traits.get() ); } void QOsgViewer::paintEvent( QPaintEvent* event ) { // prevent capturing duplicate frames if ( isCapturing() && current_frame_time_ == last_drawn_frame_time_ ) return; // this frame was already captured, skip ++frame_count_; // advance and handle camera events advance(); eventTraversal(); // update camera light position updateLightPos(); // update and render updateTraversal(); renderingTraversals(); last_drawn_frame_time_ = current_frame_time_; } bool QOsgViewer::event( QEvent* e ) { if ( e->type() == QEvent::ToolTip ) emit tooltip(); return QWidget::event( e ); } void QOsgViewer::setScene( osg::Group* s ) { scene_ = s; for ( size_t i = 0; i < getNumViews(); ++i ) getView( i )->setSceneData( s ); // init light scene_light_ = new osg::Light; scene_light_->setLightNum( 0 ); scene_light_->setPosition( osg::Vec4f( scene_light_offset_.x, scene_light_offset_.y, scene_light_offset_.z, 1 ) ); scene_light_->setDiffuse( osg::Vec4( 1, 1, 1, 1 ) ); scene_light_->setSpecular( osg::Vec4( 1, 1, 1, 1 ) ); scene_light_->setAmbient( osg::Vec4( 1, 1, 1, 1 ) ); auto light_source = new osg::LightSource; light_source->setLight( scene_light_ ); light_source->setLocalStateSetModes( osg::StateAttribute::ON ); light_source->setReferenceFrame( osg::LightSource::RELATIVE_RF ); // directly add the light to the parent node s->addChild( light_source ); s->getOrCreateStateSet()->setMode( GL_LIGHT0, osg::StateAttribute::ON ); scene_light_->setConstantAttenuation( 1.0f ); } void QOsgViewer::createHud( const xo::path& file ) { hud_node_ = new osg::PositionAttitudeTransform; osg::ref_ptr<osg::Image> img = osgDB::readImageFile( file.str() ); xo_assert( img.valid() ); auto width = osg::Vec3f( hud_size, 0, 0 ); auto height = osg::Vec3f( 0, hud_size, 0 ); osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D; texture->setImage( img ); texture->setWrap( osg::Texture::WRAP_S, osg::Texture::REPEAT ); texture->setWrap( osg::Texture::WRAP_T, osg::Texture::REPEAT ); osg::ref_ptr<osg::Geometry> geom = osg::createTexturedQuadGeometry( width * -0.5f - height * 0.5f, width, height, 0, 0, 1.0f, 1.0f ); geom->getOrCreateStateSet()->setTextureAttributeAndModes( 0, texture.get() ); geom->getOrCreateStateSet()->setMode( GL_DEPTH_TEST, osg::StateAttribute::OFF ); geom->getOrCreateStateSet()->setMode( GL_BLEND, osg::StateAttribute::ON ); osg::ref_ptr<osg::Geode> geode = new osg::Geode(); geode->addDrawable( geom ); hud_node_->addChild( geode ); hud_node_->setReferenceFrame( osg::Transform::ABSOLUTE_RF ); view_->getCamera()->addChild( hud_node_ ); updateHudPos(); } void QOsgViewer::updateHudPos() { if ( hud_node_ ) { double fovy, aspect, nearplane, farplane; view_->getCamera()->getProjectionMatrixAsPerspective( fovy, aspect, nearplane, farplane ); auto hh = tan( xo::degreed( fovy / 2 ) ); auto hw = tan( atan( hh * aspect ) ); //xo::log::info( "Updating HUD position to ", hw - 0.55f * hud_size, ", ", -hh + 0.55f * hud_size, "; aspect ratio = ", aspect ); hud_node_->setPosition( osg::Vec3( hw - 0.55f * hud_size, -hh + 0.55f * hud_size, -1 ) ); } } void QOsgViewer::updateLightPos() { auto center = camera_man_->getCenter(); auto ori = xo::quat_from_axis_angle( xo::vec3f::unit_y(), camera_man_->getYaw() ); auto v = ori * scene_light_offset_; auto p = center + osg::Vec3d( v.x, v.y, v.z ); scene_light_->setPosition( osg::Vec4( p, 1 ) ); } void QOsgViewer::viewerInit() { updateHudPos(); } void QOsgViewer::setClearColor( const osg::Vec4& col ) { view_->getCamera()->setClearColor( col ); } void QOsgViewer::moveCamera( const osg::Vec3d& delta_pos ) { camera_man_->setCenter( camera_man_->getCenter() + delta_pos ); } bool QOsgViewer::handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa ) { switch ( ea.getEventType() ) { case osgGA::GUIEventAdapter::RESIZE: width_ = ea.getWindowWidth(); height_ = ea.getWindowHeight(); xo::log::trace( "Viewer resized to ", width_, "x", height_ ); updateHudPos(); return true; case osgGA::GUIEventAdapter::PUSH: if ( ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON ) { updateIntersections( ea ); emit pressed(); } mouse_drag_count_ = 0; mouse_hover_allowed_ = false; break; case osgGA::GUIEventAdapter::MOVE: mouse_hover_timer_.restart(); mouse_hover_allowed_ = true; break; case osgGA::GUIEventAdapter::DRAG: ++mouse_drag_count_; mouse_hover_allowed_ = false; break; case osgGA::GUIEventAdapter::RELEASE: if ( mouse_drag_count_ <= 2 && ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON ) { updateIntersections( ea ); emit clicked(); return true; } break; default: break; } if ( mouse_hover_allowed_ && mouse_hover_timer_() >= mouse_hover_duration_ ) { mouse_hover_allowed_ = false; updateIntersections( ea ); emit hover(); } return false; } void QOsgViewer::updateIntersections( const osgGA::GUIEventAdapter& ea ) { view_->computeIntersections( ea, intersections_ ); } osg::Node* QOsgViewer::getTopNamedIntersectionNode( const std::string& skipName ) const { for ( auto& is : intersections_ ) { for ( auto it = is.nodePath.rbegin(); it != is.nodePath.rend(); it++ ) { const auto& name = ( *it )->getName(); if ( name.empty() ) continue; else if ( name != skipName ) return *it; else break; } } return nullptr; } void QOsgViewer::enableObjectCache( bool enable ) { getOrCreateOptions()->setObjectCacheHint( enable ? osgDB::Options::CACHE_ALL : osgDB::Options::CACHE_ARCHIVES ); } void QOsgViewer::startCapture( const std::string& filename ) { // create capture handler xo::log::info( "Started capturing video to ", filename ); capture_handler_ = new osgViewer::ScreenCaptureHandler( new osgViewer::ScreenCaptureHandler::WriteToFile( filename, "png", osgViewer::ScreenCaptureHandler::WriteToFile::SEQUENTIAL_NUMBER ), -1 ); view_->addEventHandler( capture_handler_ ); capture_handler_->startCapture(); } void QOsgViewer::stopCapture() { last_drawn_frame_time_ = xo::constants<double>::lowest(); if ( capture_handler_ ) { xo::log::info( "Video capture stopped" ); capture_handler_->stopCapture(); capture_handler_ = nullptr; } } void QOsgViewer::captureCurrentFrame( const std::string& filename ) { stopCapture(); capture_handler_ = new osgViewer::ScreenCaptureHandler( new osgViewer::ScreenCaptureHandler::WriteToFile( filename, "png", osgViewer::ScreenCaptureHandler::WriteToFile::OVERWRITE ) ); view_->addEventHandler( capture_handler_ ); capture_handler_->startCapture(); // schedule and handle paint event // NOTE: calling frame() directly messes up the event handler repaint(); QApplication::processEvents(); capture_handler_->stopCapture(); capture_handler_ = nullptr; xo::log::info( "Written image to ", filename ); } void QOsgViewer::setFrameTime( double t ) { if ( current_frame_time_ != t ) { current_frame_time_ = t; repaint(); } } void QOsgViewer::timerUpdate() { // check if update is needed eventTraversal(); camera_man_->handleKeyboardAnimation(); if ( camera_man_->hasCameraStateChanged() ) update(); } bool QOsgViewer::eventFilter( QObject* obj, QEvent* event ) { if ( obj == view_widget_ ) { // detect event inside view_widget_ if ( event->type() == QEvent::MouseMove ) update(); } return QObject::eventFilter( obj, event ); } osgDB::Options* QOsgViewer::getOrCreateOptions() { if ( !osgDB::Registry::instance()->getOptions() ) osgDB::Registry::instance()->setOptions( new osgDB::Options() ); return osgDB::Registry::instance()->getOptions(); } <commit_msg>F: QOsgViewer::moveCamera() now checks for NaN<commit_after>#include "QOsgViewer.h" #include <osgGA/TrackballManipulator> #include <osgViewer/ViewerEventHandlers> #include <osgDB/ReadFile> #include "xo/system/log.h" #include "qevent.h" #include "osg/MatrixTransform" #include "xo/geometry/quat.h" #include "osg/Material" #include "osg/PositionAttitudeTransform" #include "osgUtil/LineSegmentIntersector" // class for routing GUI events to QOsgViewer // This is needed because QOsgViewer can't derive from GUIEventHandler directly // because both are derived from osg::Object (basically, because of bad design) class QOsgEventHandler : public osgGA::GUIEventHandler { public: QOsgEventHandler( QOsgViewer& viewer ) : viewer_( viewer ) {} virtual bool handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa ) { return viewer_.handle( ea, aa ); } private: QOsgViewer& viewer_; }; QOsgViewer::QOsgViewer( QWidget* parent /*= 0*/, Qt::WindowFlags f /*= 0*/, osgViewer::ViewerBase::ThreadingModel threadingModel/*=osgViewer::CompositeViewer::SingleThreaded*/ ) : QWidget( parent, f ), frame_count_( 0 ), capture_handler_( nullptr ), scene_light_offset_( -2, 8, 3 ), current_frame_time_( -1 ), mouse_drag_count_( 0 ), mouse_hover_allowed_( false ), mouse_hover_duration_( xo::time_from_milliseconds( 100 ) ) { setThreadingModel( threadingModel ); // disable the default setting of viewer.done() by pressing Escape. setKeyEventSetsDone( 0 ); // setup viewer grid view_widget_ = addViewWidget( createGraphicsWindow( 0, 0, 100, 100, "", true ) ); auto* grid = new QGridLayout; grid->addWidget( view_widget_ ); setLayout( grid ); grid->setMargin( 1 ); // start timer that checks for updates in the camera manager connect( &timer_, SIGNAL( timeout() ), this, SLOT( timerUpdate() ) ); startTimer(); // this allows us to detect events, and update the viewer accordingly // overriding mouseMoveEvent, etc. does not work, because they are send directly to GLWidget //QCoreApplication::instance()->installEventFilter( this ); } osgQt::GLWidget* QOsgViewer::addViewWidget( osgQt::GraphicsWindowQt* gw ) { view_ = new osgViewer::View; addView( view_ ); osg::Camera* cam = view_->getCamera(); cam->setGraphicsContext( gw ); const osg::GraphicsContext::Traits* traits = gw->getTraits(); cam->setClearColor( osg::Vec4( 0.55, 0.55, 0.55, 1.0 ) ); cam->setViewport( new osg::Viewport( 0, 0, traits->width, traits->height ) ); cam->setProjectionMatrixAsPerspective( 30.0f, static_cast<double>( traits->width ) / static_cast<double>( traits->height ), 1.0f, 10000.0f ); // add event handlers view_->addEventHandler( new osgViewer::StatsHandler ); view_->addEventHandler( new QOsgEventHandler( *this ) ); // disable lighting by default view_->setLightingMode( osg::View::NO_LIGHT ); // setup camera manipulator gw->setTouchEventsEnabled( true ); camera_man_ = new vis::osg_camera_man(); camera_man_->setVerticalAxisFixed( false ); view_->setCameraManipulator( camera_man_ ); return gw->getGLWidget(); } osgQt::GraphicsWindowQt* QOsgViewer::createGraphicsWindow( int x, int y, int w, int h, const std::string& name/*=""*/, bool windowDecoration/*=false */ ) { osg::DisplaySettings* ds = osg::DisplaySettings::instance().get(); ds->setNumMultiSamples( 2 ); osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits; traits->windowName = name; traits->windowDecoration = windowDecoration; traits->x = x; traits->y = y; traits->width = w; traits->height = h; traits->doubleBuffer = true; traits->alpha = ds->getMinimumNumAlphaBits(); traits->stencil = ds->getMinimumNumStencilBits(); traits->sampleBuffers = ds->getMultiSamples(); traits->samples = ds->getNumMultiSamples(); width_ = w; height_ = h; return new osgQt::GraphicsWindowQt( traits.get() ); } void QOsgViewer::paintEvent( QPaintEvent* event ) { // prevent capturing duplicate frames if ( isCapturing() && current_frame_time_ == last_drawn_frame_time_ ) return; // this frame was already captured, skip ++frame_count_; // advance and handle camera events advance(); eventTraversal(); // update camera light position updateLightPos(); // update and render updateTraversal(); renderingTraversals(); last_drawn_frame_time_ = current_frame_time_; } bool QOsgViewer::event( QEvent* e ) { if ( e->type() == QEvent::ToolTip ) emit tooltip(); return QWidget::event( e ); } void QOsgViewer::setScene( osg::Group* s ) { scene_ = s; for ( size_t i = 0; i < getNumViews(); ++i ) getView( i )->setSceneData( s ); // init light scene_light_ = new osg::Light; scene_light_->setLightNum( 0 ); scene_light_->setPosition( osg::Vec4f( scene_light_offset_.x, scene_light_offset_.y, scene_light_offset_.z, 1 ) ); scene_light_->setDiffuse( osg::Vec4( 1, 1, 1, 1 ) ); scene_light_->setSpecular( osg::Vec4( 1, 1, 1, 1 ) ); scene_light_->setAmbient( osg::Vec4( 1, 1, 1, 1 ) ); auto light_source = new osg::LightSource; light_source->setLight( scene_light_ ); light_source->setLocalStateSetModes( osg::StateAttribute::ON ); light_source->setReferenceFrame( osg::LightSource::RELATIVE_RF ); // directly add the light to the parent node s->addChild( light_source ); s->getOrCreateStateSet()->setMode( GL_LIGHT0, osg::StateAttribute::ON ); scene_light_->setConstantAttenuation( 1.0f ); } void QOsgViewer::createHud( const xo::path& file ) { hud_node_ = new osg::PositionAttitudeTransform; osg::ref_ptr<osg::Image> img = osgDB::readImageFile( file.str() ); xo_assert( img.valid() ); auto width = osg::Vec3f( hud_size, 0, 0 ); auto height = osg::Vec3f( 0, hud_size, 0 ); osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D; texture->setImage( img ); texture->setWrap( osg::Texture::WRAP_S, osg::Texture::REPEAT ); texture->setWrap( osg::Texture::WRAP_T, osg::Texture::REPEAT ); osg::ref_ptr<osg::Geometry> geom = osg::createTexturedQuadGeometry( width * -0.5f - height * 0.5f, width, height, 0, 0, 1.0f, 1.0f ); geom->getOrCreateStateSet()->setTextureAttributeAndModes( 0, texture.get() ); geom->getOrCreateStateSet()->setMode( GL_DEPTH_TEST, osg::StateAttribute::OFF ); geom->getOrCreateStateSet()->setMode( GL_BLEND, osg::StateAttribute::ON ); osg::ref_ptr<osg::Geode> geode = new osg::Geode(); geode->addDrawable( geom ); hud_node_->addChild( geode ); hud_node_->setReferenceFrame( osg::Transform::ABSOLUTE_RF ); view_->getCamera()->addChild( hud_node_ ); updateHudPos(); } void QOsgViewer::updateHudPos() { if ( hud_node_ ) { double fovy, aspect, nearplane, farplane; view_->getCamera()->getProjectionMatrixAsPerspective( fovy, aspect, nearplane, farplane ); auto hh = tan( xo::degreed( fovy / 2 ) ); auto hw = tan( atan( hh * aspect ) ); //xo::log::info( "Updating HUD position to ", hw - 0.55f * hud_size, ", ", -hh + 0.55f * hud_size, "; aspect ratio = ", aspect ); hud_node_->setPosition( osg::Vec3( hw - 0.55f * hud_size, -hh + 0.55f * hud_size, -1 ) ); } } void QOsgViewer::updateLightPos() { auto center = camera_man_->getCenter(); auto ori = xo::quat_from_axis_angle( xo::vec3f::unit_y(), camera_man_->getYaw() ); auto v = ori * scene_light_offset_; auto p = center + osg::Vec3d( v.x, v.y, v.z ); scene_light_->setPosition( osg::Vec4( p, 1 ) ); } void QOsgViewer::viewerInit() { updateHudPos(); } void QOsgViewer::setClearColor( const osg::Vec4& col ) { view_->getCamera()->setClearColor( col ); } void QOsgViewer::moveCamera( const osg::Vec3d& delta_pos ) { if ( !delta_pos.isNaN() ) camera_man_->setCenter( camera_man_->getCenter() + delta_pos ); } bool QOsgViewer::handle( const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa ) { switch ( ea.getEventType() ) { case osgGA::GUIEventAdapter::RESIZE: width_ = ea.getWindowWidth(); height_ = ea.getWindowHeight(); xo::log::trace( "Viewer resized to ", width_, "x", height_ ); updateHudPos(); return true; case osgGA::GUIEventAdapter::PUSH: if ( ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON ) { updateIntersections( ea ); emit pressed(); } mouse_drag_count_ = 0; mouse_hover_allowed_ = false; break; case osgGA::GUIEventAdapter::MOVE: mouse_hover_timer_.restart(); mouse_hover_allowed_ = true; break; case osgGA::GUIEventAdapter::DRAG: ++mouse_drag_count_; mouse_hover_allowed_ = false; break; case osgGA::GUIEventAdapter::RELEASE: if ( mouse_drag_count_ <= 2 && ea.getButton() == osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON ) { updateIntersections( ea ); emit clicked(); return true; } break; default: break; } if ( mouse_hover_allowed_ && mouse_hover_timer_() >= mouse_hover_duration_ ) { mouse_hover_allowed_ = false; updateIntersections( ea ); emit hover(); } return false; } void QOsgViewer::updateIntersections( const osgGA::GUIEventAdapter& ea ) { view_->computeIntersections( ea, intersections_ ); } osg::Node* QOsgViewer::getTopNamedIntersectionNode( const std::string& skipName ) const { for ( auto& is : intersections_ ) { for ( auto it = is.nodePath.rbegin(); it != is.nodePath.rend(); it++ ) { const auto& name = ( *it )->getName(); if ( name.empty() ) continue; else if ( name != skipName ) return *it; else break; } } return nullptr; } void QOsgViewer::enableObjectCache( bool enable ) { getOrCreateOptions()->setObjectCacheHint( enable ? osgDB::Options::CACHE_ALL : osgDB::Options::CACHE_ARCHIVES ); } void QOsgViewer::startCapture( const std::string& filename ) { // create capture handler xo::log::info( "Started capturing video to ", filename ); capture_handler_ = new osgViewer::ScreenCaptureHandler( new osgViewer::ScreenCaptureHandler::WriteToFile( filename, "png", osgViewer::ScreenCaptureHandler::WriteToFile::SEQUENTIAL_NUMBER ), -1 ); view_->addEventHandler( capture_handler_ ); capture_handler_->startCapture(); } void QOsgViewer::stopCapture() { last_drawn_frame_time_ = xo::constants<double>::lowest(); if ( capture_handler_ ) { xo::log::info( "Video capture stopped" ); capture_handler_->stopCapture(); capture_handler_ = nullptr; } } void QOsgViewer::captureCurrentFrame( const std::string& filename ) { stopCapture(); capture_handler_ = new osgViewer::ScreenCaptureHandler( new osgViewer::ScreenCaptureHandler::WriteToFile( filename, "png", osgViewer::ScreenCaptureHandler::WriteToFile::OVERWRITE ) ); view_->addEventHandler( capture_handler_ ); capture_handler_->startCapture(); // schedule and handle paint event // NOTE: calling frame() directly messes up the event handler repaint(); QApplication::processEvents(); capture_handler_->stopCapture(); capture_handler_ = nullptr; xo::log::info( "Written image to ", filename ); } void QOsgViewer::setFrameTime( double t ) { if ( current_frame_time_ != t ) { current_frame_time_ = t; repaint(); } } void QOsgViewer::timerUpdate() { // check if update is needed eventTraversal(); camera_man_->handleKeyboardAnimation(); if ( camera_man_->hasCameraStateChanged() ) update(); } bool QOsgViewer::eventFilter( QObject* obj, QEvent* event ) { if ( obj == view_widget_ ) { // detect event inside view_widget_ if ( event->type() == QEvent::MouseMove ) update(); } return QObject::eventFilter( obj, event ); } osgDB::Options* QOsgViewer::getOrCreateOptions() { if ( !osgDB::Registry::instance()->getOptions() ) osgDB::Registry::instance()->setOptions( new osgDB::Options() ); return osgDB::Registry::instance()->getOptions(); } <|endoftext|>
<commit_before>//===- llvm/unittests/IR/DominatorTreeBatchUpdatesTest.cpp ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <random> #include "CFGBuilder.h" #include "gtest/gtest.h" #include "llvm/Analysis/PostDominators.h" #include "llvm/IR/Dominators.h" #include "llvm/Support/GenericDomTreeConstruction.h" #define DEBUG_TYPE "batch-update-tests" using namespace llvm; namespace { const auto CFGInsert = CFGBuilder::ActionKind::Insert; const auto CFGDelete = CFGBuilder::ActionKind::Delete; struct PostDomTree : PostDomTreeBase<BasicBlock> { PostDomTree(Function &F) { recalculate(F); } }; using DomUpdate = DominatorTree::UpdateType; static_assert( std::is_same<DomUpdate, PostDomTree::UpdateType>::value, "Trees differing only in IsPostDom should have the same update types"); using DomSNCA = DomTreeBuilder::SemiNCAInfo<DomTreeBuilder::BBDomTree>; using PostDomSNCA = DomTreeBuilder::SemiNCAInfo<DomTreeBuilder::BBPostDomTree>; const auto Insert = DominatorTree::Insert; const auto Delete = DominatorTree::Delete; std::vector<DomUpdate> ToDomUpdates(CFGBuilder &B, std::vector<CFGBuilder::Update> &In) { std::vector<DomUpdate> Res; Res.reserve(In.size()); for (const auto &CFGU : In) Res.push_back({CFGU.Action == CFGInsert ? Insert : Delete, B.getOrAddBlock(CFGU.Edge.From), B.getOrAddBlock(CFGU.Edge.To)}); return Res; } } // namespace TEST(DominatorTreeBatchUpdates, LegalizeDomUpdates) { CFGHolder Holder; CFGBuilder Builder(Holder.F, {{"A", "B"}}, {}); BasicBlock *A = Builder.getOrAddBlock("A"); BasicBlock *B = Builder.getOrAddBlock("B"); BasicBlock *C = Builder.getOrAddBlock("C"); BasicBlock *D = Builder.getOrAddBlock("D"); std::vector<DomUpdate> Updates = { {Insert, B, C}, {Insert, C, D}, {Delete, B, C}, {Insert, B, C}, {Insert, B, D}, {Delete, C, D}, {Delete, A, B}}; SmallVector<DomUpdate, 4> Legalized; DomSNCA::LegalizeUpdates(Updates, Legalized); DEBUG(dbgs() << "Legalized updates:\t"); DEBUG(for (auto &U : Legalized) dbgs() << U << ", "); DEBUG(dbgs() << "\n"); EXPECT_EQ(Legalized.size(), 3UL); EXPECT_NE(llvm::find(Legalized, DomUpdate{Insert, B, C}), Legalized.end()); EXPECT_NE(llvm::find(Legalized, DomUpdate{Insert, B, D}), Legalized.end()); EXPECT_NE(llvm::find(Legalized, DomUpdate{Delete, A, B}), Legalized.end()); } TEST(DominatorTreeBatchUpdates, LegalizePostDomUpdates) { CFGHolder Holder; CFGBuilder Builder(Holder.F, {{"A", "B"}}, {}); BasicBlock *A = Builder.getOrAddBlock("A"); BasicBlock *B = Builder.getOrAddBlock("B"); BasicBlock *C = Builder.getOrAddBlock("C"); BasicBlock *D = Builder.getOrAddBlock("D"); std::vector<DomUpdate> Updates = { {Insert, B, C}, {Insert, C, D}, {Delete, B, C}, {Insert, B, C}, {Insert, B, D}, {Delete, C, D}, {Delete, A, B}}; SmallVector<DomUpdate, 4> Legalized; PostDomSNCA::LegalizeUpdates(Updates, Legalized); DEBUG(dbgs() << "Legalized postdom updates:\t"); DEBUG(for (auto &U : Legalized) dbgs() << U << ", "); DEBUG(dbgs() << "\n"); EXPECT_EQ(Legalized.size(), 3UL); EXPECT_NE(llvm::find(Legalized, DomUpdate{Insert, C, B}), Legalized.end()); EXPECT_NE(llvm::find(Legalized, DomUpdate{Insert, D, B}), Legalized.end()); EXPECT_NE(llvm::find(Legalized, DomUpdate{Delete, B, A}), Legalized.end()); } TEST(DominatorTreeBatchUpdates, SingleInsertion) { CFGHolder Holder; CFGBuilder Builder(Holder.F, {{"A", "B"}}, {{CFGInsert, {"B", "C"}}}); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(DT.verify()); BasicBlock *B = Builder.getOrAddBlock("B"); BasicBlock *C = Builder.getOrAddBlock("C"); std::vector<DomUpdate> Updates = {{Insert, B, C}}; ASSERT_TRUE(Builder.applyUpdate()); DT.applyUpdates(Updates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(Updates); EXPECT_TRUE(PDT.verify()); } TEST(DominatorTreeBatchUpdates, SingleDeletion) { CFGHolder Holder; CFGBuilder Builder(Holder.F, {{"A", "B"}, {"B", "C"}}, {{CFGDelete, {"B", "C"}}}); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(DT.verify()); BasicBlock *B = Builder.getOrAddBlock("B"); BasicBlock *C = Builder.getOrAddBlock("C"); std::vector<DomUpdate> Updates = {{Delete, B, C}}; ASSERT_TRUE(Builder.applyUpdate()); DT.applyUpdates(Updates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(Updates); EXPECT_TRUE(PDT.verify()); } TEST(DominatorTreeBatchUpdates, FewInsertion) { std::vector<CFGBuilder::Update> CFGUpdates = {{CFGInsert, {"B", "C"}}, {CFGInsert, {"C", "B"}}, {CFGInsert, {"C", "D"}}, {CFGInsert, {"D", "E"}}}; CFGHolder Holder; CFGBuilder Builder(Holder.F, {{"A", "B"}}, CFGUpdates); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); BasicBlock *B = Builder.getOrAddBlock("B"); BasicBlock *C = Builder.getOrAddBlock("C"); BasicBlock *D = Builder.getOrAddBlock("D"); BasicBlock *E = Builder.getOrAddBlock("E"); std::vector<DomUpdate> Updates = { {Insert, B, C}, {Insert, C, B}, {Insert, C, D}, {Insert, D, E}}; while (Builder.applyUpdate()) ; DT.applyUpdates(Updates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(Updates); EXPECT_TRUE(PDT.verify()); } TEST(DominatorTreeBatchUpdates, FewDeletions) { std::vector<CFGBuilder::Update> CFGUpdates = {{CFGDelete, {"B", "C"}}, {CFGDelete, {"C", "B"}}, {CFGDelete, {"B", "D"}}, {CFGDelete, {"D", "E"}}}; CFGHolder Holder; CFGBuilder Builder( Holder.F, {{"A", "B"}, {"B", "C"}, {"B", "D"}, {"D", "E"}, {"C", "B"}}, CFGUpdates); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); auto Updates = ToDomUpdates(Builder, CFGUpdates); while (Builder.applyUpdate()) ; DT.applyUpdates(Updates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(Updates); EXPECT_TRUE(PDT.verify()); } TEST(DominatorTreeBatchUpdates, InsertDelete) { std::vector<CFGBuilder::Arc> Arcs = { {"1", "2"}, {"2", "3"}, {"3", "4"}, {"4", "5"}, {"5", "6"}, {"5", "7"}, {"3", "8"}, {"8", "9"}, {"9", "10"}, {"8", "11"}, {"11", "12"}}; std::vector<CFGBuilder::Update> Updates = { {CFGInsert, {"2", "4"}}, {CFGInsert, {"12", "10"}}, {CFGInsert, {"10", "9"}}, {CFGInsert, {"7", "6"}}, {CFGInsert, {"7", "5"}}, {CFGDelete, {"3", "8"}}, {CFGInsert, {"10", "7"}}, {CFGInsert, {"2", "8"}}, {CFGDelete, {"3", "4"}}, {CFGDelete, {"8", "9"}}, {CFGDelete, {"11", "12"}}}; CFGHolder Holder; CFGBuilder B(Holder.F, Arcs, Updates); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); while (B.applyUpdate()) ; auto DomUpdates = ToDomUpdates(B, Updates); DT.applyUpdates(DomUpdates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(DomUpdates); EXPECT_TRUE(PDT.verify()); } TEST(DominatorTreeBatchUpdates, InsertDeleteExhaustive) { std::vector<CFGBuilder::Arc> Arcs = { {"1", "2"}, {"2", "3"}, {"3", "4"}, {"4", "5"}, {"5", "6"}, {"5", "7"}, {"3", "8"}, {"8", "9"}, {"9", "10"}, {"8", "11"}, {"11", "12"}}; std::vector<CFGBuilder::Update> Updates = { {CFGInsert, {"2", "4"}}, {CFGInsert, {"12", "10"}}, {CFGInsert, {"10", "9"}}, {CFGInsert, {"7", "6"}}, {CFGInsert, {"7", "5"}}, {CFGDelete, {"3", "8"}}, {CFGInsert, {"10", "7"}}, {CFGInsert, {"2", "8"}}, {CFGDelete, {"3", "4"}}, {CFGDelete, {"8", "9"}}, {CFGDelete, {"11", "12"}}}; std::mt19937 Generator(0); for (unsigned i = 0; i < 16; ++i) { std::shuffle(Updates.begin(), Updates.end(), Generator); CFGHolder Holder; CFGBuilder B(Holder.F, Arcs, Updates); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); while (B.applyUpdate()) ; auto DomUpdates = ToDomUpdates(B, Updates); DT.applyUpdates(DomUpdates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(DomUpdates); EXPECT_TRUE(PDT.verify()); } } // These are some odd flowgraphs, usually generated from csmith cases, // which are difficult on post dom trees. TEST(DominatorTreeBatchUpdates, InfiniteLoop) { std::vector<CFGBuilder::Arc> Arcs = { {"1", "2"}, {"2", "3"}, {"3", "6"}, {"3", "5"}, {"4", "5"}, {"5", "2"}, {"6", "3"}, {"6", "4"}}; // SplitBlock on 3 -> 5 std::vector<CFGBuilder::Update> Updates = { {CFGInsert, {"N", "5"}}, {CFGInsert, {"3", "N"}}, {CFGDelete, {"3", "5"}}}; CFGHolder Holder; CFGBuilder B(Holder.F, Arcs, Updates); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); while (B.applyUpdate()) ; auto DomUpdates = ToDomUpdates(B, Updates); DT.applyUpdates(DomUpdates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(DomUpdates); EXPECT_TRUE(PDT.verify()); } TEST(DominatorTreeBatchUpdates, DeadBlocks) { std::vector<CFGBuilder::Arc> Arcs = { {"1", "2"}, {"2", "3"}, {"3", "4"}, {"3", "7"}, {"4", "4"}, {"5", "6"}, {"5", "7"}, {"6", "7"}, {"7", "2"}, {"7", "8"}}; // Remove dead 5 and 7, // plus SplitBlock on 7 -> 8 std::vector<CFGBuilder::Update> Updates = { {CFGDelete, {"6", "7"}}, {CFGDelete, {"5", "7"}}, {CFGDelete, {"5", "6"}}, {CFGInsert, {"N", "8"}}, {CFGInsert, {"7", "N"}}, {CFGDelete, {"7", "8"}}}; CFGHolder Holder; CFGBuilder B(Holder.F, Arcs, Updates); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); while (B.applyUpdate()) ; auto DomUpdates = ToDomUpdates(B, Updates); DT.applyUpdates(DomUpdates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(DomUpdates); EXPECT_TRUE(PDT.verify()); } TEST(DominatorTreeBatchUpdates, InfiniteLoop2) { std::vector<CFGBuilder::Arc> Arcs = { {"1", "2"}, {"2", "6"}, {"2", "3"}, {"3", "4"}, {"4", "5"}, {"4", "6"}, {"5", "4"}, {"6", "2"}}; // SplitBlock on 4 -> 6 std::vector<CFGBuilder::Update> Updates = { {CFGInsert, {"N", "6"}}, {CFGInsert, {"4", "N"}}, {CFGDelete, {"4", "6"}}}; CFGHolder Holder; CFGBuilder B(Holder.F, Arcs, Updates); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); while (B.applyUpdate()) ; auto DomUpdates = ToDomUpdates(B, Updates); DT.applyUpdates(DomUpdates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(DomUpdates); EXPECT_TRUE(PDT.verify()); } <commit_msg>[IRTests] Verify PDT instead of DT<commit_after>//===- llvm/unittests/IR/DominatorTreeBatchUpdatesTest.cpp ----------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <random> #include "CFGBuilder.h" #include "gtest/gtest.h" #include "llvm/Analysis/PostDominators.h" #include "llvm/IR/Dominators.h" #include "llvm/Support/GenericDomTreeConstruction.h" #define DEBUG_TYPE "batch-update-tests" using namespace llvm; namespace { const auto CFGInsert = CFGBuilder::ActionKind::Insert; const auto CFGDelete = CFGBuilder::ActionKind::Delete; struct PostDomTree : PostDomTreeBase<BasicBlock> { PostDomTree(Function &F) { recalculate(F); } }; using DomUpdate = DominatorTree::UpdateType; static_assert( std::is_same<DomUpdate, PostDomTree::UpdateType>::value, "Trees differing only in IsPostDom should have the same update types"); using DomSNCA = DomTreeBuilder::SemiNCAInfo<DomTreeBuilder::BBDomTree>; using PostDomSNCA = DomTreeBuilder::SemiNCAInfo<DomTreeBuilder::BBPostDomTree>; const auto Insert = DominatorTree::Insert; const auto Delete = DominatorTree::Delete; std::vector<DomUpdate> ToDomUpdates(CFGBuilder &B, std::vector<CFGBuilder::Update> &In) { std::vector<DomUpdate> Res; Res.reserve(In.size()); for (const auto &CFGU : In) Res.push_back({CFGU.Action == CFGInsert ? Insert : Delete, B.getOrAddBlock(CFGU.Edge.From), B.getOrAddBlock(CFGU.Edge.To)}); return Res; } } // namespace TEST(DominatorTreeBatchUpdates, LegalizeDomUpdates) { CFGHolder Holder; CFGBuilder Builder(Holder.F, {{"A", "B"}}, {}); BasicBlock *A = Builder.getOrAddBlock("A"); BasicBlock *B = Builder.getOrAddBlock("B"); BasicBlock *C = Builder.getOrAddBlock("C"); BasicBlock *D = Builder.getOrAddBlock("D"); std::vector<DomUpdate> Updates = { {Insert, B, C}, {Insert, C, D}, {Delete, B, C}, {Insert, B, C}, {Insert, B, D}, {Delete, C, D}, {Delete, A, B}}; SmallVector<DomUpdate, 4> Legalized; DomSNCA::LegalizeUpdates(Updates, Legalized); DEBUG(dbgs() << "Legalized updates:\t"); DEBUG(for (auto &U : Legalized) dbgs() << U << ", "); DEBUG(dbgs() << "\n"); EXPECT_EQ(Legalized.size(), 3UL); EXPECT_NE(llvm::find(Legalized, DomUpdate{Insert, B, C}), Legalized.end()); EXPECT_NE(llvm::find(Legalized, DomUpdate{Insert, B, D}), Legalized.end()); EXPECT_NE(llvm::find(Legalized, DomUpdate{Delete, A, B}), Legalized.end()); } TEST(DominatorTreeBatchUpdates, LegalizePostDomUpdates) { CFGHolder Holder; CFGBuilder Builder(Holder.F, {{"A", "B"}}, {}); BasicBlock *A = Builder.getOrAddBlock("A"); BasicBlock *B = Builder.getOrAddBlock("B"); BasicBlock *C = Builder.getOrAddBlock("C"); BasicBlock *D = Builder.getOrAddBlock("D"); std::vector<DomUpdate> Updates = { {Insert, B, C}, {Insert, C, D}, {Delete, B, C}, {Insert, B, C}, {Insert, B, D}, {Delete, C, D}, {Delete, A, B}}; SmallVector<DomUpdate, 4> Legalized; PostDomSNCA::LegalizeUpdates(Updates, Legalized); DEBUG(dbgs() << "Legalized postdom updates:\t"); DEBUG(for (auto &U : Legalized) dbgs() << U << ", "); DEBUG(dbgs() << "\n"); EXPECT_EQ(Legalized.size(), 3UL); EXPECT_NE(llvm::find(Legalized, DomUpdate{Insert, C, B}), Legalized.end()); EXPECT_NE(llvm::find(Legalized, DomUpdate{Insert, D, B}), Legalized.end()); EXPECT_NE(llvm::find(Legalized, DomUpdate{Delete, B, A}), Legalized.end()); } TEST(DominatorTreeBatchUpdates, SingleInsertion) { CFGHolder Holder; CFGBuilder Builder(Holder.F, {{"A", "B"}}, {{CFGInsert, {"B", "C"}}}); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); BasicBlock *B = Builder.getOrAddBlock("B"); BasicBlock *C = Builder.getOrAddBlock("C"); std::vector<DomUpdate> Updates = {{Insert, B, C}}; ASSERT_TRUE(Builder.applyUpdate()); DT.applyUpdates(Updates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(Updates); EXPECT_TRUE(PDT.verify()); } TEST(DominatorTreeBatchUpdates, SingleDeletion) { CFGHolder Holder; CFGBuilder Builder(Holder.F, {{"A", "B"}, {"B", "C"}}, {{CFGDelete, {"B", "C"}}}); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); BasicBlock *B = Builder.getOrAddBlock("B"); BasicBlock *C = Builder.getOrAddBlock("C"); std::vector<DomUpdate> Updates = {{Delete, B, C}}; ASSERT_TRUE(Builder.applyUpdate()); DT.applyUpdates(Updates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(Updates); EXPECT_TRUE(PDT.verify()); } TEST(DominatorTreeBatchUpdates, FewInsertion) { std::vector<CFGBuilder::Update> CFGUpdates = {{CFGInsert, {"B", "C"}}, {CFGInsert, {"C", "B"}}, {CFGInsert, {"C", "D"}}, {CFGInsert, {"D", "E"}}}; CFGHolder Holder; CFGBuilder Builder(Holder.F, {{"A", "B"}}, CFGUpdates); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); BasicBlock *B = Builder.getOrAddBlock("B"); BasicBlock *C = Builder.getOrAddBlock("C"); BasicBlock *D = Builder.getOrAddBlock("D"); BasicBlock *E = Builder.getOrAddBlock("E"); std::vector<DomUpdate> Updates = { {Insert, B, C}, {Insert, C, B}, {Insert, C, D}, {Insert, D, E}}; while (Builder.applyUpdate()) ; DT.applyUpdates(Updates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(Updates); EXPECT_TRUE(PDT.verify()); } TEST(DominatorTreeBatchUpdates, FewDeletions) { std::vector<CFGBuilder::Update> CFGUpdates = {{CFGDelete, {"B", "C"}}, {CFGDelete, {"C", "B"}}, {CFGDelete, {"B", "D"}}, {CFGDelete, {"D", "E"}}}; CFGHolder Holder; CFGBuilder Builder( Holder.F, {{"A", "B"}, {"B", "C"}, {"B", "D"}, {"D", "E"}, {"C", "B"}}, CFGUpdates); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); auto Updates = ToDomUpdates(Builder, CFGUpdates); while (Builder.applyUpdate()) ; DT.applyUpdates(Updates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(Updates); EXPECT_TRUE(PDT.verify()); } TEST(DominatorTreeBatchUpdates, InsertDelete) { std::vector<CFGBuilder::Arc> Arcs = { {"1", "2"}, {"2", "3"}, {"3", "4"}, {"4", "5"}, {"5", "6"}, {"5", "7"}, {"3", "8"}, {"8", "9"}, {"9", "10"}, {"8", "11"}, {"11", "12"}}; std::vector<CFGBuilder::Update> Updates = { {CFGInsert, {"2", "4"}}, {CFGInsert, {"12", "10"}}, {CFGInsert, {"10", "9"}}, {CFGInsert, {"7", "6"}}, {CFGInsert, {"7", "5"}}, {CFGDelete, {"3", "8"}}, {CFGInsert, {"10", "7"}}, {CFGInsert, {"2", "8"}}, {CFGDelete, {"3", "4"}}, {CFGDelete, {"8", "9"}}, {CFGDelete, {"11", "12"}}}; CFGHolder Holder; CFGBuilder B(Holder.F, Arcs, Updates); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); while (B.applyUpdate()) ; auto DomUpdates = ToDomUpdates(B, Updates); DT.applyUpdates(DomUpdates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(DomUpdates); EXPECT_TRUE(PDT.verify()); } TEST(DominatorTreeBatchUpdates, InsertDeleteExhaustive) { std::vector<CFGBuilder::Arc> Arcs = { {"1", "2"}, {"2", "3"}, {"3", "4"}, {"4", "5"}, {"5", "6"}, {"5", "7"}, {"3", "8"}, {"8", "9"}, {"9", "10"}, {"8", "11"}, {"11", "12"}}; std::vector<CFGBuilder::Update> Updates = { {CFGInsert, {"2", "4"}}, {CFGInsert, {"12", "10"}}, {CFGInsert, {"10", "9"}}, {CFGInsert, {"7", "6"}}, {CFGInsert, {"7", "5"}}, {CFGDelete, {"3", "8"}}, {CFGInsert, {"10", "7"}}, {CFGInsert, {"2", "8"}}, {CFGDelete, {"3", "4"}}, {CFGDelete, {"8", "9"}}, {CFGDelete, {"11", "12"}}}; std::mt19937 Generator(0); for (unsigned i = 0; i < 16; ++i) { std::shuffle(Updates.begin(), Updates.end(), Generator); CFGHolder Holder; CFGBuilder B(Holder.F, Arcs, Updates); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); while (B.applyUpdate()) ; auto DomUpdates = ToDomUpdates(B, Updates); DT.applyUpdates(DomUpdates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(DomUpdates); EXPECT_TRUE(PDT.verify()); } } // These are some odd flowgraphs, usually generated from csmith cases, // which are difficult on post dom trees. TEST(DominatorTreeBatchUpdates, InfiniteLoop) { std::vector<CFGBuilder::Arc> Arcs = { {"1", "2"}, {"2", "3"}, {"3", "6"}, {"3", "5"}, {"4", "5"}, {"5", "2"}, {"6", "3"}, {"6", "4"}}; // SplitBlock on 3 -> 5 std::vector<CFGBuilder::Update> Updates = { {CFGInsert, {"N", "5"}}, {CFGInsert, {"3", "N"}}, {CFGDelete, {"3", "5"}}}; CFGHolder Holder; CFGBuilder B(Holder.F, Arcs, Updates); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); while (B.applyUpdate()) ; auto DomUpdates = ToDomUpdates(B, Updates); DT.applyUpdates(DomUpdates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(DomUpdates); EXPECT_TRUE(PDT.verify()); } TEST(DominatorTreeBatchUpdates, DeadBlocks) { std::vector<CFGBuilder::Arc> Arcs = { {"1", "2"}, {"2", "3"}, {"3", "4"}, {"3", "7"}, {"4", "4"}, {"5", "6"}, {"5", "7"}, {"6", "7"}, {"7", "2"}, {"7", "8"}}; // Remove dead 5 and 7, // plus SplitBlock on 7 -> 8 std::vector<CFGBuilder::Update> Updates = { {CFGDelete, {"6", "7"}}, {CFGDelete, {"5", "7"}}, {CFGDelete, {"5", "6"}}, {CFGInsert, {"N", "8"}}, {CFGInsert, {"7", "N"}}, {CFGDelete, {"7", "8"}}}; CFGHolder Holder; CFGBuilder B(Holder.F, Arcs, Updates); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); while (B.applyUpdate()) ; auto DomUpdates = ToDomUpdates(B, Updates); DT.applyUpdates(DomUpdates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(DomUpdates); EXPECT_TRUE(PDT.verify()); } TEST(DominatorTreeBatchUpdates, InfiniteLoop2) { std::vector<CFGBuilder::Arc> Arcs = { {"1", "2"}, {"2", "6"}, {"2", "3"}, {"3", "4"}, {"4", "5"}, {"4", "6"}, {"5", "4"}, {"6", "2"}}; // SplitBlock on 4 -> 6 std::vector<CFGBuilder::Update> Updates = { {CFGInsert, {"N", "6"}}, {CFGInsert, {"4", "N"}}, {CFGDelete, {"4", "6"}}}; CFGHolder Holder; CFGBuilder B(Holder.F, Arcs, Updates); DominatorTree DT(*Holder.F); EXPECT_TRUE(DT.verify()); PostDomTree PDT(*Holder.F); EXPECT_TRUE(PDT.verify()); while (B.applyUpdate()) ; auto DomUpdates = ToDomUpdates(B, Updates); DT.applyUpdates(DomUpdates); EXPECT_TRUE(DT.verify()); PDT.applyUpdates(DomUpdates); EXPECT_TRUE(PDT.verify()); } <|endoftext|>
<commit_before>/* * Copyright 2015 WebAssembly Community Group participants * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "support/command-line.h" using namespace wasm; Options::Options(const std::string &command, const std::string &description) : debug(false), positional(Arguments::Zero) { add("--help", "-h", "Show this help message and exit", Arguments::Zero, [this, command, description](Options *o, const std::string &) { std::cerr << command; if (positional != Arguments::Zero) std::cerr << ' ' << positionalName; std::cerr << "\n\n" << description << "\n\nOptions:\n"; size_t optionWidth = 0; for (const auto &o : options) { optionWidth = std::max(optionWidth, o.longName.size() + o.shortName.size()); } // TODO: line-wrap description. for (const auto &o : options) { bool long_n_short = o.longName.size() != 0 && o.shortName.size() != 0; size_t pad = 1 + optionWidth - o.longName.size() - o.shortName.size(); std::cerr << " " << o.longName << (long_n_short ? ',' : ' ') << o.shortName << std::string(pad, ' ') << o.description << '\n'; } std::cerr << '\n'; exit(EXIT_SUCCESS); }); add("--debug", "-d", "Print debug information to stderr", Arguments::Zero, [](Options *o, const std::string &arguments) {}); } Options::~Options() {} Options &Options::add(const std::string &longName, const std::string &shortName, const std::string &description, Arguments arguments, const Action &action) { options.push_back({longName, shortName, description, arguments, action, 0}); return *this; } Options &Options::add_positional(const std::string &name, Arguments arguments, const Action &action) { positional = arguments; positionalName = name; positionalAction = action; return *this; } void Options::parse(int argc, const char *argv[]) { assert(argc > 0 && "expect at least program name as an argument"); size_t positionalsSeen = 0; auto dashes = [](const std::string &s) { for (size_t i = 0;; ++i) { if (s[i] != '-') return i; } }; for (size_t i = 1, e = argc; i != e; ++i) { std::string currentOption = argv[i]; if (dashes(currentOption) == 0) { // Positional. switch (positional) { case Arguments::Zero: std::cerr << "Unexpected positional argument '" << currentOption << "'\n"; exit(EXIT_FAILURE); case Arguments::One: case Arguments::Optional: if (positionalsSeen) { std::cerr << "Unexpected second positional argument '" << currentOption << "' for " << positionalName << '\n'; exit(EXIT_FAILURE); } // Fallthrough. case Arguments::N: positionalAction(this, currentOption); ++positionalsSeen; break; } continue; } // Non-positional. std::string argument; auto equal = currentOption.find_first_of('='); if (equal != std::string::npos) { argument = currentOption.substr(equal + 1); currentOption = currentOption.substr(0, equal); } Option *option = nullptr; for (auto &o : options) if (o.longName == currentOption || o.shortName == currentOption) option = &o; if (!option) { std::cerr << "Unknown option '" << currentOption << "'\n"; exit(EXIT_FAILURE); } switch (option->arguments) { case Arguments::Zero: if (argument.size()) { std::cerr << "Unexpected argument '" << argument << "' for option '" << currentOption << "'\n"; exit(EXIT_FAILURE); } break; case Arguments::One: if (option->seen) { std::cerr << "Unexpected second argument '" << argument << "' for '" << currentOption << "'\n"; exit(EXIT_FAILURE); } // Fallthrough. case Arguments::N: if (!argument.size()) { if (i + 1 == e) { std::cerr << "Couldn't find expected argument for '" << currentOption << "'\n"; exit(EXIT_FAILURE); } argument = argv[++i]; } break; case Arguments::Optional: if (!argument.size()) { if (i + 1 != e) argument = argv[++i]; } break; } option->action(this, argument); ++option->seen; } } <commit_msg>make --debug work<commit_after>/* * Copyright 2015 WebAssembly Community Group participants * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "support/command-line.h" using namespace wasm; Options::Options(const std::string &command, const std::string &description) : debug(false), positional(Arguments::Zero) { add("--help", "-h", "Show this help message and exit", Arguments::Zero, [this, command, description](Options *o, const std::string &) { std::cerr << command; if (positional != Arguments::Zero) std::cerr << ' ' << positionalName; std::cerr << "\n\n" << description << "\n\nOptions:\n"; size_t optionWidth = 0; for (const auto &o : options) { optionWidth = std::max(optionWidth, o.longName.size() + o.shortName.size()); } // TODO: line-wrap description. for (const auto &o : options) { bool long_n_short = o.longName.size() != 0 && o.shortName.size() != 0; size_t pad = 1 + optionWidth - o.longName.size() - o.shortName.size(); std::cerr << " " << o.longName << (long_n_short ? ',' : ' ') << o.shortName << std::string(pad, ' ') << o.description << '\n'; } std::cerr << '\n'; exit(EXIT_SUCCESS); }); add("--debug", "-d", "Print debug information to stderr", Arguments::Zero, [&](Options *o, const std::string &arguments) { debug = true; }); } Options::~Options() {} Options &Options::add(const std::string &longName, const std::string &shortName, const std::string &description, Arguments arguments, const Action &action) { options.push_back({longName, shortName, description, arguments, action, 0}); return *this; } Options &Options::add_positional(const std::string &name, Arguments arguments, const Action &action) { positional = arguments; positionalName = name; positionalAction = action; return *this; } void Options::parse(int argc, const char *argv[]) { assert(argc > 0 && "expect at least program name as an argument"); size_t positionalsSeen = 0; auto dashes = [](const std::string &s) { for (size_t i = 0;; ++i) { if (s[i] != '-') return i; } }; for (size_t i = 1, e = argc; i != e; ++i) { std::string currentOption = argv[i]; if (dashes(currentOption) == 0) { // Positional. switch (positional) { case Arguments::Zero: std::cerr << "Unexpected positional argument '" << currentOption << "'\n"; exit(EXIT_FAILURE); case Arguments::One: case Arguments::Optional: if (positionalsSeen) { std::cerr << "Unexpected second positional argument '" << currentOption << "' for " << positionalName << '\n'; exit(EXIT_FAILURE); } // Fallthrough. case Arguments::N: positionalAction(this, currentOption); ++positionalsSeen; break; } continue; } // Non-positional. std::string argument; auto equal = currentOption.find_first_of('='); if (equal != std::string::npos) { argument = currentOption.substr(equal + 1); currentOption = currentOption.substr(0, equal); } Option *option = nullptr; for (auto &o : options) if (o.longName == currentOption || o.shortName == currentOption) option = &o; if (!option) { std::cerr << "Unknown option '" << currentOption << "'\n"; exit(EXIT_FAILURE); } switch (option->arguments) { case Arguments::Zero: if (argument.size()) { std::cerr << "Unexpected argument '" << argument << "' for option '" << currentOption << "'\n"; exit(EXIT_FAILURE); } break; case Arguments::One: if (option->seen) { std::cerr << "Unexpected second argument '" << argument << "' for '" << currentOption << "'\n"; exit(EXIT_FAILURE); } // Fallthrough. case Arguments::N: if (!argument.size()) { if (i + 1 == e) { std::cerr << "Couldn't find expected argument for '" << currentOption << "'\n"; exit(EXIT_FAILURE); } argument = argv[++i]; } break; case Arguments::Optional: if (!argument.size()) { if (i + 1 != e) argument = argv[++i]; } break; } option->action(this, argument); ++option->seen; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2005 Justin Karneges <justin@affinix.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * */ #include "qca_support.h" #include <QAbstractEventDispatcher> #include <QCoreApplication> #include <QEvent> #include <QMutex> #include <QPair> #include <QTime> #include <QWaitCondition> //#define TIMERFIXER_DEBUG namespace QCA { //---------------------------------------------------------------------------- // TimerFixer //---------------------------------------------------------------------------- class TimerFixer : public QObject { Q_OBJECT public: struct TimerInfo { int id; int interval; QTime time; bool fixInterval; TimerInfo() : fixInterval(false) {} }; TimerFixer *fixerParent; QList<TimerFixer*> fixerChildren; QObject *target; QAbstractEventDispatcher *ed; QList<TimerInfo> timers; static bool haveFixer(QObject *obj) { return (qFindChild<TimerFixer *>(obj) ? true: false); } TimerFixer(QObject *_target, TimerFixer *_fp = 0) : QObject(_target) { ed = 0; target = _target; fixerParent = _fp; if(fixerParent) fixerParent->fixerChildren.append(this); #ifdef TIMERFIXER_DEBUG printf("TimerFixer[%p] pairing with %p (%s)\n", this, target, target->metaObject()->className()); #endif edlink(); target->installEventFilter(this); QObjectList list = target->children(); for(int n = 0; n < list.count(); ++n) hook(list[n]); } ~TimerFixer() { if(fixerParent) fixerParent->fixerChildren.removeAll(this); QList<TimerFixer*> list = fixerChildren; for(int n = 0; n < list.count(); ++n) delete list[n]; list.clear(); updateTimerList(); // do this just to trip debug output target->removeEventFilter(this); edunlink(); #ifdef TIMERFIXER_DEBUG printf("TimerFixer[%p] unpaired with %p (%s)\n", this, target, target->metaObject()->className()); #endif } virtual bool event(QEvent *e) { switch(e->type()) { case QEvent::ThreadChange: // this happens second //printf("TimerFixer[%p] self changing threads\n", this); edunlink(); QMetaObject::invokeMethod(this, "fixTimers", Qt::QueuedConnection); break; default: break; } return QObject::event(e); } virtual bool eventFilter(QObject *, QEvent *e) { switch(e->type()) { case QEvent::ChildAdded: hook(((QChildEvent *)e)->child()); break; case QEvent::ChildRemoved: unhook(((QChildEvent *)e)->child()); break; case QEvent::Timer: handleTimerEvent(((QTimerEvent *)e)->timerId()); break; case QEvent::ThreadChange: // this happens first #ifdef TIMERFIXER_DEBUG printf("TimerFixer[%p] target changing threads\n", this); #endif break; default: break; } return false; } private slots: void edlink() { ed = QAbstractEventDispatcher::instance(); //printf("TimerFixer[%p] linking to dispatcher %p\n", this, ed); connect(ed, SIGNAL(aboutToBlock()), SLOT(ed_aboutToBlock())); } void edunlink() { //printf("TimerFixer[%p] unlinking from dispatcher %p\n", this, ed); if(ed) { disconnect(ed, SIGNAL(aboutToBlock()), this, SLOT(ed_aboutToBlock())); ed = 0; } } void ed_aboutToBlock() { //printf("TimerFixer[%p] aboutToBlock\n", this); updateTimerList(); } void fixTimers() { edlink(); updateTimerList(); for(int n = 0; n < timers.count(); ++n) { TimerInfo &info = timers[n]; QThread *objectThread = target->thread(); QAbstractEventDispatcher *ed = QAbstractEventDispatcher::instance(objectThread); int timeLeft = qMax(info.interval - info.time.elapsed(), 0); info.fixInterval = true; ed->unregisterTimer(info.id); ed->registerTimer(info.id, timeLeft, target); #ifdef TIMERFIXER_DEBUG printf("TimerFixer[%p] adjusting [%d] to %d\n", this, info.id, timeLeft); #endif } } private: void hook(QObject *obj) { // don't watch a fixer or any object that already has one if(obj == this || qobject_cast<TimerFixer *>(obj) || haveFixer(obj)) return; new TimerFixer(obj, this); } void unhook(QObject *obj) { TimerFixer *t = 0; for(int n = 0; n < fixerChildren.count(); ++n) { if(fixerChildren[n]->target == obj) t = fixerChildren[n]; } delete t; } void handleTimerEvent(int id) { bool found = false; int n; for(n = 0; n < timers.count(); ++n) { if(timers[n].id == id) { found = true; break; } } if(!found) { //printf("*** unrecognized timer [%d] activated ***\n", id); return; } TimerInfo &info = timers[n]; #ifdef TIMERFIXER_DEBUG printf("TimerFixer[%p] timer [%d] activated!\n", this, info.id); #endif if(info.fixInterval) { #ifdef TIMERFIXER_DEBUG printf("restoring correct interval (%d)\n", info.interval); #endif info.fixInterval = false; ed->unregisterTimer(info.id); ed->registerTimer(info.id, info.interval, target); } info.time.start(); } void updateTimerList() { QList<QAbstractEventDispatcher::TimerInfo> edtimers; if(ed) edtimers = ed->registeredTimers(target); // removed? for(int n = 0; n < timers.count(); ++n) { bool found = false; int id = timers[n].id; for(int i = 0; i < edtimers.count(); ++i) { if(edtimers[i].first == id) { found = true; break; } } if(!found) { timers.removeAt(n); --n; #ifdef TIMERFIXER_DEBUG printf("TimerFixer[%p] timer [%d] removed\n", this, id); #endif } } // added? for(int n = 0; n < edtimers.count(); ++n) { int id = edtimers[n].first; bool found = false; for(int i = 0; i < timers.count(); ++i) { if(timers[i].id == id) { found = true; break; } } if(!found) { TimerInfo info; info.id = id; info.interval = edtimers[n].second; info.time.start(); timers += info; #ifdef TIMERFIXER_DEBUG printf("TimerFixer[%p] timer [%d] added (interval=%d)\n", this, info.id, info.interval); #endif } } } }; //---------------------------------------------------------------------------- // Synchronizer //---------------------------------------------------------------------------- class Synchronizer::Private : public QThread { Q_OBJECT public: Synchronizer *q; bool active; bool do_quit; bool cond_met; QObject *obj; QEventLoop *loop; TimerFixer *fixer; QMutex m; QWaitCondition w; QThread *orig_thread; Private(QObject *_obj, Synchronizer *_q) : QThread(_q), q(_q) { active = false; obj = _obj; loop = 0; fixer = new TimerFixer(obj); } ~Private() { stop(); delete fixer; } void start() { m.lock(); active = true; do_quit = false; QThread::start(); w.wait(&m); m.unlock(); } void stop() { if(!active) return; m.lock(); do_quit = true; w.wakeOne(); m.unlock(); wait(); } bool waitForCondition(int msecs) { unsigned long time = ULONG_MAX; if(msecs != -1) time = msecs; // move object to the worker thread cond_met = false; orig_thread = QThread::currentThread(); q->setParent(0); // don't follow the object QObject *orig_parent = obj->parent(); obj->setParent(0); // unparent the target or the move will fail obj->moveToThread(this); // tell the worker thread to start, wait for completion m.lock(); w.wakeOne(); if(!w.wait(&m, time)) { if(loop) { // if we timed out, tell the worker to quit QMetaObject::invokeMethod(loop, "quit"); w.wait(&m); } } // at this point the worker is done. cleanup and return m.unlock(); // restore parents obj->setParent(orig_parent); q->setParent(obj); return cond_met; } void conditionMet() { if(!loop) return; loop->quit(); cond_met = true; } protected: virtual void run() { m.lock(); QEventLoop eventLoop; while(1) { // thread now sleeps, waiting for work w.wakeOne(); w.wait(&m); if(do_quit) { m.unlock(); break; } loop = &eventLoop; m.unlock(); // run the event loop eventLoop.exec(); // eventloop done, flush pending events QCoreApplication::instance()->sendPostedEvents(); QCoreApplication::instance()->sendPostedEvents(0, QEvent::DeferredDelete); // and move the object back obj->moveToThread(orig_thread); m.lock(); loop = 0; w.wakeOne(); } } }; Synchronizer::Synchronizer(QObject *parent) :QObject(parent) { d = new Private(parent, this); d->start(); } Synchronizer::~Synchronizer() { delete d; } bool Synchronizer::waitForCondition(int msecs) { return d->waitForCondition(msecs); } void Synchronizer::conditionMet() { d->conditionMet(); } } #include "synchronizer.moc" <commit_msg>lazy-start the thread<commit_after>/* * Copyright (C) 2005 Justin Karneges <justin@affinix.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * */ #include "qca_support.h" #include <QAbstractEventDispatcher> #include <QCoreApplication> #include <QEvent> #include <QMutex> #include <QPair> #include <QTime> #include <QWaitCondition> //#define TIMERFIXER_DEBUG namespace QCA { //---------------------------------------------------------------------------- // TimerFixer //---------------------------------------------------------------------------- class TimerFixer : public QObject { Q_OBJECT public: struct TimerInfo { int id; int interval; QTime time; bool fixInterval; TimerInfo() : fixInterval(false) {} }; TimerFixer *fixerParent; QList<TimerFixer*> fixerChildren; QObject *target; QAbstractEventDispatcher *ed; QList<TimerInfo> timers; static bool haveFixer(QObject *obj) { return (qFindChild<TimerFixer *>(obj) ? true: false); } TimerFixer(QObject *_target, TimerFixer *_fp = 0) : QObject(_target) { ed = 0; target = _target; fixerParent = _fp; if(fixerParent) fixerParent->fixerChildren.append(this); #ifdef TIMERFIXER_DEBUG printf("TimerFixer[%p] pairing with %p (%s)\n", this, target, target->metaObject()->className()); #endif edlink(); target->installEventFilter(this); QObjectList list = target->children(); for(int n = 0; n < list.count(); ++n) hook(list[n]); } ~TimerFixer() { if(fixerParent) fixerParent->fixerChildren.removeAll(this); QList<TimerFixer*> list = fixerChildren; for(int n = 0; n < list.count(); ++n) delete list[n]; list.clear(); updateTimerList(); // do this just to trip debug output target->removeEventFilter(this); edunlink(); #ifdef TIMERFIXER_DEBUG printf("TimerFixer[%p] unpaired with %p (%s)\n", this, target, target->metaObject()->className()); #endif } virtual bool event(QEvent *e) { switch(e->type()) { case QEvent::ThreadChange: // this happens second //printf("TimerFixer[%p] self changing threads\n", this); edunlink(); QMetaObject::invokeMethod(this, "fixTimers", Qt::QueuedConnection); break; default: break; } return QObject::event(e); } virtual bool eventFilter(QObject *, QEvent *e) { switch(e->type()) { case QEvent::ChildAdded: hook(((QChildEvent *)e)->child()); break; case QEvent::ChildRemoved: unhook(((QChildEvent *)e)->child()); break; case QEvent::Timer: handleTimerEvent(((QTimerEvent *)e)->timerId()); break; case QEvent::ThreadChange: // this happens first #ifdef TIMERFIXER_DEBUG printf("TimerFixer[%p] target changing threads\n", this); #endif break; default: break; } return false; } private slots: void edlink() { ed = QAbstractEventDispatcher::instance(); //printf("TimerFixer[%p] linking to dispatcher %p\n", this, ed); connect(ed, SIGNAL(aboutToBlock()), SLOT(ed_aboutToBlock())); } void edunlink() { //printf("TimerFixer[%p] unlinking from dispatcher %p\n", this, ed); if(ed) { disconnect(ed, SIGNAL(aboutToBlock()), this, SLOT(ed_aboutToBlock())); ed = 0; } } void ed_aboutToBlock() { //printf("TimerFixer[%p] aboutToBlock\n", this); updateTimerList(); } void fixTimers() { edlink(); updateTimerList(); for(int n = 0; n < timers.count(); ++n) { TimerInfo &info = timers[n]; QThread *objectThread = target->thread(); QAbstractEventDispatcher *ed = QAbstractEventDispatcher::instance(objectThread); int timeLeft = qMax(info.interval - info.time.elapsed(), 0); info.fixInterval = true; ed->unregisterTimer(info.id); ed->registerTimer(info.id, timeLeft, target); #ifdef TIMERFIXER_DEBUG printf("TimerFixer[%p] adjusting [%d] to %d\n", this, info.id, timeLeft); #endif } } private: void hook(QObject *obj) { // don't watch a fixer or any object that already has one if(obj == this || qobject_cast<TimerFixer *>(obj) || haveFixer(obj)) return; new TimerFixer(obj, this); } void unhook(QObject *obj) { TimerFixer *t = 0; for(int n = 0; n < fixerChildren.count(); ++n) { if(fixerChildren[n]->target == obj) t = fixerChildren[n]; } delete t; } void handleTimerEvent(int id) { bool found = false; int n; for(n = 0; n < timers.count(); ++n) { if(timers[n].id == id) { found = true; break; } } if(!found) { //printf("*** unrecognized timer [%d] activated ***\n", id); return; } TimerInfo &info = timers[n]; #ifdef TIMERFIXER_DEBUG printf("TimerFixer[%p] timer [%d] activated!\n", this, info.id); #endif if(info.fixInterval) { #ifdef TIMERFIXER_DEBUG printf("restoring correct interval (%d)\n", info.interval); #endif info.fixInterval = false; ed->unregisterTimer(info.id); ed->registerTimer(info.id, info.interval, target); } info.time.start(); } void updateTimerList() { QList<QAbstractEventDispatcher::TimerInfo> edtimers; if(ed) edtimers = ed->registeredTimers(target); // removed? for(int n = 0; n < timers.count(); ++n) { bool found = false; int id = timers[n].id; for(int i = 0; i < edtimers.count(); ++i) { if(edtimers[i].first == id) { found = true; break; } } if(!found) { timers.removeAt(n); --n; #ifdef TIMERFIXER_DEBUG printf("TimerFixer[%p] timer [%d] removed\n", this, id); #endif } } // added? for(int n = 0; n < edtimers.count(); ++n) { int id = edtimers[n].first; bool found = false; for(int i = 0; i < timers.count(); ++i) { if(timers[i].id == id) { found = true; break; } } if(!found) { TimerInfo info; info.id = id; info.interval = edtimers[n].second; info.time.start(); timers += info; #ifdef TIMERFIXER_DEBUG printf("TimerFixer[%p] timer [%d] added (interval=%d)\n", this, info.id, info.interval); #endif } } } }; //---------------------------------------------------------------------------- // Synchronizer //---------------------------------------------------------------------------- class Synchronizer::Private : public QThread { Q_OBJECT public: Synchronizer *q; bool active; bool do_quit; bool cond_met; QObject *obj; QEventLoop *loop; TimerFixer *fixer; QMutex m; QWaitCondition w; QThread *orig_thread; Private(QObject *_obj, Synchronizer *_q) : QThread(_q), q(_q) { active = false; obj = _obj; loop = 0; fixer = new TimerFixer(obj); } ~Private() { stop(); delete fixer; } void start() { if(active) return; m.lock(); active = true; do_quit = false; QThread::start(); w.wait(&m); m.unlock(); } void stop() { if(!active) return; m.lock(); do_quit = true; w.wakeOne(); m.unlock(); wait(); active = false; } bool waitForCondition(int msecs) { unsigned long time = ULONG_MAX; if(msecs != -1) time = msecs; // move object to the worker thread cond_met = false; orig_thread = QThread::currentThread(); q->setParent(0); // don't follow the object QObject *orig_parent = obj->parent(); obj->setParent(0); // unparent the target or the move will fail obj->moveToThread(this); // tell the worker thread to start, wait for completion m.lock(); w.wakeOne(); if(!w.wait(&m, time)) { if(loop) { // if we timed out, tell the worker to quit QMetaObject::invokeMethod(loop, "quit"); w.wait(&m); } } // at this point the worker is done. cleanup and return m.unlock(); // restore parents obj->setParent(orig_parent); q->setParent(obj); return cond_met; } void conditionMet() { if(!loop) return; loop->quit(); cond_met = true; } protected: virtual void run() { m.lock(); QEventLoop eventLoop; while(1) { // thread now sleeps, waiting for work w.wakeOne(); w.wait(&m); if(do_quit) { m.unlock(); break; } loop = &eventLoop; m.unlock(); // run the event loop eventLoop.exec(); // eventloop done, flush pending events QCoreApplication::instance()->sendPostedEvents(); QCoreApplication::instance()->sendPostedEvents(0, QEvent::DeferredDelete); // and move the object back obj->moveToThread(orig_thread); m.lock(); loop = 0; w.wakeOne(); } } }; Synchronizer::Synchronizer(QObject *parent) :QObject(parent) { d = new Private(parent, this); } Synchronizer::~Synchronizer() { delete d; } bool Synchronizer::waitForCondition(int msecs) { d->start(); return d->waitForCondition(msecs); } void Synchronizer::conditionMet() { d->conditionMet(); } } #include "synchronizer.moc" <|endoftext|>
<commit_before> #ifndef SILL_LEARNING_DISCRIMINATIVE_CLASSIFIER_CASCADE_HPP #define SILL_LEARNING_DISCRIMINATIVE_CLASSIFIER_CASCADE_HPP #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int.hpp> #include <sill/learning/dataset/ds_oracle.hpp> #include <sill/learning/dataset/vector_dataset.hpp> #include <sill/learning/discriminative/binary_classifier.hpp> #include <sill/math/statistics.hpp> #include <sill/stl_io.hpp> #include <sill/macros_def.hpp> // set to 1 to print debugging information #define DEBUG_CLASSIFIER_CASCADE 1 namespace sill { struct classifier_cascade_parameters { typedef dense_linear_algebra<> la_type; /** * Empty classifiers to use to construct the base classifiers. The * parameters from these classifiers are used for the base classifiers, * save for random seeds, which are generated by the cascade classifier. * If the number of base classifiers becomes > BASE_CLASSIFIERS.size(), * then the last classifier from BASE_CLASSIFIERS is used to construct * the extra base classifiers. * (required) */ std::vector<boost::shared_ptr<binary_classifier<la_type> > > base_classifiers; //! Initial number of base classifiers to build. //! (default = 0) size_t init_base_classifiers; //! Label/class which is rare //! (required) size_t rare_class; /** * Max misclassification rate for the * rare class for each level of the cascade * (If RARE_CLASS = 0, this is the false positive rate; * if RARE_CLASS = 1, this is the false negative rate.) * This should be fairly high (say .95 to .99). * (required) */ double max_false_common_rate; //! Number of training examples to pass to the base dataset, //! including all examples from the rare class. //! (default = 2 * number of examples in rare class) size_t base_dataset_size; //! Used to make the algorithm deterministic //! (default = time) double random_seed; /** * Max number of examples which can be thrown * out to generate one example from the common class. * This resets to the default if it has value 0. * (default = 100 / (1 - MAX_FALSE_COMMON_RATE), or * = 100000 if the rate is 1) * @todo MAX_FILTER_COUNT should be set more intelligently. */ size_t max_filter_count; classifier_cascade_parameters() : base_classifiers(), init_base_classifiers(0), rare_class(2), max_false_common_rate(2), base_dataset_size(0), max_filter_count(0) { std::time_t time_tmp; time(&time_tmp); random_seed = time_tmp; } bool valid() const { if (rare_class != 0 && rare_class != 1) return false; if (max_false_common_rate < 0 || max_false_common_rate > 1) return false; return true; } void set_check_params(size_t n_rare_exs) { if (base_dataset_size == 0) { // then set to default base_dataset_size = 2 * n_rare_exs; } else assert(base_dataset_size > n_rare_exs); if (max_filter_count == 0) { // then set to default if (max_false_common_rate == 1) max_filter_count = 100000; else max_filter_count = 100 / (1. - max_false_common_rate); } } void save(std::ofstream& out) const { out << base_classifiers.size() << " " << init_base_classifiers << " " << rare_class << " " << max_false_common_rate << " " << base_dataset_size << " " << random_seed << " " << max_filter_count << "\n"; for (size_t t = 0; t < base_classifiers.size(); ++t) base_classifiers[t]->save(out); } void load(std::ifstream& in, const datasource& ds); }; // class classifier_cascade_parameters /** * Cascade of increasingly complex/accurate binary classifiers, useful * for rapid classification with highly imbalanced classes. * * This is based on the cascades used by Viola and Jones for face detection. * The classifier cascade is given a range of empty binary classifiers, * and it trains these iteratively on a combination of examples from a fixed * set and of examples generated from a given oracle. The examples from * the oracle are passed through a classifier_filter_oracle which can, e.g., * only select examples which the current cascade misclassifies. * * At test time, the cascade works as follows: * - The test example is given to the first classifier. * - The first classifier's predict_raw() value is compared to * a threshold (chosen at training time). * - If the rare class is 1 (0), then if predict_raw() is greater (less) * than this threshold, then the example is passed to the next classifier * in the cascade. Otherwise, it is classified as 0 (1). * * At training time, the cascade: * - Builds a dataset using a fixed set of examples (which should be * examples from the rare class) and new examples from an oracle (which * should provide examples from the common class) * - Trains the first base classifier * - Chooses a threshold such that, if the rare class is 1 (0), * using the prediction rule * (base_classifier.predict_raw() > threshold ? 1 : 0) * gives a low false negative (positive) rate. * - Iterates, training the next base classifiers in the same way. * In the following iterations, though, the examples from the oracle * are filtered such that only examples which are misclassified by the * current set of cascades are accepted. * * NOTE: This must be used with a margin-based classifier. * * \author Joseph Bradley * \ingroup learning_discriminative * @todo serialization */ class classifier_cascade : public binary_classifier<dense_linear_algebra<> > { // Public types //========================================================================== public: typedef dense_linear_algebra<> la_type; typedef binary_classifier<la_type> base; typedef base::record_type record_type; typedef classifier_cascade_parameters parameters; // Protected data members //========================================================================== protected: parameters params; // copied from params: size_t max_filter_count_; //! random number generator boost::mt11213b rng; //! Dataset to be passed to base learners //! The first fixed_ds_size examples are from the fixed dataset, //! and the remaining ones are from the oracle. vector_dataset<la_type> base_ds; //! Number of rare class examples permanently stored in base_ds. size_t rare_ds_size; //! for constructing an empty classifier_cascade ds_oracle<la_type>* ds_o_ptr; //! Oracle for common class oracle<la_type>& common_o; //! Used for choosing a threshold (and avoiding reallocation) vec base_ds_preds; //! Base classifiers std::vector<boost::shared_ptr<binary_classifier<la_type> > > base_classifiers; //! Thresholds for base classifiers std::vector<double> thresholds; // Protected methods //========================================================================== void init(const dataset<la_type>& rare_ds); //! Advance the oracle to the next example which is misclassified. //! @return true iff a valid next example has been found bool next_example(); // Constructors and destructors //========================================================================== public: /** * Constructor for a cascade of binary classifiers without associated data; * useful for: * - creating other instances * - loading a saved cascade * @param params algorithm parameters */ explicit classifier_cascade(parameters params) : params(params), base_ds(), rare_ds_size(0), ds_o_ptr(new ds_oracle<la_type>(base_ds)), common_o(*ds_o_ptr) { } /** * Constructor for a cascade of binary classifiers. * @param rare_ds dataset for rare class * @param common_o oracle for common class * @param params algorithm parameters */ classifier_cascade(const dataset<la_type>& rare_ds, oracle<la_type>& common_o, parameters params) : base(rare_ds), params(params), base_ds(rare_ds.datasource_info()), rare_ds_size(rare_ds.size()), ds_o_ptr(NULL), common_o(common_o) { assert(rare_ds.is_weighted() == false); init(rare_ds); } ~classifier_cascade() { if (ds_o_ptr != NULL) delete(ds_o_ptr); } //! Warning: This should not be used for this class! boost::shared_ptr<binary_classifier<la_type> > create(dataset_statistics<la_type>& stats) const { assert(false); return boost::shared_ptr<binary_classifier<la_type> >(); } //! Warning: This should not be used for this class! boost::shared_ptr<binary_classifier<la_type> > create(oracle<la_type>& o, size_t n) const { assert(false); return boost::shared_ptr<binary_classifier<la_type> >(); } // Getters and helpers //========================================================================== //! Return a name for the algorithm without template parameters. std::string name() const { return "classifier_cascade"; } //! Return a name for the algorithm with comma-separated template parameters //! (e.g., objective). std::string fullname() const { return name(); } //! Returns true iff learner is naturally an online learner. bool is_online() const { return false; } //! Returns the current iteration number (from 0) //! (i.e., the number of boosting iterations completed). size_t iteration() const { return base_classifiers.size(); } //! Computes the accuracy after each iteration on a test set. std::vector<double> test_accuracies(const dataset<la_type>& testds) const { assert(false); } // Learning and mutating operations //========================================================================== //! Reset the random seed in this algorithm's parameters and in its //! random number generator. void random_seed(double value) { params.random_seed = value; rng.seed(static_cast<unsigned>(value)); } //! Train the next level of the cascade. //! @return false iff the cascade may not be trained further bool step(); // Prediction methods //========================================================================== //! Predict the 0/1 label of a new example. std::size_t predict(const assignment& example) const; //! Predict the 0/1 label of a new example. std::size_t predict(const record_type& example) const; // Save and load methods //========================================================================== using base::save; using base::load; //! Output the learner to a human-readable file which can be reloaded. //! @param save_part 0: save function (default), 1: engine, 2: shell //! @param save_name If true, this saves the name of the learner. void save(std::ofstream& out, size_t save_part = 0, bool save_name = true) const; /** * Input the classifier from a human-readable file. * @param in input filestream for file holding the saved learner * @param ds datasource used to get variables * @param load_part 0: load function (default), 1: engine, 2: shell * This assumes that the learner name has already been checked. * @return true if successful */ bool load(std::ifstream& in, const datasource& ds, size_t load_part); }; // class classifier_cascade } // namespace sill #include <sill/macros_undef.hpp> #endif // #ifndef SILL_LEARNING_DISCRIMINATIVE_CLASSIFIER_CASCADE_HPP <commit_msg>size_t conversion in classifier_cascade<commit_after> #ifndef SILL_LEARNING_DISCRIMINATIVE_CLASSIFIER_CASCADE_HPP #define SILL_LEARNING_DISCRIMINATIVE_CLASSIFIER_CASCADE_HPP #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int.hpp> #include <sill/learning/dataset/ds_oracle.hpp> #include <sill/learning/dataset/vector_dataset.hpp> #include <sill/learning/discriminative/binary_classifier.hpp> #include <sill/math/statistics.hpp> #include <sill/stl_io.hpp> #include <sill/macros_def.hpp> // set to 1 to print debugging information #define DEBUG_CLASSIFIER_CASCADE 1 namespace sill { struct classifier_cascade_parameters { typedef dense_linear_algebra<> la_type; /** * Empty classifiers to use to construct the base classifiers. The * parameters from these classifiers are used for the base classifiers, * save for random seeds, which are generated by the cascade classifier. * If the number of base classifiers becomes > BASE_CLASSIFIERS.size(), * then the last classifier from BASE_CLASSIFIERS is used to construct * the extra base classifiers. * (required) */ std::vector<boost::shared_ptr<binary_classifier<la_type> > > base_classifiers; //! Initial number of base classifiers to build. //! (default = 0) size_t init_base_classifiers; //! Label/class which is rare //! (required) size_t rare_class; /** * Max misclassification rate for the * rare class for each level of the cascade * (If RARE_CLASS = 0, this is the false positive rate; * if RARE_CLASS = 1, this is the false negative rate.) * This should be fairly high (say .95 to .99). * (required) */ double max_false_common_rate; //! Number of training examples to pass to the base dataset, //! including all examples from the rare class. //! (default = 2 * number of examples in rare class) size_t base_dataset_size; //! Used to make the algorithm deterministic //! (default = time) double random_seed; /** * Max number of examples which can be thrown * out to generate one example from the common class. * This resets to the default if it has value 0. * (default = 100 / (1 - MAX_FALSE_COMMON_RATE), or * = 100000 if the rate is 1) * @todo MAX_FILTER_COUNT should be set more intelligently. */ size_t max_filter_count; classifier_cascade_parameters() : base_classifiers(), init_base_classifiers(0), rare_class(2), max_false_common_rate(2), base_dataset_size(0), max_filter_count(0) { std::time_t time_tmp; time(&time_tmp); random_seed = time_tmp; } bool valid() const { if (rare_class != 0 && rare_class != 1) return false; if (max_false_common_rate < 0 || max_false_common_rate > 1) return false; return true; } void set_check_params(size_t n_rare_exs) { if (base_dataset_size == 0) { // then set to default base_dataset_size = 2 * n_rare_exs; } else assert(base_dataset_size > n_rare_exs); if (max_filter_count == 0) { // then set to default if (max_false_common_rate == 1) max_filter_count = 100000; else max_filter_count = (size_t)(100 / (1. - max_false_common_rate)); } } void save(std::ofstream& out) const { out << base_classifiers.size() << " " << init_base_classifiers << " " << rare_class << " " << max_false_common_rate << " " << base_dataset_size << " " << random_seed << " " << max_filter_count << "\n"; for (size_t t = 0; t < base_classifiers.size(); ++t) base_classifiers[t]->save(out); } void load(std::ifstream& in, const datasource& ds); }; // class classifier_cascade_parameters /** * Cascade of increasingly complex/accurate binary classifiers, useful * for rapid classification with highly imbalanced classes. * * This is based on the cascades used by Viola and Jones for face detection. * The classifier cascade is given a range of empty binary classifiers, * and it trains these iteratively on a combination of examples from a fixed * set and of examples generated from a given oracle. The examples from * the oracle are passed through a classifier_filter_oracle which can, e.g., * only select examples which the current cascade misclassifies. * * At test time, the cascade works as follows: * - The test example is given to the first classifier. * - The first classifier's predict_raw() value is compared to * a threshold (chosen at training time). * - If the rare class is 1 (0), then if predict_raw() is greater (less) * than this threshold, then the example is passed to the next classifier * in the cascade. Otherwise, it is classified as 0 (1). * * At training time, the cascade: * - Builds a dataset using a fixed set of examples (which should be * examples from the rare class) and new examples from an oracle (which * should provide examples from the common class) * - Trains the first base classifier * - Chooses a threshold such that, if the rare class is 1 (0), * using the prediction rule * (base_classifier.predict_raw() > threshold ? 1 : 0) * gives a low false negative (positive) rate. * - Iterates, training the next base classifiers in the same way. * In the following iterations, though, the examples from the oracle * are filtered such that only examples which are misclassified by the * current set of cascades are accepted. * * NOTE: This must be used with a margin-based classifier. * * \author Joseph Bradley * \ingroup learning_discriminative * @todo serialization */ class classifier_cascade : public binary_classifier<dense_linear_algebra<> > { // Public types //========================================================================== public: typedef dense_linear_algebra<> la_type; typedef binary_classifier<la_type> base; typedef base::record_type record_type; typedef classifier_cascade_parameters parameters; // Protected data members //========================================================================== protected: parameters params; // copied from params: size_t max_filter_count_; //! random number generator boost::mt11213b rng; //! Dataset to be passed to base learners //! The first fixed_ds_size examples are from the fixed dataset, //! and the remaining ones are from the oracle. vector_dataset<la_type> base_ds; //! Number of rare class examples permanently stored in base_ds. size_t rare_ds_size; //! for constructing an empty classifier_cascade ds_oracle<la_type>* ds_o_ptr; //! Oracle for common class oracle<la_type>& common_o; //! Used for choosing a threshold (and avoiding reallocation) vec base_ds_preds; //! Base classifiers std::vector<boost::shared_ptr<binary_classifier<la_type> > > base_classifiers; //! Thresholds for base classifiers std::vector<double> thresholds; // Protected methods //========================================================================== void init(const dataset<la_type>& rare_ds); //! Advance the oracle to the next example which is misclassified. //! @return true iff a valid next example has been found bool next_example(); // Constructors and destructors //========================================================================== public: /** * Constructor for a cascade of binary classifiers without associated data; * useful for: * - creating other instances * - loading a saved cascade * @param params algorithm parameters */ explicit classifier_cascade(parameters params) : params(params), base_ds(), rare_ds_size(0), ds_o_ptr(new ds_oracle<la_type>(base_ds)), common_o(*ds_o_ptr) { } /** * Constructor for a cascade of binary classifiers. * @param rare_ds dataset for rare class * @param common_o oracle for common class * @param params algorithm parameters */ classifier_cascade(const dataset<la_type>& rare_ds, oracle<la_type>& common_o, parameters params) : base(rare_ds), params(params), base_ds(rare_ds.datasource_info()), rare_ds_size(rare_ds.size()), ds_o_ptr(NULL), common_o(common_o) { assert(rare_ds.is_weighted() == false); init(rare_ds); } ~classifier_cascade() { if (ds_o_ptr != NULL) delete(ds_o_ptr); } //! Warning: This should not be used for this class! boost::shared_ptr<binary_classifier<la_type> > create(dataset_statistics<la_type>& stats) const { assert(false); return boost::shared_ptr<binary_classifier<la_type> >(); } //! Warning: This should not be used for this class! boost::shared_ptr<binary_classifier<la_type> > create(oracle<la_type>& o, size_t n) const { assert(false); return boost::shared_ptr<binary_classifier<la_type> >(); } // Getters and helpers //========================================================================== //! Return a name for the algorithm without template parameters. std::string name() const { return "classifier_cascade"; } //! Return a name for the algorithm with comma-separated template parameters //! (e.g., objective). std::string fullname() const { return name(); } //! Returns true iff learner is naturally an online learner. bool is_online() const { return false; } //! Returns the current iteration number (from 0) //! (i.e., the number of boosting iterations completed). size_t iteration() const { return base_classifiers.size(); } //! Computes the accuracy after each iteration on a test set. std::vector<double> test_accuracies(const dataset<la_type>& testds) const { assert(false); } // Learning and mutating operations //========================================================================== //! Reset the random seed in this algorithm's parameters and in its //! random number generator. void random_seed(double value) { params.random_seed = value; rng.seed(static_cast<unsigned>(value)); } //! Train the next level of the cascade. //! @return false iff the cascade may not be trained further bool step(); // Prediction methods //========================================================================== //! Predict the 0/1 label of a new example. std::size_t predict(const assignment& example) const; //! Predict the 0/1 label of a new example. std::size_t predict(const record_type& example) const; // Save and load methods //========================================================================== using base::save; using base::load; //! Output the learner to a human-readable file which can be reloaded. //! @param save_part 0: save function (default), 1: engine, 2: shell //! @param save_name If true, this saves the name of the learner. void save(std::ofstream& out, size_t save_part = 0, bool save_name = true) const; /** * Input the classifier from a human-readable file. * @param in input filestream for file holding the saved learner * @param ds datasource used to get variables * @param load_part 0: load function (default), 1: engine, 2: shell * This assumes that the learner name has already been checked. * @return true if successful */ bool load(std::ifstream& in, const datasource& ds, size_t load_part); }; // class classifier_cascade } // namespace sill #include <sill/macros_undef.hpp> #endif // #ifndef SILL_LEARNING_DISCRIMINATIVE_CLASSIFIER_CASCADE_HPP <|endoftext|>
<commit_before>#include "falconn/lsh_nn_table.h" #include <memory> #include <utility> #include <vector> #include "gtest/gtest.h" using falconn::compute_number_of_hash_functions; using falconn::construct_table; using falconn::DenseVector; using falconn::DistanceFunction; using falconn::LSHConstructionParameters; using falconn::LSHFamily; using falconn::LSHNearestNeighborTable; using falconn::get_default_parameters; using falconn::SparseVector; using falconn::StorageHashTable; using std::make_pair; using std::unique_ptr; using std::vector; TEST(WrapperTest, DenseHPTest1) { int dim = 4; typedef DenseVector<float> Point; LSHConstructionParameters params; params.dimension = dim; params.lsh_family = LSHFamily::Hyperplane; params.distance_function = DistanceFunction::NegativeInnerProduct; params.storage_hash_table = StorageHashTable::BitPackedFlatHashTable; params.k = 2; params.l = 4; Point p1(dim); p1[0] = 1.0; p1[1] = 0.0; p1[2] = 0.0; p1[3] = 0.0; Point p2(dim); p2[0] = 0.6; p2[1] = 0.8; p2[2] = 0.0; p2[3] = 0.0; Point p3(dim); p3[0] = 0.0; p3[1] = 0.0; p3[2] = 1.0; p3[3] = 0.0; vector<Point> points; points.push_back(p1); points.push_back(p2); points.push_back(p3); unique_ptr<LSHNearestNeighborTable<Point>> table(std::move( construct_table<Point>(points, params))); int32_t res1 = table->find_nearest_neighbor(p1); EXPECT_EQ(0, res1); int32_t res2 = table->find_nearest_neighbor(p2); EXPECT_EQ(1, res2); int32_t res3 = table->find_nearest_neighbor(p3); EXPECT_EQ(2, res3); Point p4(dim); p4[0] = 0.0; p4[1] = 1.0; p4[2] = 0.0; p4[3] = 0.0; int32_t res4 = table->find_nearest_neighbor(p4); EXPECT_EQ(1, res4); } TEST(WrapperTest, DenseCPTest1) { int dim = 4; typedef DenseVector<float> Point; LSHConstructionParameters params; params.dimension = dim; params.lsh_family = LSHFamily::CrossPolytope; params.distance_function = DistanceFunction::NegativeInnerProduct; params.storage_hash_table = StorageHashTable::BitPackedFlatHashTable; params.k = 2; params.l = 8; params.last_cp_dimension = dim; params.num_rotations = 3; Point p1(dim); p1[0] = 1.0; p1[1] = 0.0; p1[2] = 0.0; p1[3] = 0.0; Point p2(dim); p2[0] = 0.6; p2[1] = 0.8; p2[2] = 0.0; p2[3] = 0.0; Point p3(dim); p3[0] = 0.0; p3[1] = 0.0; p3[2] = 1.0; p3[3] = 0.0; vector<Point> points; points.push_back(p1); points.push_back(p2); points.push_back(p3); unique_ptr<LSHNearestNeighborTable<Point>> table(std::move( construct_table<Point>(points, params))); int32_t res1 = table->find_nearest_neighbor(p1); EXPECT_EQ(0, res1); int32_t res2 = table->find_nearest_neighbor(p2); EXPECT_EQ(1, res2); int32_t res3 = table->find_nearest_neighbor(p3); EXPECT_EQ(2, res3); Point p4(dim); p4[0] = 0.0; p4[1] = 1.0; p4[2] = 0.0; p4[3] = 0.0; int32_t res4 = table->find_nearest_neighbor(p4); EXPECT_EQ(1, res4); } TEST(WrapperTest, SparseHPTest1) { int dim = 100; typedef SparseVector<float> Point; LSHConstructionParameters params; params.dimension = dim; params.lsh_family = LSHFamily::Hyperplane; params.distance_function = DistanceFunction::NegativeInnerProduct; params.storage_hash_table = StorageHashTable::BitPackedFlatHashTable; params.k = 2; params.l = 4; Point p1; p1.push_back(make_pair(24, 1.0)); Point p2; p2.push_back(make_pair(7, 0.8)); p2.push_back(make_pair(24, 0.6)); Point p3; p3.push_back(make_pair(50, 1.0)); vector<Point> points; points.push_back(p1); points.push_back(p2); points.push_back(p3); unique_ptr<LSHNearestNeighborTable<Point>> table(std::move( construct_table<Point>(points, params))); int32_t res1 = table->find_nearest_neighbor(p1); EXPECT_EQ(0, res1); int32_t res2 = table->find_nearest_neighbor(p2); EXPECT_EQ(1, res2); int32_t res3 = table->find_nearest_neighbor(p3); EXPECT_EQ(2, res3); Point p4; p4.push_back(make_pair(7, 1.0)); int32_t res4 = table->find_nearest_neighbor(p4); EXPECT_EQ(1, res4); } TEST(WrapperTest, SparseCPTest1) { int dim = 100; typedef SparseVector<float> Point; LSHConstructionParameters params; params.dimension = dim; params.lsh_family = LSHFamily::CrossPolytope; params.distance_function = DistanceFunction::NegativeInnerProduct; params.storage_hash_table = StorageHashTable::BitPackedFlatHashTable; params.k = 2; params.l = 4; params.feature_hashing_dimension = 8; params.last_cp_dimension = 8; params.num_rotations = 3; Point p1; p1.push_back(make_pair(24, 1.0)); Point p2; p2.push_back(make_pair(7, 0.8)); p2.push_back(make_pair(24, 0.6)); Point p3; p3.push_back(make_pair(50, 1.0)); vector<Point> points; points.push_back(p1); points.push_back(p2); points.push_back(p3); unique_ptr<LSHNearestNeighborTable<Point>> table(std::move( construct_table<Point>(points, params))); int32_t res1 = table->find_nearest_neighbor(p1); EXPECT_EQ(0, res1); int32_t res2 = table->find_nearest_neighbor(p2); EXPECT_EQ(1, res2); int32_t res3 = table->find_nearest_neighbor(p3); EXPECT_EQ(2, res3); //printf("LAST QUERY\n"); Point p4; p4.push_back(make_pair(7, 1.0)); int32_t res4 = table->find_nearest_neighbor(p4); EXPECT_EQ(1, res4); } TEST(WrapperTest, ComputeNumberOfHashFunctionsTest) { typedef DenseVector<float> VecDense; typedef SparseVector<float> VecSparse; LSHConstructionParameters params; params.dimension = 10; params.lsh_family = LSHFamily::Hyperplane; compute_number_of_hash_functions<VecDense>(5, &params); EXPECT_EQ(5, params.k); params.lsh_family = LSHFamily::CrossPolytope; compute_number_of_hash_functions<VecDense>(5, &params); EXPECT_EQ(1, params.k); EXPECT_EQ(16, params.last_cp_dimension); params.dimension = 100; params.lsh_family = LSHFamily::Hyperplane; compute_number_of_hash_functions<VecSparse>(8, &params); EXPECT_EQ(8, params.k); params.lsh_family = LSHFamily::CrossPolytope; params.feature_hashing_dimension = 32; compute_number_of_hash_functions<VecSparse>(9, &params); EXPECT_EQ(2, params.k); EXPECT_EQ(4, params.last_cp_dimension); } TEST(WrapperTest, GetDefaultParametersTest1) { typedef DenseVector<float> Vec; LSHConstructionParameters params = get_default_parameters<Vec>(1000000, 128, DistanceFunction::NegativeInnerProduct, true); EXPECT_EQ(1, params.num_rotations); EXPECT_EQ(-1, params.feature_hashing_dimension); EXPECT_EQ(10, params.l); EXPECT_EQ(128, params.dimension); EXPECT_EQ(DistanceFunction::NegativeInnerProduct, params.distance_function); EXPECT_EQ(LSHFamily::CrossPolytope, params.lsh_family); EXPECT_EQ(3, params.k); EXPECT_EQ(2, params.last_cp_dimension); } TEST(WrapperTest, GetDefaultParametersTest2) { typedef SparseVector<float> Vec; LSHConstructionParameters params = get_default_parameters<Vec>(1000000, 100000, DistanceFunction::NegativeInnerProduct, true); EXPECT_EQ(2, params.num_rotations); EXPECT_EQ(1024, params.feature_hashing_dimension); } <commit_msg>adding unit tests for new hash table setup code paths<commit_after>#include "falconn/lsh_nn_table.h" #include <memory> #include <utility> #include <vector> #include "gtest/gtest.h" using falconn::compute_number_of_hash_functions; using falconn::construct_table; using falconn::DenseVector; using falconn::DistanceFunction; using falconn::LSHConstructionParameters; using falconn::LSHFamily; using falconn::LSHNearestNeighborTable; using falconn::get_default_parameters; using falconn::SparseVector; using falconn::StorageHashTable; using std::make_pair; using std::unique_ptr; using std::vector; // Point dimension is 4 void basic_test_dense_1(const LSHConstructionParameters& params) { typedef DenseVector<float> Point; int dim = 4; Point p1(dim); p1[0] = 1.0; p1[1] = 0.0; p1[2] = 0.0; p1[3] = 0.0; Point p2(dim); p2[0] = 0.6; p2[1] = 0.8; p2[2] = 0.0; p2[3] = 0.0; Point p3(dim); p3[0] = 0.0; p3[1] = 0.0; p3[2] = 1.0; p3[3] = 0.0; vector<Point> points; points.push_back(p1); points.push_back(p2); points.push_back(p3); unique_ptr<LSHNearestNeighborTable<Point>> table(std::move( construct_table<Point>(points, params))); int32_t res1 = table->find_nearest_neighbor(p1); EXPECT_EQ(0, res1); int32_t res2 = table->find_nearest_neighbor(p2); EXPECT_EQ(1, res2); int32_t res3 = table->find_nearest_neighbor(p3); EXPECT_EQ(2, res3); Point p4(dim); p4[0] = 0.0; p4[1] = 1.0; p4[2] = 0.0; p4[3] = 0.0; int32_t res4 = table->find_nearest_neighbor(p4); EXPECT_EQ(1, res4); } void basic_test_sparse_1(const LSHConstructionParameters& params) { typedef SparseVector<float> Point; Point p1; p1.push_back(make_pair(24, 1.0)); Point p2; p2.push_back(make_pair(7, 0.8)); p2.push_back(make_pair(24, 0.6)); Point p3; p3.push_back(make_pair(50, 1.0)); vector<Point> points; points.push_back(p1); points.push_back(p2); points.push_back(p3); unique_ptr<LSHNearestNeighborTable<Point>> table(std::move( construct_table<Point>(points, params))); int32_t res1 = table->find_nearest_neighbor(p1); EXPECT_EQ(0, res1); int32_t res2 = table->find_nearest_neighbor(p2); EXPECT_EQ(1, res2); int32_t res3 = table->find_nearest_neighbor(p3); EXPECT_EQ(2, res3); Point p4; p4.push_back(make_pair(7, 1.0)); int32_t res4 = table->find_nearest_neighbor(p4); EXPECT_EQ(1, res4); } TEST(WrapperTest, DenseHPTest1) { int dim = 4; LSHConstructionParameters params; params.dimension = dim; params.lsh_family = LSHFamily::Hyperplane; params.distance_function = DistanceFunction::NegativeInnerProduct; params.storage_hash_table = StorageHashTable::BitPackedFlatHashTable; params.k = 2; params.l = 4; basic_test_dense_1(params); } TEST(WrapperTest, DenseCPTest1) { int dim = 4; LSHConstructionParameters params; params.dimension = dim; params.lsh_family = LSHFamily::CrossPolytope; params.distance_function = DistanceFunction::NegativeInnerProduct; params.storage_hash_table = StorageHashTable::BitPackedFlatHashTable; params.k = 2; params.l = 8; params.last_cp_dimension = dim; params.num_rotations = 3; basic_test_dense_1(params); } TEST(WrapperTest, SparseHPTest1) { int dim = 100; LSHConstructionParameters params; params.dimension = dim; params.lsh_family = LSHFamily::Hyperplane; params.distance_function = DistanceFunction::NegativeInnerProduct; params.storage_hash_table = StorageHashTable::BitPackedFlatHashTable; params.k = 2; params.l = 4; basic_test_sparse_1(params); } TEST(WrapperTest, SparseCPTest1) { int dim = 100; LSHConstructionParameters params; params.dimension = dim; params.lsh_family = LSHFamily::CrossPolytope; params.distance_function = DistanceFunction::NegativeInnerProduct; params.storage_hash_table = StorageHashTable::BitPackedFlatHashTable; params.k = 2; params.l = 4; params.feature_hashing_dimension = 8; params.last_cp_dimension = 8; params.num_rotations = 3; basic_test_sparse_1(params); } TEST(WrapperTest, FlatHashTableTest1) { int dim = 4; LSHConstructionParameters params; params.dimension = dim; params.lsh_family = LSHFamily::Hyperplane; params.distance_function = DistanceFunction::NegativeInnerProduct; params.storage_hash_table = StorageHashTable::FlatHashTable; params.k = 2; params.l = 4; basic_test_dense_1(params); } TEST(WrapperTest, BitPackedFlatHashTableTest1) { int dim = 4; LSHConstructionParameters params; params.dimension = dim; params.lsh_family = LSHFamily::Hyperplane; params.distance_function = DistanceFunction::NegativeInnerProduct; params.storage_hash_table = StorageHashTable::BitPackedFlatHashTable; params.k = 2; params.l = 4; basic_test_dense_1(params); } TEST(WrapperTest, STLHashTableTest1) { int dim = 4; LSHConstructionParameters params; params.dimension = dim; params.lsh_family = LSHFamily::Hyperplane; params.distance_function = DistanceFunction::NegativeInnerProduct; params.storage_hash_table = StorageHashTable::STLHashTable; params.k = 2; params.l = 4; basic_test_dense_1(params); } TEST(WrapperTest, LinearProbingHashTableTest1) { int dim = 4; LSHConstructionParameters params; params.dimension = dim; params.lsh_family = LSHFamily::Hyperplane; params.distance_function = DistanceFunction::NegativeInnerProduct; params.storage_hash_table = StorageHashTable::LinearProbingHashTable; params.k = 2; params.l = 4; basic_test_dense_1(params); } TEST(WrapperTest, ComputeNumberOfHashFunctionsTest) { typedef DenseVector<float> VecDense; typedef SparseVector<float> VecSparse; LSHConstructionParameters params; params.dimension = 10; params.lsh_family = LSHFamily::Hyperplane; compute_number_of_hash_functions<VecDense>(5, &params); EXPECT_EQ(5, params.k); params.lsh_family = LSHFamily::CrossPolytope; compute_number_of_hash_functions<VecDense>(5, &params); EXPECT_EQ(1, params.k); EXPECT_EQ(16, params.last_cp_dimension); params.dimension = 100; params.lsh_family = LSHFamily::Hyperplane; compute_number_of_hash_functions<VecSparse>(8, &params); EXPECT_EQ(8, params.k); params.lsh_family = LSHFamily::CrossPolytope; params.feature_hashing_dimension = 32; compute_number_of_hash_functions<VecSparse>(9, &params); EXPECT_EQ(2, params.k); EXPECT_EQ(4, params.last_cp_dimension); } TEST(WrapperTest, GetDefaultParametersTest1) { typedef DenseVector<float> Vec; LSHConstructionParameters params = get_default_parameters<Vec>(1000000, 128, DistanceFunction::NegativeInnerProduct, true); EXPECT_EQ(1, params.num_rotations); EXPECT_EQ(-1, params.feature_hashing_dimension); EXPECT_EQ(10, params.l); EXPECT_EQ(128, params.dimension); EXPECT_EQ(DistanceFunction::NegativeInnerProduct, params.distance_function); EXPECT_EQ(LSHFamily::CrossPolytope, params.lsh_family); EXPECT_EQ(3, params.k); EXPECT_EQ(2, params.last_cp_dimension); } TEST(WrapperTest, GetDefaultParametersTest2) { typedef SparseVector<float> Vec; LSHConstructionParameters params = get_default_parameters<Vec>(1000000, 100000, DistanceFunction::NegativeInnerProduct, true); EXPECT_EQ(2, params.num_rotations); EXPECT_EQ(1024, params.feature_hashing_dimension); } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/range/irange.hpp> #include <seastar/util/defer.hh> #include <seastar/core/app-template.hh> #include <seastar/core/thread.hh> #include "partition_slice_builder.hh" #include "schema_builder.hh" #include "memtable.hh" #include "row_cache.hh" #include "frozen_mutation.hh" #include "test/lib/tmpdir.hh" #include "sstables/sstables.hh" #include "canonical_mutation.hh" #include "test/lib/sstable_utils.hh" #include "test/lib/test_services.hh" #include "test/lib/sstable_test_env.hh" #include "test/lib/cql_test_env.hh" #include "test/lib/reader_permit.hh" class size_calculator { class nest { public: static thread_local int level; nest() { ++level; } ~nest() { --level; } }; static std::string prefix() { std::string s(" "); for (int i = 0; i < nest::level; ++i) { s += "-- "; } return s; } public: static void print_cache_entry_size() { std::cout << prefix() << "sizeof(cache_entry) = " << sizeof(cache_entry) << "\n"; std::cout << prefix() << "sizeof(memtable_entry) = " << sizeof(memtable_entry) << "\n"; std::cout << prefix() << "sizeof(bptree::node) = " << sizeof(row_cache::partitions_type::outer_tree::node) << "\n"; std::cout << prefix() << "sizeof(bptree::data) = " << sizeof(row_cache::partitions_type::outer_tree::data) << "\n"; { nest n; std::cout << prefix() << "sizeof(decorated_key) = " << sizeof(dht::decorated_key) << "\n"; print_mutation_partition_size(); } std::cout << "\n"; std::cout << prefix() << "sizeof(rows_entry) = " << sizeof(rows_entry) << "\n"; std::cout << prefix() << "sizeof(lru_link_type) = " << sizeof(rows_entry::lru_link_type) << "\n"; std::cout << prefix() << "sizeof(deletable_row) = " << sizeof(deletable_row) << "\n"; std::cout << prefix() << "sizeof(row) = " << sizeof(row) << "\n"; std::cout << prefix() << "sizeof(atomic_cell_or_collection) = " << sizeof(atomic_cell_or_collection) << "\n"; } static void print_mutation_partition_size() { std::cout << prefix() << "sizeof(mutation_partition) = " << sizeof(mutation_partition) << "\n"; { nest n; std::cout << prefix() << "sizeof(_static_row) = " << sizeof(mutation_partition::_static_row) << "\n"; std::cout << prefix() << "sizeof(_rows) = " << sizeof(mutation_partition::_rows) << "\n"; std::cout << prefix() << "sizeof(_row_tombstones) = " << sizeof(mutation_partition::_row_tombstones) << "\n"; } } }; thread_local int size_calculator::nest::level = 0; static schema_ptr cassandra_stress_schema() { return schema_builder("ks", "cf") .with_column("KEY", bytes_type, column_kind::partition_key) .with_column("C0", bytes_type) .with_column("C1", bytes_type) .with_column("C2", bytes_type) .with_column("C3", bytes_type) .with_column("C4", bytes_type) .build(); } [[gnu::unused]] static mutation make_cs_mutation() { auto s = cassandra_stress_schema(); mutation m(s, partition_key::from_single_value(*s, bytes_type->from_string("4b343050393536353531"))); for (auto&& col : s->regular_columns()) { m.set_clustered_cell(clustering_key::make_empty(), col, atomic_cell::make_live(*bytes_type, 1, bytes_type->from_string("8f75da6b3dcec90c8a404fb9a5f6b0621e62d39c69ba5758e5f41b78311fbb26cc7a"))); } return m; } bytes random_bytes(size_t size) { bytes result(bytes::initialized_later(), size); for (size_t i = 0; i < size; ++i) { result[i] = std::rand() % std::numeric_limits<uint8_t>::max(); } return result; } sstring random_name(size_t size) { sstring result = uninitialized_string(size); static const char chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for (size_t i = 0; i < size; ++i) { result[i] = chars[std::rand() % sizeof(chars)]; } return result; } struct mutation_settings { size_t column_count; size_t column_name_size; size_t row_count; size_t partition_count; size_t partition_key_size; size_t clustering_key_size; size_t data_size; }; static schema_ptr make_schema(const mutation_settings& settings) { auto builder = schema_builder("ks", "cf") .with_column("pk", bytes_type, column_kind::partition_key) .with_column("ck", bytes_type, column_kind::clustering_key); for (size_t i = 0; i < settings.column_count; ++i) { builder.with_column(to_bytes(random_name(settings.column_name_size)), bytes_type); } return builder.build(); } static mutation make_mutation(schema_ptr s, mutation_settings settings) { mutation m(s, partition_key::from_single_value(*s, bytes_type->decompose(data_value(random_bytes(settings.partition_key_size))))); for (size_t i = 0; i < settings.row_count; ++i) { auto ck = clustering_key::from_single_value(*s, bytes_type->decompose(data_value(random_bytes(settings.clustering_key_size)))); for (auto&& col : s->regular_columns()) { m.set_clustered_cell(ck, col, atomic_cell::make_live(*bytes_type, 1, bytes_type->decompose(data_value(random_bytes(settings.data_size))))); } } return m; } struct sizes { size_t memtable; size_t cache; std::map<sstables::sstable::version_types, size_t> sstable; size_t frozen; size_t canonical; size_t query_result; }; static sizes calculate_sizes(cache_tracker& tracker, const mutation_settings& settings) { sizes result; auto s = make_schema(settings); auto mt = make_lw_shared<memtable>(s); row_cache cache(s, make_empty_snapshot_source(), tracker); auto cache_initial_occupancy = tracker.region().occupancy().used_space(); assert(mt->occupancy().used_space() == 0); std::vector<mutation> muts; for (size_t i = 0; i < settings.partition_count; ++i) { muts.emplace_back(make_mutation(s, settings)); mt->apply(muts.back()); cache.populate(muts.back()); } mutation& m = muts[0]; result.memtable = mt->occupancy().used_space(); result.cache = tracker.region().occupancy().used_space() - cache_initial_occupancy; result.frozen = freeze(m).representation().size(); result.canonical = canonical_mutation(m).representation().size(); result.query_result = query_mutation(mutation(m), partition_slice_builder(*s).build()).buf().size(); tmpdir sstable_dir; sstables::test_env::do_with_async([&] (sstables::test_env& env) { for (auto v : sstables::all_sstable_versions) { auto sst = env.make_sstable(s, sstable_dir.path().string(), 1 /* generation */, v, sstables::sstable::format_types::big); auto mt2 = make_lw_shared<memtable>(s); mt2->apply(*mt, tests::make_permit()).get(); write_memtable_to_sstable_for_test(*mt2, sst).get(); sst->load().get(); result.sstable[v] = sst->data_size(); } }).get(); return result; } int main(int argc, char** argv) { namespace bpo = boost::program_options; app_template app; app.add_options() ("verbose", "Enable info-level logging") ("column-count", bpo::value<size_t>()->default_value(5), "column count") ("column-name-size", bpo::value<size_t>()->default_value(2), "column name size") ("row-count", bpo::value<size_t>()->default_value(1), "row count") ("partition-count", bpo::value<size_t>()->default_value(1), "partition count") ("partition-key-size", bpo::value<size_t>()->default_value(10), "partition key size") ("clustering-key-size", bpo::value<size_t>()->default_value(10), "clustering key size") ("data-size", bpo::value<size_t>()->default_value(32), "cell data size"); return app.run(argc, argv, [&] { if (smp::count != 1) { throw std::runtime_error("This test has to be run with -c1"); } if (!app.configuration().contains("verbose")) { logging::logger_registry().set_all_loggers_level(seastar::log_level::warn); } return do_with_cql_env_thread([&](cql_test_env& env) { mutation_settings settings; settings.column_count = app.configuration()["column-count"].as<size_t>(); settings.column_name_size = app.configuration()["column-name-size"].as<size_t>(); settings.row_count = app.configuration()["row-count"].as<size_t>(); settings.partition_count = app.configuration()["partition-count"].as<size_t>(); settings.partition_key_size = app.configuration()["partition-key-size"].as<size_t>(); settings.clustering_key_size = app.configuration()["clustering-key-size"].as<size_t>(); settings.data_size = app.configuration()["data-size"].as<size_t>(); auto& tracker = env.local_db().find_column_family("system", "local").get_row_cache().get_cache_tracker(); auto sizes = calculate_sizes(tracker, settings); std::cout << "mutation footprint:" << "\n"; std::cout << " - in cache: " << sizes.cache << "\n"; std::cout << " - in memtable: " << sizes.memtable << "\n"; std::cout << " - in sstable:\n"; for (auto v : sizes.sstable) { std::cout << " " << sstables::to_string(v.first) << ": " << v.second << "\n"; } std::cout << " - frozen: " << sizes.frozen << "\n"; std::cout << " - canonical: " << sizes.canonical << "\n"; std::cout << " - query result: " << sizes.query_result << "\n"; std::cout << "\n"; size_calculator::print_cache_entry_size(); }); }); } <commit_msg>perf-test : Print B-tree sizes<commit_after>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <boost/range/irange.hpp> #include <seastar/util/defer.hh> #include <seastar/core/app-template.hh> #include <seastar/core/thread.hh> #include "partition_slice_builder.hh" #include "schema_builder.hh" #include "memtable.hh" #include "row_cache.hh" #include "frozen_mutation.hh" #include "test/lib/tmpdir.hh" #include "sstables/sstables.hh" #include "canonical_mutation.hh" #include "test/lib/sstable_utils.hh" #include "test/lib/test_services.hh" #include "test/lib/sstable_test_env.hh" #include "test/lib/cql_test_env.hh" #include "test/lib/reader_permit.hh" class size_calculator { class nest { public: static thread_local int level; nest() { ++level; } ~nest() { --level; } }; static std::string prefix() { std::string s(" "); for (int i = 0; i < nest::level; ++i) { s += "-- "; } return s; } public: static void print_cache_entry_size() { std::cout << prefix() << "sizeof(cache_entry) = " << sizeof(cache_entry) << "\n"; std::cout << prefix() << "sizeof(memtable_entry) = " << sizeof(memtable_entry) << "\n"; std::cout << prefix() << "sizeof(bptree::node) = " << sizeof(row_cache::partitions_type::outer_tree::node) << "\n"; std::cout << prefix() << "sizeof(bptree::data) = " << sizeof(row_cache::partitions_type::outer_tree::data) << "\n"; { nest n; std::cout << prefix() << "sizeof(decorated_key) = " << sizeof(dht::decorated_key) << "\n"; print_mutation_partition_size(); } std::cout << "\n"; std::cout << prefix() << "sizeof(rows_entry) = " << sizeof(rows_entry) << "\n"; std::cout << prefix() << "sizeof(lru_link_type) = " << sizeof(rows_entry::lru_link_type) << "\n"; std::cout << prefix() << "sizeof(deletable_row) = " << sizeof(deletable_row) << "\n"; std::cout << prefix() << "sizeof(row) = " << sizeof(row) << "\n"; std::cout << prefix() << "sizeof(atomic_cell_or_collection) = " << sizeof(atomic_cell_or_collection) << "\n"; std::cout << prefix() << "btree::linear_node_size(1) = " << mutation_partition::rows_type::node::linear_node_size(1) << "\n"; std::cout << prefix() << "btree::inner_node_size = " << mutation_partition::rows_type::node::inner_node_size << "\n"; std::cout << prefix() << "btree::leaf_node_size = " << mutation_partition::rows_type::node::leaf_node_size << "\n"; } static void print_mutation_partition_size() { std::cout << prefix() << "sizeof(mutation_partition) = " << sizeof(mutation_partition) << "\n"; { nest n; std::cout << prefix() << "sizeof(_static_row) = " << sizeof(mutation_partition::_static_row) << "\n"; std::cout << prefix() << "sizeof(_rows) = " << sizeof(mutation_partition::_rows) << "\n"; std::cout << prefix() << "sizeof(_row_tombstones) = " << sizeof(mutation_partition::_row_tombstones) << "\n"; } } }; thread_local int size_calculator::nest::level = 0; static schema_ptr cassandra_stress_schema() { return schema_builder("ks", "cf") .with_column("KEY", bytes_type, column_kind::partition_key) .with_column("C0", bytes_type) .with_column("C1", bytes_type) .with_column("C2", bytes_type) .with_column("C3", bytes_type) .with_column("C4", bytes_type) .build(); } [[gnu::unused]] static mutation make_cs_mutation() { auto s = cassandra_stress_schema(); mutation m(s, partition_key::from_single_value(*s, bytes_type->from_string("4b343050393536353531"))); for (auto&& col : s->regular_columns()) { m.set_clustered_cell(clustering_key::make_empty(), col, atomic_cell::make_live(*bytes_type, 1, bytes_type->from_string("8f75da6b3dcec90c8a404fb9a5f6b0621e62d39c69ba5758e5f41b78311fbb26cc7a"))); } return m; } bytes random_bytes(size_t size) { bytes result(bytes::initialized_later(), size); for (size_t i = 0; i < size; ++i) { result[i] = std::rand() % std::numeric_limits<uint8_t>::max(); } return result; } sstring random_name(size_t size) { sstring result = uninitialized_string(size); static const char chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for (size_t i = 0; i < size; ++i) { result[i] = chars[std::rand() % sizeof(chars)]; } return result; } struct mutation_settings { size_t column_count; size_t column_name_size; size_t row_count; size_t partition_count; size_t partition_key_size; size_t clustering_key_size; size_t data_size; }; static schema_ptr make_schema(const mutation_settings& settings) { auto builder = schema_builder("ks", "cf") .with_column("pk", bytes_type, column_kind::partition_key) .with_column("ck", bytes_type, column_kind::clustering_key); for (size_t i = 0; i < settings.column_count; ++i) { builder.with_column(to_bytes(random_name(settings.column_name_size)), bytes_type); } return builder.build(); } static mutation make_mutation(schema_ptr s, mutation_settings settings) { mutation m(s, partition_key::from_single_value(*s, bytes_type->decompose(data_value(random_bytes(settings.partition_key_size))))); for (size_t i = 0; i < settings.row_count; ++i) { auto ck = clustering_key::from_single_value(*s, bytes_type->decompose(data_value(random_bytes(settings.clustering_key_size)))); for (auto&& col : s->regular_columns()) { m.set_clustered_cell(ck, col, atomic_cell::make_live(*bytes_type, 1, bytes_type->decompose(data_value(random_bytes(settings.data_size))))); } } return m; } struct sizes { size_t memtable; size_t cache; std::map<sstables::sstable::version_types, size_t> sstable; size_t frozen; size_t canonical; size_t query_result; }; static sizes calculate_sizes(cache_tracker& tracker, const mutation_settings& settings) { sizes result; auto s = make_schema(settings); auto mt = make_lw_shared<memtable>(s); row_cache cache(s, make_empty_snapshot_source(), tracker); auto cache_initial_occupancy = tracker.region().occupancy().used_space(); assert(mt->occupancy().used_space() == 0); std::vector<mutation> muts; for (size_t i = 0; i < settings.partition_count; ++i) { muts.emplace_back(make_mutation(s, settings)); mt->apply(muts.back()); cache.populate(muts.back()); } mutation& m = muts[0]; result.memtable = mt->occupancy().used_space(); result.cache = tracker.region().occupancy().used_space() - cache_initial_occupancy; result.frozen = freeze(m).representation().size(); result.canonical = canonical_mutation(m).representation().size(); result.query_result = query_mutation(mutation(m), partition_slice_builder(*s).build()).buf().size(); tmpdir sstable_dir; sstables::test_env::do_with_async([&] (sstables::test_env& env) { for (auto v : sstables::all_sstable_versions) { auto sst = env.make_sstable(s, sstable_dir.path().string(), 1 /* generation */, v, sstables::sstable::format_types::big); auto mt2 = make_lw_shared<memtable>(s); mt2->apply(*mt, tests::make_permit()).get(); write_memtable_to_sstable_for_test(*mt2, sst).get(); sst->load().get(); result.sstable[v] = sst->data_size(); } }).get(); return result; } int main(int argc, char** argv) { namespace bpo = boost::program_options; app_template app; app.add_options() ("verbose", "Enable info-level logging") ("column-count", bpo::value<size_t>()->default_value(5), "column count") ("column-name-size", bpo::value<size_t>()->default_value(2), "column name size") ("row-count", bpo::value<size_t>()->default_value(1), "row count") ("partition-count", bpo::value<size_t>()->default_value(1), "partition count") ("partition-key-size", bpo::value<size_t>()->default_value(10), "partition key size") ("clustering-key-size", bpo::value<size_t>()->default_value(10), "clustering key size") ("data-size", bpo::value<size_t>()->default_value(32), "cell data size"); return app.run(argc, argv, [&] { if (smp::count != 1) { throw std::runtime_error("This test has to be run with -c1"); } if (!app.configuration().contains("verbose")) { logging::logger_registry().set_all_loggers_level(seastar::log_level::warn); } return do_with_cql_env_thread([&](cql_test_env& env) { mutation_settings settings; settings.column_count = app.configuration()["column-count"].as<size_t>(); settings.column_name_size = app.configuration()["column-name-size"].as<size_t>(); settings.row_count = app.configuration()["row-count"].as<size_t>(); settings.partition_count = app.configuration()["partition-count"].as<size_t>(); settings.partition_key_size = app.configuration()["partition-key-size"].as<size_t>(); settings.clustering_key_size = app.configuration()["clustering-key-size"].as<size_t>(); settings.data_size = app.configuration()["data-size"].as<size_t>(); auto& tracker = env.local_db().find_column_family("system", "local").get_row_cache().get_cache_tracker(); auto sizes = calculate_sizes(tracker, settings); std::cout << "mutation footprint:" << "\n"; std::cout << " - in cache: " << sizes.cache << "\n"; std::cout << " - in memtable: " << sizes.memtable << "\n"; std::cout << " - in sstable:\n"; for (auto v : sizes.sstable) { std::cout << " " << sstables::to_string(v.first) << ": " << v.second << "\n"; } std::cout << " - frozen: " << sizes.frozen << "\n"; std::cout << " - canonical: " << sizes.canonical << "\n"; std::cout << " - query result: " << sizes.query_result << "\n"; std::cout << "\n"; size_calculator::print_cache_entry_size(); }); }); } <|endoftext|>
<commit_before>// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <netaddress.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <cassert> #include <cstdint> #include <netinet/in.h> #include <vector> namespace { CNetAddr ConsumeNetAddr(FuzzedDataProvider& fuzzed_data_provider) noexcept { const Network network = fuzzed_data_provider.PickValueInArray({Network::NET_IPV4, Network::NET_IPV6, Network::NET_INTERNAL, Network::NET_ONION}); if (network == Network::NET_IPV4) { const in_addr v4_addr = { .s_addr = fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; return CNetAddr{v4_addr}; } else if (network == Network::NET_IPV6) { if (fuzzed_data_provider.remaining_bytes() < 16) { return CNetAddr{}; } in6_addr v6_addr = {}; memcpy(v6_addr.s6_addr, fuzzed_data_provider.ConsumeBytes<uint8_t>(16).data(), 16); return CNetAddr{v6_addr, fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; } else if (network == Network::NET_INTERNAL) { CNetAddr net_addr; net_addr.SetInternal(fuzzed_data_provider.ConsumeBytesAsString(32)); return net_addr; } else if (network == Network::NET_ONION) { CNetAddr net_addr; net_addr.SetSpecial(fuzzed_data_provider.ConsumeBytesAsString(32)); return net_addr; } else { assert(false); } } }; // namespace void test_one_input(const std::vector<uint8_t>& buffer) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const CNetAddr net_addr = ConsumeNetAddr(fuzzed_data_provider); for (int i = 0; i < 15; ++i) { (void)net_addr.GetByte(i); } (void)net_addr.GetHash(); (void)net_addr.GetNetClass(); if (net_addr.GetNetwork() == Network::NET_IPV4) { assert(net_addr.IsIPv4()); } if (net_addr.GetNetwork() == Network::NET_IPV6) { assert(net_addr.IsIPv6()); } if (net_addr.GetNetwork() == Network::NET_ONION) { assert(net_addr.IsTor()); } if (net_addr.GetNetwork() == Network::NET_INTERNAL) { assert(net_addr.IsInternal()); } if (net_addr.GetNetwork() == Network::NET_UNROUTABLE) { assert(!net_addr.IsRoutable()); } (void)net_addr.IsBindAny(); if (net_addr.IsInternal()) { assert(net_addr.GetNetwork() == Network::NET_INTERNAL); } if (net_addr.IsIPv4()) { assert(net_addr.GetNetwork() == Network::NET_IPV4 || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } if (net_addr.IsIPv6()) { assert(net_addr.GetNetwork() == Network::NET_IPV6 || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } (void)net_addr.IsLocal(); if (net_addr.IsRFC1918() || net_addr.IsRFC2544() || net_addr.IsRFC6598() || net_addr.IsRFC5737() || net_addr.IsRFC3927()) { assert(net_addr.IsIPv4()); } (void)net_addr.IsRFC2544(); if (net_addr.IsRFC3849() || net_addr.IsRFC3964() || net_addr.IsRFC4380() || net_addr.IsRFC4843() || net_addr.IsRFC7343() || net_addr.IsRFC4862() || net_addr.IsRFC6052() || net_addr.IsRFC6145()) { assert(net_addr.IsIPv6()); } (void)net_addr.IsRFC3927(); (void)net_addr.IsRFC3964(); if (net_addr.IsRFC4193()) { assert(net_addr.GetNetwork() == Network::NET_ONION || net_addr.GetNetwork() == Network::NET_INTERNAL || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } (void)net_addr.IsRFC4380(); (void)net_addr.IsRFC4843(); (void)net_addr.IsRFC4862(); (void)net_addr.IsRFC5737(); (void)net_addr.IsRFC6052(); (void)net_addr.IsRFC6145(); (void)net_addr.IsRFC6598(); (void)net_addr.IsRFC7343(); if (!net_addr.IsRoutable()) { assert(net_addr.GetNetwork() == Network::NET_UNROUTABLE || net_addr.GetNetwork() == Network::NET_INTERNAL); } if (net_addr.IsTor()) { assert(net_addr.GetNetwork() == Network::NET_ONION); } (void)net_addr.IsValid(); (void)net_addr.ToString(); (void)net_addr.ToStringIP(); const CSubNet sub_net{net_addr, fuzzed_data_provider.ConsumeIntegral<int32_t>()}; (void)sub_net.IsValid(); (void)sub_net.ToString(); const CService service{net_addr, fuzzed_data_provider.ConsumeIntegral<uint16_t>()}; (void)service.GetKey(); (void)service.GetPort(); (void)service.ToString(); (void)service.ToStringIPPort(); (void)service.ToStringPort(); const CNetAddr other_net_addr = ConsumeNetAddr(fuzzed_data_provider); (void)net_addr.GetReachabilityFrom(&other_net_addr); (void)sub_net.Match(other_net_addr); } <commit_msg>tests: Fuzz operator!= of CService<commit_after>// Copyright (c) 2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <netaddress.h> #include <test/fuzz/FuzzedDataProvider.h> #include <test/fuzz/fuzz.h> #include <cassert> #include <cstdint> #include <netinet/in.h> #include <vector> namespace { CNetAddr ConsumeNetAddr(FuzzedDataProvider& fuzzed_data_provider) noexcept { const Network network = fuzzed_data_provider.PickValueInArray({Network::NET_IPV4, Network::NET_IPV6, Network::NET_INTERNAL, Network::NET_ONION}); if (network == Network::NET_IPV4) { const in_addr v4_addr = { .s_addr = fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; return CNetAddr{v4_addr}; } else if (network == Network::NET_IPV6) { if (fuzzed_data_provider.remaining_bytes() < 16) { return CNetAddr{}; } in6_addr v6_addr = {}; memcpy(v6_addr.s6_addr, fuzzed_data_provider.ConsumeBytes<uint8_t>(16).data(), 16); return CNetAddr{v6_addr, fuzzed_data_provider.ConsumeIntegral<uint32_t>()}; } else if (network == Network::NET_INTERNAL) { CNetAddr net_addr; net_addr.SetInternal(fuzzed_data_provider.ConsumeBytesAsString(32)); return net_addr; } else if (network == Network::NET_ONION) { CNetAddr net_addr; net_addr.SetSpecial(fuzzed_data_provider.ConsumeBytesAsString(32)); return net_addr; } else { assert(false); } } }; // namespace void test_one_input(const std::vector<uint8_t>& buffer) { FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); const CNetAddr net_addr = ConsumeNetAddr(fuzzed_data_provider); for (int i = 0; i < 15; ++i) { (void)net_addr.GetByte(i); } (void)net_addr.GetHash(); (void)net_addr.GetNetClass(); if (net_addr.GetNetwork() == Network::NET_IPV4) { assert(net_addr.IsIPv4()); } if (net_addr.GetNetwork() == Network::NET_IPV6) { assert(net_addr.IsIPv6()); } if (net_addr.GetNetwork() == Network::NET_ONION) { assert(net_addr.IsTor()); } if (net_addr.GetNetwork() == Network::NET_INTERNAL) { assert(net_addr.IsInternal()); } if (net_addr.GetNetwork() == Network::NET_UNROUTABLE) { assert(!net_addr.IsRoutable()); } (void)net_addr.IsBindAny(); if (net_addr.IsInternal()) { assert(net_addr.GetNetwork() == Network::NET_INTERNAL); } if (net_addr.IsIPv4()) { assert(net_addr.GetNetwork() == Network::NET_IPV4 || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } if (net_addr.IsIPv6()) { assert(net_addr.GetNetwork() == Network::NET_IPV6 || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } (void)net_addr.IsLocal(); if (net_addr.IsRFC1918() || net_addr.IsRFC2544() || net_addr.IsRFC6598() || net_addr.IsRFC5737() || net_addr.IsRFC3927()) { assert(net_addr.IsIPv4()); } (void)net_addr.IsRFC2544(); if (net_addr.IsRFC3849() || net_addr.IsRFC3964() || net_addr.IsRFC4380() || net_addr.IsRFC4843() || net_addr.IsRFC7343() || net_addr.IsRFC4862() || net_addr.IsRFC6052() || net_addr.IsRFC6145()) { assert(net_addr.IsIPv6()); } (void)net_addr.IsRFC3927(); (void)net_addr.IsRFC3964(); if (net_addr.IsRFC4193()) { assert(net_addr.GetNetwork() == Network::NET_ONION || net_addr.GetNetwork() == Network::NET_INTERNAL || net_addr.GetNetwork() == Network::NET_UNROUTABLE); } (void)net_addr.IsRFC4380(); (void)net_addr.IsRFC4843(); (void)net_addr.IsRFC4862(); (void)net_addr.IsRFC5737(); (void)net_addr.IsRFC6052(); (void)net_addr.IsRFC6145(); (void)net_addr.IsRFC6598(); (void)net_addr.IsRFC7343(); if (!net_addr.IsRoutable()) { assert(net_addr.GetNetwork() == Network::NET_UNROUTABLE || net_addr.GetNetwork() == Network::NET_INTERNAL); } if (net_addr.IsTor()) { assert(net_addr.GetNetwork() == Network::NET_ONION); } (void)net_addr.IsValid(); (void)net_addr.ToString(); (void)net_addr.ToStringIP(); const CSubNet sub_net{net_addr, fuzzed_data_provider.ConsumeIntegral<int32_t>()}; (void)sub_net.IsValid(); (void)sub_net.ToString(); const CService service{net_addr, fuzzed_data_provider.ConsumeIntegral<uint16_t>()}; (void)service.GetKey(); (void)service.GetPort(); (void)service.ToString(); (void)service.ToStringIPPort(); (void)service.ToStringPort(); const CNetAddr other_net_addr = ConsumeNetAddr(fuzzed_data_provider); (void)net_addr.GetReachabilityFrom(&other_net_addr); (void)sub_net.Match(other_net_addr); const CService other_service{net_addr, fuzzed_data_provider.ConsumeIntegral<uint16_t>()}; assert((service == other_service) != (service != other_service)); } <|endoftext|>
<commit_before>#include "FileOperations.h" #include <QFile> #include <QtGlobal> template <class InputIterator1, class InputIterator2> bool FileOperations::equal(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2) { while ((first1 != last1) && (first2 != last2)) { if (*first1 != *first2) { return false; } ++first1; ++first2; } return (first1 == last1) && (first2 == last2); } bool FileOperations::filesEqual(const QString& filePath1, const QString& filePath2) { bool equivalent = false; QFile file1(filePath1); QFile file2(filePath2); if (file1.exists() && file2.exists()) { file1.open(QFile::ReadOnly); uchar* fileMemory1 = file1.map(0, file1.size()); file2.open(QFile::ReadOnly); uchar* fileMemory2 = file2.map(0, file2.size()); equivalent = equal(fileMemory1, fileMemory1 + file1.size(), fileMemory2, fileMemory2 + file2.size()); } return equivalent; } <commit_msg>Use QFile to do file comparison<commit_after>#include "FileOperations.h" #include <QFile> #include <QtGlobal> bool FileOperations::filesEqual(const QString& filePath1, const QString& filePath2) { bool equivalent = false; QFile file1(filePath1); QFile file2(filePath2); if (file1.exists() && file2.exists()) { file1.open(QFile::ReadOnly); file2.open(QFile::ReadOnly); while (!file1.atEnd()) { QByteArray file1Buffer; const qint64 file1BytesRead = file1.read(file1Buffer.data(), 16384); if (-1 == file1BytesRead) { break; } QByteArray file2Buffer; const qint64 file2BytesRead = file2.read(file2Buffer.data(), 16384); if (-1 == file1BytesRead) { break; } if (file1Buffer != file2Buffer) { break; } if (file1.atEnd() && !file2.atEnd()) { break; } if (file1.atEnd() && file2.atEnd()) { equivalent = true; } } } return equivalent; } <|endoftext|>
<commit_before>/** * Copyright © 2016 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../mainloop.hpp" #include <iostream> #include <fstream> #include <cstdio> #include <unistd.h> #include <thread> auto server_thread(void* data) { auto mgr = static_cast<MainLoop*>(data); mgr->run(); return static_cast<void*>(nullptr); } void runTests(MainLoop& loop) { loop.shutdown(); std::cout << "Success!\n"; } int main() { char tmpl[] = "/tmp/hwmon-test.XXXXXX"; std::string dir = mkdtemp(tmpl); std::string entry = dir + "/temp1_input"; std::ofstream f{entry}; f << "1234"; auto loop = MainLoop( sdbusplus::bus::new_default(), dir, "xyz.openbmc_project.Testing", "/testing"); auto t = std::thread(server_thread, &loop); runTests(loop); // Wait for server thread to exit. t.join(); unlink(entry.c_str()); rmdir(dir.c_str()); return 0; } // vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 <commit_msg>Avoid unnecessary move operation<commit_after>/** * Copyright © 2016 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "../mainloop.hpp" #include <iostream> #include <fstream> #include <cstdio> #include <unistd.h> #include <thread> auto server_thread(void* data) { auto mgr = static_cast<MainLoop*>(data); mgr->run(); return static_cast<void*>(nullptr); } void runTests(MainLoop& loop) { loop.shutdown(); std::cout << "Success!\n"; } int main() { char tmpl[] = "/tmp/hwmon-test.XXXXXX"; std::string dir = mkdtemp(tmpl); std::string entry = dir + "/temp1_input"; std::ofstream f{entry}; f << "1234"; MainLoop loop( sdbusplus::bus::new_default(), dir, "xyz.openbmc_project.Testing", "/testing"); auto t = std::thread(server_thread, &loop); runTests(loop); // Wait for server thread to exit. t.join(); unlink(entry.c_str()); rmdir(dir.c_str()); return 0; } // vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 <|endoftext|>
<commit_before>/* * * Author: Jeffrey Leung * Last edited: 2016-02-18 * * This C++ file tests the functions of the exception logger Exceptional. * */ #include <exception> #include <iostream> #include <stdexcept> #include "../include/exceptional.hpp" exceptional::Logger log; namespace { // This function throws an std::out_of_range error. void out_of_range() { throw std::out_of_range("Exception message for std::out_of_range."); } } // End of unnamed namespace (for local functions) int main() { int i = 948; log.LogWarning(i); std::string s = "Example string here."; log.LogWarning(s); try { out_of_range(); } catch( const std::exception& e ) { log.LogWarning(e); } std::cout << "Test output written to log.txt." << std::endl; return 0; } <commit_msg>Adding tests for exceptions with and without newlines.<commit_after>/* * * Author: Jeffrey Leung * Last edited: 2016-02-18 * * This C++ file tests the functions of the exception logger Exceptional. * */ #include <exception> #include <iostream> #include <stdexcept> #include "../include/exceptional.hpp" exceptional::Logger log; namespace { // This function throws an std::out_of_range error with a newline at the end. void out_of_range_newline() { throw std::out_of_range("Exception message for std::out_of_range.\n"); } // This function throws an std::out_of_range error without a newline. void out_of_range_no_newline() { throw std::out_of_range("Exception message for std::out_of_range."); } } // End of unnamed namespace (for local functions) int main() { int i = 948; log.LogWarning(i); std::string s = "Example string here."; log.LogWarning(s); try { out_of_range_newline(); } catch( const std::exception& e ) { log.LogWarning(e); } try { out_of_range_no_newline(); } catch( const std::exception& e ) { log.LogWarning(e); } std::cout << "Test output written to log.txt." << std::endl; return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <iostream> #include "util/test.h" #include "util/splay_map.h" #include "util/name.h" using namespace lean; struct int_cmp { int operator()(int i1, int i2) const { return i1 < i2 ? -1 : (i1 > i2 ? 1 : 0); } }; typedef splay_map<int, name, int_cmp> int2name; static void tst0() { int2name m1; m1[10] = name("t1"); m1[20] = name("t2"); int2name m2(m1); m2[10] = name("t3"); lean_assert(m1[10] == name("t1")); lean_assert(m1[20] == name("t2")); lean_assert(m2[10] == name("t3")); lean_assert(m2[20] == name("t2")); } int main() { tst0(); return has_violations() ? 1 : 0; } <commit_msg>test(splay_map): add tests for improving code coverage<commit_after>/* Copyright (c) 2013 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <iostream> #include "util/test.h" #include "util/splay_map.h" #include "util/name.h" using namespace lean; struct int_cmp { int operator()(int i1, int i2) const { return i1 < i2 ? -1 : (i1 > i2 ? 1 : 0); } }; typedef splay_map<int, name, int_cmp> int2name; static void tst0() { int2name m1; m1[10] = name("t1"); m1[20] = name("t2"); int2name m2(m1); m2[10] = name("t3"); lean_assert(m1[10] == name("t1")); lean_assert(m1[20] == name("t2")); lean_assert(m2[10] == name("t3")); lean_assert(m2[20] == name("t2")); lean_assert(m2.size() == 2); lean_assert(m2[100] == name()); lean_assert(m2.size() == 3); lean_assert(m2[100] == name()); lean_assert(m2.size() == 3); } int main() { tst0(); return has_violations() ? 1 : 0; } <|endoftext|>