text
stringlengths
54
60.6k
<commit_before>#ifndef QCAN_NETWORK_HPP_ #define QCAN_NETWORK_HPP_ #include <QTcpServer> #include <QTcpSocket> #include <QMutex> #include <QPointer> #include <QTimer> #include "qcan_frame.hpp" #include "qcan_frame_api.hpp" #include "qcan_frame_error.hpp" class QCanInterface; //----------------------------------------------------------------------------- /*! ** \class QCanNetwork ** \brief CAN network representation ** ** This class represents a CAN network with a unique bitrate. ** It supports one physical CAN interface, which can be assigned ** during run-time to the CAN network and a limited number of ** virtual CAN interfaces (sockets). ** */ class QCanNetwork : public QObject { Q_OBJECT public: /*! ** Create new CAN network with unique channel number. */ QCanNetwork(QObject * pclParentV = Q_NULLPTR, uint16_t uwPortV = QCAN_TCP_DEFAULT_PORT); ~QCanNetwork(); /*! ** \param pclCanIfV - Pointer to physical CAN interface ** \see removeInterface() ** ** Add a physical CAN interface to the CAN network. ** Each CAN network supports only one physical CAN interface. ** The CAN interface is removed from the network by calling ** the removeInterface() method. */ bool addInterface(QCanInterface * pclCanIfV); int32_t bitrate(void) {return (slBitrateP); }; uint32_t dispatcherTime(void) {return (ulDispatchTimeP); }; bool hasErrorFramesSupport(void); bool hasFastDataSupport(void); bool hasListenOnlySupport(void); bool isErrorFramesEnabled(void) {return (btErrorFramesEnabledP); }; bool isFastDataEnabled(void) {return (btFastDataEnabledP); }; bool isListenOnlyEnabled(void) {return (btListenOnlyEnabledP); }; bool isNetworkEnabled(void) {return (btNetworkEnabledP); }; /*! ** Show actual network load in percent. ** */ uint8_t load(); QString name() { return(clNetNameP); }; /*! ** \see addInterface() ** ** Remove a physical CAN interface from the CAN network. */ void removeInterface(void); void setBitrate(int32_t slBitrateV, int32_t slBrsClockV); void setDispatcherTime(uint32_t ulTimeV); void setErrorFramesEnabled(bool btEnableV = true); void setFastDataEnabled(bool btEnableV = true); void setListenOnlyEnabled(bool btEnableV = true); void setNetworkEnabled(bool btEnableV = true); public slots: void onSocketConnect(void); void onSocketDisconnect(void); void onTimerEvent(void); signals: void showApiFrames(uint32_t ulFrameTotalV); void showCanFrames(uint32_t ulFrameTotalV); void showErrFrames(uint32_t ulFrameTotalV); void showLoad(uint8_t ubLoadV, uint32_t ulMsgPerSecV); protected: private: bool handleApiFrame(int32_t & slSockSrcR, QCanFrameApi & clApiFrameR); bool handleCanFrame(int32_t & slSockSrcR, QByteArray & clSockDataR); bool handleErrFrame(int32_t & slSockSrcR, QCanFrameError & clErrorFrameR); QPointer<QCanInterface> pclInterfaceP; QPointer<QTcpServer> pclTcpSrvP; QVector<QTcpSocket *> * pclTcpSockListP; QHostAddress clTcpHostAddrP; uint16_t uwTcpPortP; static uint8_t ubNetIdP; QString clNetNameP; QMutex clTcpSockMutexP; QTimer clDispatchTmrP; uint32_t ulDispatchTimeP; int32_t slBitrateP; int32_t slBrsClockP; uint32_t ulCntFrameApiP; uint32_t ulCntFrameCanP; uint32_t ulCntFrameErrP; bool btErrorFramesEnabledP; bool btFastDataEnabledP; bool btListenOnlyEnabledP; bool btNetworkEnabledP; }; #endif // QCAN_NETWORK_HPP_ <commit_msg>Add documentation<commit_after>//============================================================================// // File: qcan_network.hpp // // Description: QCAN classes - CAN network // // // // Copyright (C) MicroControl GmbH & Co. KG // // 53844 Troisdorf - Germany // // www.microcontrol.net // // // //----------------------------------------------------------------------------// // 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, the following disclaimer and // // the referenced file 'LICENSE'. // // 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 MicroControl nor the names of its contributors // // may be used to endorse or promote products derived from this software // // without specific prior written permission. // // // // Provided that this notice is retained in full, this software may be // // distributed under the terms of the GNU Lesser General Public License // // ("LGPL") version 3 as distributed in the 'LICENSE' file. // // // //============================================================================// #ifndef QCAN_NETWORK_HPP_ #define QCAN_NETWORK_HPP_ /*----------------------------------------------------------------------------*\ ** Include files ** ** ** \*----------------------------------------------------------------------------*/ #include <QTcpServer> #include <QTcpSocket> #include <QMutex> #include <QPointer> #include <QTimer> #include "qcan_frame.hpp" #include "qcan_frame_api.hpp" #include "qcan_frame_error.hpp" /*----------------------------------------------------------------------------*\ ** Referenced classes ** ** ** \*----------------------------------------------------------------------------*/ class QCanInterface; //----------------------------------------------------------------------------- /*! ** \file qcan_network.hpp ** \brief CAN network ** ** This file ... ** */ //----------------------------------------------------------------------------- /*! ** \class QCanNetwork ** \brief CAN network representation ** ** This class represents a CAN network with a unique bitrate. ** It supports one physical CAN interface, which can be assigned ** during run-time to the CAN network and a limited number of ** virtual CAN interfaces (sockets). Clients can connect to a QCanNetwork ** via the QCanSocket class. ** */ class QCanNetwork : public QObject { Q_OBJECT public: /*! ** Create new CAN network with unique channel number. */ QCanNetwork(QObject * pclParentV = Q_NULLPTR, uint16_t uwPortV = QCAN_TCP_DEFAULT_PORT); ~QCanNetwork(); /*! ** \see removeInterface() ** ** The function adds a physical CAN interface to the CAN network. ** Each CAN network supports only one physical CAN interface. ** The CAN interface is removed from the network by calling ** the removeInterface() method. The parameter \c pclCanIfV is a pointer ** to an instance of a QCanInterface class. ** <p> ** The function returns \c true if the CAN interface is added, otherwise ** it will return \c false. */ bool addInterface(QCanInterface * pclCanIfV); /*! ** \see setBitrate() ** ** This function returns the current bit-rate of the CAN network. ** For <b>classic CAN</b>, the return value defines the bit-rate for the ** complete frame. ** For <b>CAN FD</b> the return value defines the bit-rate for ** the arbitration phase. ** <p> ** If no bit-rate is configured, the function will return ** QCan::eCAN_BITRATE_NONE. */ int32_t bitrate(void) {return (slBitrateP); }; /*! ** \see setDispatcherTime() ** ** This function returns the current dispatcher time for the ** internal CAN frame handler in milli-seconds. */ uint32_t dispatcherTime(void) {return (ulDispatchTimeP); }; bool hasErrorFramesSupport(void); bool hasFastDataSupport(void); bool hasListenOnlySupport(void); bool isErrorFramesEnabled(void) {return (btErrorFramesEnabledP); }; bool isFastDataEnabled(void) {return (btFastDataEnabledP); }; bool isListenOnlyEnabled(void) {return (btListenOnlyEnabledP); }; /*! ** \see setNetworkEnabled() ** ** This function returns \c true if the network is enabled, ** otherwise it returns \c false. */ bool isNetworkEnabled(void) {return (btNetworkEnabledP); }; QString name() { return(clNetNameP); }; void reset(void); /*! ** \see addInterface() ** ** Remove a physical CAN interface from the CAN network. */ void removeInterface(void); /*! ** \see bitrate() ** ** This function sets the bit-rate for the CAN network. For <b>classic CAN</b>, ** the parameter \c slBitrateV defines the bit-rate for the complete frame, ** the parameter \c slBrsClockV is not evaluated in that case. ** For <b>CAN FD</b> the parameter \c slBitrateV defines the bit-rate for ** the arbitration phase, the parameter \c slBrsClockV defines the ** bit-rate for the data phase. ** <p> ** For selection of pre-defined bit-rates the value can be taken from ** the enumeration QCan::CAN_Bitrate_e. */ void setBitrate(int32_t slBitrateV, int32_t slBrsClockV = QCan::eCAN_BITRATE_NONE); /*! ** \see dispatcherTime() ** ** This function sets the dispatcher time for the internal CAN frame ** handler in milli-seconds. */ void setDispatcherTime(uint32_t ulTimeV); void setErrorFramesEnabled(bool btEnableV = true); void setFastDataEnabled(bool btEnableV = true); void setListenOnlyEnabled(bool btEnableV = true); /*! ** \see isNetworkEnabled() ** ** This function enables the dispatching of CAN frames if \c btEnable is ** \c true. It is disabled for <c>btEnable = false</c>. */ void setNetworkEnabled(bool btEnableV = true); public slots: /*! ** This function is called upon socket connection. */ void onSocketConnect(void); /*! ** This function is called upon socket disconnection. */ void onSocketDisconnect(void); void onTimerEvent(void); signals: /*! ** This signal is emitted .. */ void showApiFrames(uint32_t ulFrameTotalV); void showCanFrames(uint32_t ulFrameTotalV); void showErrFrames(uint32_t ulFrameTotalV); void showLoad(uint8_t ubLoadV, uint32_t ulMsgPerSecV); protected: private: bool handleApiFrame(int32_t & slSockSrcR, QCanFrameApi & clApiFrameR); bool handleCanFrame(int32_t & slSockSrcR, QByteArray & clSockDataR); bool handleErrFrame(int32_t & slSockSrcR, QCanFrameError & clErrorFrameR); QPointer<QCanInterface> pclInterfaceP; QPointer<QTcpServer> pclTcpSrvP; QVector<QTcpSocket *> * pclTcpSockListP; QHostAddress clTcpHostAddrP; uint16_t uwTcpPortP; static uint8_t ubNetIdP; QString clNetNameP; QMutex clTcpSockMutexP; QTimer clDispatchTmrP; uint32_t ulDispatchTimeP; int32_t slBitrateP; int32_t slBrsClockP; uint32_t ulCntFrameApiP; uint32_t ulCntFrameCanP; uint32_t ulCntFrameErrP; bool btErrorFramesEnabledP; bool btFastDataEnabledP; bool btListenOnlyEnabledP; bool btNetworkEnabledP; }; #endif // QCAN_NETWORK_HPP_ <|endoftext|>
<commit_before>/* Lantern - A path tracer * * Lantern is the legal property of Adrian Astley * Copyright Adrian Astley 2015 - 2016 */ #include "renderer/renderer.h" #include "common/global_args.h" #include "scene/mesh_elements.h" #include "graphics/atomic_frame_buffer.h" namespace Lantern { Renderer::Renderer(GlobalArgs *globalArgs) : m_globalArgs(globalArgs), m_device(rtcNewDevice(nullptr)), m_scene(nullptr) { } Renderer::~Renderer() { if (!m_scene) { rtcDeleteScene(m_scene); } rtcDeleteDevice(m_device); } void Renderer::SetScene() { m_scene = rtcDeviceNewScene(m_device, RTC_SCENE_STATIC, RTC_INTERSECT1); // Create a cube uint id = rtcNewTriangleMesh(m_scene, RTC_GEOMETRY_STATIC, 12, 8); Vertex *vertices = (Vertex *)rtcMapBuffer(m_scene, id, RTC_VERTEX_BUFFER); vertices[0].X = -1; vertices[0].Y = -1; vertices[0].Z = -1; vertices[1].X = -1; vertices[1].Y = -1; vertices[1].Z = +1; vertices[2].X = -1; vertices[2].Y = +1; vertices[2].Z = -1; vertices[3].X = -1; vertices[3].Y = +1; vertices[3].Z = +1; vertices[4].X = +1; vertices[4].Y = -1; vertices[4].Z = -1; vertices[5].X = +1; vertices[5].Y = -1; vertices[5].Z = +1; vertices[6].X = +1; vertices[6].Y = +1; vertices[6].Z = -1; vertices[7].X = +1; vertices[7].Y = +1; vertices[7].Z = +1; rtcUnmapBuffer(m_scene, id, RTC_VERTEX_BUFFER); Triangle* triangles = (Triangle*)rtcMapBuffer(m_scene, id, RTC_INDEX_BUFFER); // left side triangles[0].V0 = 0; triangles[0].V1 = 2; triangles[0].V2 = 1; triangles[1].V0 = 1; triangles[1].V1 = 2; triangles[1].V2 = 3; // right side triangles[2].V0 = 4; triangles[2].V1 = 5; triangles[2].V2 = 6; triangles[3].V0 = 5; triangles[3].V1 = 7; triangles[3].V2 = 6; // bottom side triangles[4].V0 = 0; triangles[4].V1 = 1; triangles[4].V2 = 4; triangles[5].V0 = 1; triangles[5].V1 = 5; triangles[5].V2 = 4; // top side triangles[6].V0 = 2; triangles[6].V1 = 6; triangles[6].V2 = 3; triangles[7].V0 = 3; triangles[7].V1 = 6; triangles[7].V2 = 7; // front side triangles[8].V0 = 0; triangles[8].V1 = 4; triangles[8].V2 = 2; triangles[9].V0 = 2; triangles[9].V1 = 4; triangles[9].V2 = 6; // back side triangles[10].V0 = 1; triangles[10].V1 = 3; triangles[10].V2 = 5; triangles[11].V0 = 3; triangles[11].V1 = 7; triangles[11].V2 = 5; rtcUnmapBuffer(m_scene, id, RTC_INDEX_BUFFER); rtcCommit(m_scene); } void Renderer::Start() { uint width = m_globalArgs->FrameBuffer->Width(); uint height = m_globalArgs->FrameBuffer->Height(); for (uint y = 0; y < height; ++y) { for (uint x = 0; x < width; ++x) { float3 color = float3(1.0f, 0.0f, 0.0f); m_globalArgs->FrameBuffer->SplatPixel(x, y, color); } } m_globalArgs->RenderChanged.store(true); } } // End of namespace Lantern <commit_msg>Add something more exciting to look at<commit_after>/* Lantern - A path tracer * * Lantern is the legal property of Adrian Astley * Copyright Adrian Astley 2015 - 2016 */ #include "renderer/renderer.h" #include "common/global_args.h" #include "scene/mesh_elements.h" #include "graphics/atomic_frame_buffer.h" namespace Lantern { Renderer::Renderer(GlobalArgs *globalArgs) : m_globalArgs(globalArgs), m_device(rtcNewDevice(nullptr)), m_scene(nullptr) { } Renderer::~Renderer() { if (!m_scene) { rtcDeleteScene(m_scene); } rtcDeleteDevice(m_device); } void Renderer::SetScene() { m_scene = rtcDeviceNewScene(m_device, RTC_SCENE_STATIC, RTC_INTERSECT1); // Create a cube uint id = rtcNewTriangleMesh(m_scene, RTC_GEOMETRY_STATIC, 12, 8); Vertex *vertices = (Vertex *)rtcMapBuffer(m_scene, id, RTC_VERTEX_BUFFER); vertices[0].X = -1; vertices[0].Y = -1; vertices[0].Z = -1; vertices[1].X = -1; vertices[1].Y = -1; vertices[1].Z = +1; vertices[2].X = -1; vertices[2].Y = +1; vertices[2].Z = -1; vertices[3].X = -1; vertices[3].Y = +1; vertices[3].Z = +1; vertices[4].X = +1; vertices[4].Y = -1; vertices[4].Z = -1; vertices[5].X = +1; vertices[5].Y = -1; vertices[5].Z = +1; vertices[6].X = +1; vertices[6].Y = +1; vertices[6].Z = -1; vertices[7].X = +1; vertices[7].Y = +1; vertices[7].Z = +1; rtcUnmapBuffer(m_scene, id, RTC_VERTEX_BUFFER); Triangle* triangles = (Triangle*)rtcMapBuffer(m_scene, id, RTC_INDEX_BUFFER); // left side triangles[0].V0 = 0; triangles[0].V1 = 2; triangles[0].V2 = 1; triangles[1].V0 = 1; triangles[1].V1 = 2; triangles[1].V2 = 3; // right side triangles[2].V0 = 4; triangles[2].V1 = 5; triangles[2].V2 = 6; triangles[3].V0 = 5; triangles[3].V1 = 7; triangles[3].V2 = 6; // bottom side triangles[4].V0 = 0; triangles[4].V1 = 1; triangles[4].V2 = 4; triangles[5].V0 = 1; triangles[5].V1 = 5; triangles[5].V2 = 4; // top side triangles[6].V0 = 2; triangles[6].V1 = 6; triangles[6].V2 = 3; triangles[7].V0 = 3; triangles[7].V1 = 6; triangles[7].V2 = 7; // front side triangles[8].V0 = 0; triangles[8].V1 = 4; triangles[8].V2 = 2; triangles[9].V0 = 2; triangles[9].V1 = 4; triangles[9].V2 = 6; // back side triangles[10].V0 = 1; triangles[10].V1 = 3; triangles[10].V2 = 5; triangles[11].V0 = 3; triangles[11].V1 = 7; triangles[11].V2 = 5; rtcUnmapBuffer(m_scene, id, RTC_INDEX_BUFFER); rtcCommit(m_scene); } void Renderer::Start() { uint width = m_globalArgs->FrameBuffer->Width(); uint height = m_globalArgs->FrameBuffer->Height(); for (uint y = 0; y < height; ++y) { for (uint x = 0; x < width; ++x) { float3 color; if (y >= 0 && y < 100) { color = float3(1.0f, 0.0f, 0.0f); } else if (y >= 100 && y < 200) { color = float3(1.0f, 1.0f, 0.0f); } else if (y >= 200 && y < 300) { color = float3(0.0f, 1.0f, 0.0f); } else if (y >= 300 && y < 400) { color = float3(1.0f, 1.0f, 1.0f); } else if (y >= 400 && y < 500) { color = float3(1.0f, 0.0f, 1.0f); } else if (y >= 500 && y < 600) { color = float3(0.0f, 0.0f, 0.0f); } else if (y >= 600 && y < 700) { color = float3(0.0f, 0.0f, 1.0f); } else { color = float3(0.5f, 1.0f, 0.5f); } m_globalArgs->FrameBuffer->SplatPixel(x, y, color); } } m_globalArgs->RenderChanged.store(true); } } // End of namespace Lantern <|endoftext|>
<commit_before>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: 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/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "raptor.h" #include "type/data.h" #include "utils/timer.h" #include <boost/program_options.hpp> #include <boost/progress.hpp> #include <random> #include <fstream> #include "utils/init.h" #include "utils/csv.h" using namespace navitia; using namespace routing; namespace po = boost::program_options; struct PathDemand { type::idx_t start; type::idx_t target; unsigned int date; unsigned int hour; }; struct Result { int duration; int time; int arrival; int nb_changes; Result(Path path) : duration(path.duration.total_seconds()), time(-1), arrival(-1), nb_changes(path.nb_changes) { if(!path.items.empty()) arrival = path.items.back().arrival.time_of_day().total_seconds(); } }; int main(int argc, char** argv){ navitia::init_app(); po::options_description desc("Options de l'outil de benchmark"); std::string file, output, stop_input_file; int iterations, start, target, date, hour; desc.add_options() ("help", "Show this message") ("interations,i", po::value<int>(&iterations)->default_value(100), "Number of iterations (10 calcuations par iteration)") ("file,f", po::value<std::string>(&file)->default_value("data.nav.lz4"), "Path to data.nav.lz4") ("start,s", po::value<int>(&start)->default_value(-1), "Start of a particular journey") ("target,t", po::value<int>(&target)->default_value(-1), "Target of a particular journey") ("date,d", po::value<int>(&date)->default_value(-1), "Begginning date of a particular journey") ("hour,h", po::value<int>(&hour)->default_value(-1), "Begginning hour of a particular journey") ("verbose,v", "Verbose debugging output") ("stop_files", po::value<std::string>(&stop_input_file), "File with list of start and target") ("output,o", po::value<std::string>(&output)->default_value("benchmark.csv"), "Output file"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); bool verbose = vm.count("verbose"); if (vm.count("help")) { std::cout << "This is used to benchmark journey computation" << std::endl; std::cout << desc << std::endl; return 1; } type::Data data; { Timer t("Chargement des données : " + file); data.load(file); } std::vector<PathDemand> demands; if (! stop_input_file.empty()) { //csv file should be the same as the output one CsvReader csv(stop_input_file, ','); csv.next(); size_t cpt_not_found = 0; for (auto it = csv.next(); ! csv.eof(); it = csv.next()) { const auto it_start = data.pt_data->stop_areas_map.find(it[0]); if (it_start == data.pt_data->stop_areas_map.end()) { std::cout << "impossible to find " << it[0] << std::endl; cpt_not_found++; continue; } const auto start = it_start->second; const auto it_end = data.pt_data->stop_areas_map.find(it[2]); if (it_end == data.pt_data->stop_areas_map.end()) { std::cout << "impossible to find " << it[2] << std::endl; cpt_not_found++; continue; } const auto end = it_end->second; PathDemand demand; demand.start = start->idx; demand.target = end->idx; demand.hour = boost::lexical_cast<unsigned int>(it[5]); demand.date = boost::lexical_cast<unsigned int>(it[4]); demands.push_back(demand); } std::cout << "nb start not found " << cpt_not_found << std::endl; } else if(start != -1 && target != -1 && date != -1 && hour != -1) { PathDemand demand; demand.start = start; demand.target = target; demand.hour = hour; demand.date = date; demands.push_back(demand); } else { // Génération des instances std::random_device rd; std::mt19937 rng(31442); std::uniform_int_distribution<> gen(0,data.pt_data->stop_areas.size()-1); std::vector<unsigned int> hours{0, 28800, 36000, 72000, 86000}; std::vector<unsigned int> days({7}); if(data.pt_data->validity_patterns.front()->beginning_date.day_of_week().as_number() == 6) days.push_back(8); else days.push_back(13); for(int i = 0; i < iterations; ++i) { PathDemand demand; demand.start = gen(rng); demand.target = gen(rng); while(demand.start == demand.target) { demand.target = gen(rng); demand.start = gen(rng); } for(auto day : days) { for(auto hour : hours) { demand.date = day; demand.hour = hour; demands.push_back(demand); } } } } // Calculs des itinéraires std::vector<Result> results; data.build_raptor(); RAPTOR router(data); std::cout << "On lance le benchmark de l'algo " << std::endl; boost::progress_display show_progress(demands.size()); Timer t("Calcul avec l'algorithme "); //ProfilerStart("bench.prof"); int nb_reponses = 0; for(auto demand : demands){ ++show_progress; Timer t2; if (verbose){ std::cout << data.pt_data->stop_areas[demand.start]->uri << ", " << demand.start << ", " << data.pt_data->stop_areas[demand.target]->uri << ", " << demand.target << ", " << demand.date << ", " << demand.hour << "\n"; } auto res = router.compute(data.pt_data->stop_areas[demand.start], data.pt_data->stop_areas[demand.target], demand.hour, demand.date, DateTimeUtils::set(demand.date + 1, demand.hour),false, true); Path path; if(res.size() > 0) { path = res[0]; ++ nb_reponses; } Result result(path); result.time = t2.ms(); results.push_back(result); } //ProfilerStop(); Timer ecriture("Writing results"); std::fstream out_file(output, std::ios::out); out_file << "Start, Start id, Target, Target id, Day, Hour"; out_file << ", " << "arrival, " << "duration, " << "nb_change, " << "visited, " << "time"; out_file << "\n"; for(size_t i = 0; i < demands.size(); ++i){ PathDemand demand = demands[i]; out_file << data.pt_data->stop_areas[demand.start]->uri << ", " << demand.start << ", " << data.pt_data->stop_areas[demand.target]->uri << ", " << demand.target << ", " << demand.date << ", " << demand.hour; out_file << ", " << results[i].arrival << ", " << results[i].duration << ", " << results[i].nb_changes << ", " << results[i].time; out_file << "\n"; } out_file.close(); std::cout << "Number of requests: " << demands.size() << std::endl; std::cout << "Number of results with solution: " << nb_reponses << std::endl; } <commit_msg>Bench: add callgrind instruction<commit_after>/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: 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/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "raptor.h" #include "type/data.h" #include "utils/timer.h" #include <boost/program_options.hpp> #include <boost/progress.hpp> #include <random> #include <fstream> #include "utils/init.h" #include "utils/csv.h" #ifdef __BENCH_WITH_CALGRIND__ #include "valgrind/callgrind.h" #endif using namespace navitia; using namespace routing; namespace po = boost::program_options; struct PathDemand { type::idx_t start; type::idx_t target; unsigned int date; unsigned int hour; }; struct Result { int duration; int time; int arrival; int nb_changes; Result(Path path) : duration(path.duration.total_seconds()), time(-1), arrival(-1), nb_changes(path.nb_changes) { if(!path.items.empty()) arrival = path.items.back().arrival.time_of_day().total_seconds(); } }; int main(int argc, char** argv){ navitia::init_app(); po::options_description desc("Options de l'outil de benchmark"); std::string file, output, stop_input_file; int iterations, start, target, date, hour; desc.add_options() ("help", "Show this message") ("interations,i", po::value<int>(&iterations)->default_value(100), "Number of iterations (10 calcuations par iteration)") ("file,f", po::value<std::string>(&file)->default_value("data.nav.lz4"), "Path to data.nav.lz4") ("start,s", po::value<int>(&start)->default_value(-1), "Start of a particular journey") ("target,t", po::value<int>(&target)->default_value(-1), "Target of a particular journey") ("date,d", po::value<int>(&date)->default_value(-1), "Begginning date of a particular journey") ("hour,h", po::value<int>(&hour)->default_value(-1), "Begginning hour of a particular journey") ("verbose,v", "Verbose debugging output") ("stop_files", po::value<std::string>(&stop_input_file), "File with list of start and target") ("output,o", po::value<std::string>(&output)->default_value("benchmark.csv"), "Output file"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); bool verbose = vm.count("verbose"); if (vm.count("help")) { std::cout << "This is used to benchmark journey computation" << std::endl; std::cout << desc << std::endl; return 1; } type::Data data; { Timer t("Chargement des données : " + file); data.load(file); } std::vector<PathDemand> demands; if (! stop_input_file.empty()) { //csv file should be the same as the output one CsvReader csv(stop_input_file, ','); csv.next(); size_t cpt_not_found = 0; for (auto it = csv.next(); ! csv.eof(); it = csv.next()) { const auto it_start = data.pt_data->stop_areas_map.find(it[0]); if (it_start == data.pt_data->stop_areas_map.end()) { std::cout << "impossible to find " << it[0] << std::endl; cpt_not_found++; continue; } const auto start = it_start->second; const auto it_end = data.pt_data->stop_areas_map.find(it[2]); if (it_end == data.pt_data->stop_areas_map.end()) { std::cout << "impossible to find " << it[2] << std::endl; cpt_not_found++; continue; } const auto end = it_end->second; PathDemand demand; demand.start = start->idx; demand.target = end->idx; demand.hour = boost::lexical_cast<unsigned int>(it[5]); demand.date = boost::lexical_cast<unsigned int>(it[4]); demands.push_back(demand); } std::cout << "nb start not found " << cpt_not_found << std::endl; } else if(start != -1 && target != -1 && date != -1 && hour != -1) { PathDemand demand; demand.start = start; demand.target = target; demand.hour = hour; demand.date = date; demands.push_back(demand); } else { // Génération des instances std::random_device rd; std::mt19937 rng(31442); std::uniform_int_distribution<> gen(0,data.pt_data->stop_areas.size()-1); std::vector<unsigned int> hours{0, 28800, 36000, 72000, 86000}; std::vector<unsigned int> days({7}); if(data.pt_data->validity_patterns.front()->beginning_date.day_of_week().as_number() == 6) days.push_back(8); else days.push_back(13); for(int i = 0; i < iterations; ++i) { PathDemand demand; demand.start = gen(rng); demand.target = gen(rng); while(demand.start == demand.target) { demand.target = gen(rng); demand.start = gen(rng); } for(auto day : days) { for(auto hour : hours) { demand.date = day; demand.hour = hour; demands.push_back(demand); } } } } // Calculs des itinéraires std::vector<Result> results; data.build_raptor(); RAPTOR router(data); std::cout << "On lance le benchmark de l'algo " << std::endl; boost::progress_display show_progress(demands.size()); Timer t("Calcul avec l'algorithme "); //ProfilerStart("bench.prof"); int nb_reponses = 0; #ifdef __BENCH_WITH_CALGRIND__ CALLGRIND_START_INSTRUMENTATION; #endif for(auto demand : demands){ ++show_progress; Timer t2; if (verbose){ std::cout << data.pt_data->stop_areas[demand.start]->uri << ", " << demand.start << ", " << data.pt_data->stop_areas[demand.target]->uri << ", " << demand.target << ", " << demand.date << ", " << demand.hour << "\n"; } auto res = router.compute(data.pt_data->stop_areas[demand.start], data.pt_data->stop_areas[demand.target], demand.hour, demand.date, DateTimeUtils::set(demand.date + 1, demand.hour),false, true); Path path; if(res.size() > 0) { path = res[0]; ++ nb_reponses; } Result result(path); result.time = t2.ms(); results.push_back(result); } //ProfilerStop(); #ifdef __BENCH_WITH_CALGRIND__ CALLGRIND_STOP_INSTRUMENTATION; #endif Timer ecriture("Writing results"); std::fstream out_file(output, std::ios::out); out_file << "Start, Start id, Target, Target id, Day, Hour"; out_file << ", " << "arrival, " << "duration, " << "nb_change, " << "visited, " << "time"; out_file << "\n"; for(size_t i = 0; i < demands.size(); ++i){ PathDemand demand = demands[i]; out_file << data.pt_data->stop_areas[demand.start]->uri << ", " << demand.start << ", " << data.pt_data->stop_areas[demand.target]->uri << ", " << demand.target << ", " << demand.date << ", " << demand.hour; out_file << ", " << results[i].arrival << ", " << results[i].duration << ", " << results[i].nb_changes << ", " << results[i].time; out_file << "\n"; } out_file.close(); std::cout << "Number of requests: " << demands.size() << std::endl; std::cout << "Number of results with solution: " << nb_reponses << std::endl; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "base/file_util.h" #include "base/test/test_timeouts.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/base/ui_test_utils.h" #include "chrome/test/ui/ui_layout_test.h" #include "content/public/common/content_switches.h" #include "net/base/net_util.h" static const char* kRootFiles[] = { "clear.html", // "complex-keys.html", // Output too big for a cookie. crbug.com/33472 // "complex-values.html", // crbug.com/33472 "quota.html", "remove-item.html", "window-attributes-exist.html", NULL }; static const char* kEventsFiles[] = { // "basic-body-attribute.html", // crbug.com/33472 // "basic.html", // crbug.com/33472 // "basic-setattribute.html", // crbug.com/33472 "case-sensitive.html", "documentURI.html", NULL }; static const char* kStorageFiles[] = { "delete-removal.html", "enumerate-storage.html", "enumerate-with-length-and-key.html", "index-get-and-set.html", "simple-usage.html", "string-conversion.html", // "window-open.html", // TODO(jorlow): Fix NULL }; class DOMStorageTest : public UILayoutTest { protected: DOMStorageTest() : UILayoutTest(), test_dir_(FilePath(). AppendASCII("storage").AppendASCII("domstorage")) { } virtual ~DOMStorageTest() { } virtual void SetUp() { launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking); UILayoutTest::SetUp(); } // We require fast/js/resources for most of the DOM Storage layout tests. // Add those to the list to be copied. void AddJSTestResources() { // Add other paths our tests require. FilePath js_dir = FilePath(). AppendASCII("fast").AppendASCII("js"); AddResourceForLayoutTest(js_dir, FilePath().AppendASCII("resources")); } // This is somewhat of a hack because we're running a real browser that // actually persists the LocalStorage state vs. DRT and TestShell which don't. // The correct fix is to fix the LayoutTests, but similar patches have been // rejected in the past. void ClearDOMStorage() { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); const FilePath dir(FILE_PATH_LITERAL("layout_tests")); const FilePath file(FILE_PATH_LITERAL("clear_dom_storage.html")); GURL url = ui_test_utils::GetTestUrl(dir, file); ASSERT_TRUE(tab->SetCookie(url, "")); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilCookieNonEmpty(tab.get(), url, "cleared", TestTimeouts::action_max_timeout_ms()); } // Runs each test in an array of strings until it hits a NULL. void RunTests(const char** files) { while (*files) { ClearDOMStorage(); RunLayoutTest(*files, kNoHttpPort); ++files; } } FilePath test_dir_; }; TEST_F(DOMStorageTest, RootLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath(), kNoHttpPort); AddJSTestResources(); AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("script-tests")); RunTests(kRootFiles); } TEST_F(DOMStorageTest, EventLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("events"), kNoHttpPort); AddJSTestResources(); AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("events"). AppendASCII("resources")); AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("events"). AppendASCII("script-tests")); RunTests(kEventsFiles); } TEST_F(DOMStorageTest, LocalStorageLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"), kNoHttpPort); AddJSTestResources(); AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"). AppendASCII("resources")); RunTests(kStorageFiles); } TEST_F(DOMStorageTest, SessionStorageLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"), kNoHttpPort); AddJSTestResources(); AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"). AppendASCII("resources")); RunTests(kStorageFiles); } class DomStorageEmptyDatabaseTest : public UITest { protected: FilePath StorageDir() const { FilePath storage_dir = user_data_dir(); storage_dir = storage_dir.AppendASCII("Default"); storage_dir = storage_dir.AppendASCII("Local Storage"); return storage_dir; } bool StorageDirIsEmpty() const { FilePath storage_dir = StorageDir(); if (!file_util::DirectoryExists(storage_dir)) return true; return file_util::IsDirectoryEmpty(storage_dir); } GURL TestUrl() const { FilePath test_dir = test_data_directory_; FilePath test_file = test_dir.AppendASCII("dom_storage_empty_db.html"); return net::FilePathToFileURL(test_file); } }; TEST_F(DomStorageEmptyDatabaseTest, EmptyDirAfterClear) { NavigateToURL(TestUrl()); ASSERT_TRUE(StorageDirIsEmpty()); NavigateToURL(GURL("javascript:set()")); NavigateToURL(GURL("javascript:clear()")); QuitBrowser(); EXPECT_TRUE(StorageDirIsEmpty()); } TEST_F(DomStorageEmptyDatabaseTest, EmptyDirAfterGet) { NavigateToURL(TestUrl()); ASSERT_TRUE(StorageDirIsEmpty()); NavigateToURL(GURL("javascript:get()")); QuitBrowser(); EXPECT_TRUE(StorageDirIsEmpty()); } // Flaky, see http://crbug.com/73776 TEST_F(DomStorageEmptyDatabaseTest, FLAKY_NonEmptyDirAfterSet) { NavigateToURL(TestUrl()); ASSERT_TRUE(StorageDirIsEmpty()); NavigateToURL(GURL("javascript:set()")); QuitBrowser(); EXPECT_FALSE(StorageDirIsEmpty()); LaunchBrowserAndServer(); NavigateToURL(TestUrl()); NavigateToURL(GURL("javascript:clear()")); QuitBrowser(); EXPECT_TRUE(StorageDirIsEmpty()); } <commit_msg>Mark flaky test: DOMStorageTest.EventLayoutTests<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "base/file_util.h" #include "base/test/test_timeouts.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/base/ui_test_utils.h" #include "chrome/test/ui/ui_layout_test.h" #include "content/public/common/content_switches.h" #include "net/base/net_util.h" static const char* kRootFiles[] = { "clear.html", // "complex-keys.html", // Output too big for a cookie. crbug.com/33472 // "complex-values.html", // crbug.com/33472 "quota.html", "remove-item.html", "window-attributes-exist.html", NULL }; static const char* kEventsFiles[] = { // "basic-body-attribute.html", // crbug.com/33472 // "basic.html", // crbug.com/33472 // "basic-setattribute.html", // crbug.com/33472 "case-sensitive.html", "documentURI.html", NULL }; static const char* kStorageFiles[] = { "delete-removal.html", "enumerate-storage.html", "enumerate-with-length-and-key.html", "index-get-and-set.html", "simple-usage.html", "string-conversion.html", // "window-open.html", // TODO(jorlow): Fix NULL }; class DOMStorageTest : public UILayoutTest { protected: DOMStorageTest() : UILayoutTest(), test_dir_(FilePath(). AppendASCII("storage").AppendASCII("domstorage")) { } virtual ~DOMStorageTest() { } virtual void SetUp() { launch_arguments_.AppendSwitch(switches::kDisablePopupBlocking); UILayoutTest::SetUp(); } // We require fast/js/resources for most of the DOM Storage layout tests. // Add those to the list to be copied. void AddJSTestResources() { // Add other paths our tests require. FilePath js_dir = FilePath(). AppendASCII("fast").AppendASCII("js"); AddResourceForLayoutTest(js_dir, FilePath().AppendASCII("resources")); } // This is somewhat of a hack because we're running a real browser that // actually persists the LocalStorage state vs. DRT and TestShell which don't. // The correct fix is to fix the LayoutTests, but similar patches have been // rejected in the past. void ClearDOMStorage() { scoped_refptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab.get()); const FilePath dir(FILE_PATH_LITERAL("layout_tests")); const FilePath file(FILE_PATH_LITERAL("clear_dom_storage.html")); GURL url = ui_test_utils::GetTestUrl(dir, file); ASSERT_TRUE(tab->SetCookie(url, "")); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilCookieNonEmpty(tab.get(), url, "cleared", TestTimeouts::action_max_timeout_ms()); } // Runs each test in an array of strings until it hits a NULL. void RunTests(const char** files) { while (*files) { ClearDOMStorage(); RunLayoutTest(*files, kNoHttpPort); ++files; } } FilePath test_dir_; }; TEST_F(DOMStorageTest, RootLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath(), kNoHttpPort); AddJSTestResources(); AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("script-tests")); RunTests(kRootFiles); } // Flakily fails on all platforms. http://crbug.com/102641 TEST_F(DOMStorageTest, FLAKY_EventLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("events"), kNoHttpPort); AddJSTestResources(); AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("events"). AppendASCII("resources")); AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("events"). AppendASCII("script-tests")); RunTests(kEventsFiles); } TEST_F(DOMStorageTest, LocalStorageLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"), kNoHttpPort); AddJSTestResources(); AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("localstorage"). AppendASCII("resources")); RunTests(kStorageFiles); } TEST_F(DOMStorageTest, SessionStorageLayoutTests) { InitializeForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"), kNoHttpPort); AddJSTestResources(); AddResourceForLayoutTest(test_dir_, FilePath().AppendASCII("sessionstorage"). AppendASCII("resources")); RunTests(kStorageFiles); } class DomStorageEmptyDatabaseTest : public UITest { protected: FilePath StorageDir() const { FilePath storage_dir = user_data_dir(); storage_dir = storage_dir.AppendASCII("Default"); storage_dir = storage_dir.AppendASCII("Local Storage"); return storage_dir; } bool StorageDirIsEmpty() const { FilePath storage_dir = StorageDir(); if (!file_util::DirectoryExists(storage_dir)) return true; return file_util::IsDirectoryEmpty(storage_dir); } GURL TestUrl() const { FilePath test_dir = test_data_directory_; FilePath test_file = test_dir.AppendASCII("dom_storage_empty_db.html"); return net::FilePathToFileURL(test_file); } }; TEST_F(DomStorageEmptyDatabaseTest, EmptyDirAfterClear) { NavigateToURL(TestUrl()); ASSERT_TRUE(StorageDirIsEmpty()); NavigateToURL(GURL("javascript:set()")); NavigateToURL(GURL("javascript:clear()")); QuitBrowser(); EXPECT_TRUE(StorageDirIsEmpty()); } TEST_F(DomStorageEmptyDatabaseTest, EmptyDirAfterGet) { NavigateToURL(TestUrl()); ASSERT_TRUE(StorageDirIsEmpty()); NavigateToURL(GURL("javascript:get()")); QuitBrowser(); EXPECT_TRUE(StorageDirIsEmpty()); } // Flaky, see http://crbug.com/73776 TEST_F(DomStorageEmptyDatabaseTest, FLAKY_NonEmptyDirAfterSet) { NavigateToURL(TestUrl()); ASSERT_TRUE(StorageDirIsEmpty()); NavigateToURL(GURL("javascript:set()")); QuitBrowser(); EXPECT_FALSE(StorageDirIsEmpty()); LaunchBrowserAndServer(); NavigateToURL(TestUrl()); NavigateToURL(GURL("javascript:clear()")); QuitBrowser(); EXPECT_TRUE(StorageDirIsEmpty()); } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/common/gpu/client/gl_helper_readback_support.h" #include "base/logging.h" namespace content { GLHelperReadbackSupport::GLHelperReadbackSupport(gpu::gles2::GLES2Interface* gl) : gl_(gl) { InitializeReadbackSupport(); } GLHelperReadbackSupport::~GLHelperReadbackSupport() {} void GLHelperReadbackSupport::InitializeReadbackSupport() { // We are concerned about 16, 32-bit formats only. // The below are the most used 16, 32-bit formats. // In future if any new format support is needed that should be added here. // Initialize the array with FORMAT_NOT_SUPPORTED as we dont know the // supported formats yet. for (int i = 0; i < SkBitmap::kConfigCount; ++i) { format_support_table_[i] = FORMAT_NOT_SUPPORTED; } CheckForReadbackSupport(SkBitmap::kRGB_565_Config); CheckForReadbackSupport(SkBitmap::kARGB_4444_Config); CheckForReadbackSupport(SkBitmap::kARGB_8888_Config); // Further any formats, support should be checked here. } void GLHelperReadbackSupport::CheckForReadbackSupport( SkBitmap::Config texture_format) { bool supports_format = false; switch (texture_format) { case SkBitmap::kRGB_565_Config: supports_format = SupportsFormat(GL_RGB, GL_UNSIGNED_SHORT_5_6_5); break; case SkBitmap::kARGB_8888_Config: supports_format = SupportsFormat(GL_RGBA, GL_UNSIGNED_BYTE); break; case SkBitmap::kARGB_4444_Config: supports_format = false; break; default: NOTREACHED(); supports_format = false; break; } DCHECK((int)texture_format < (int)SkBitmap::kConfigCount); format_support_table_[texture_format] = supports_format ? FORMAT_SUPPORTED : FORMAT_NOT_SUPPORTED; } bool GLHelperReadbackSupport::SupportsFormat(GLint format, GLint type) { const int kTestSize = 64; bool supports_format = false; content::ScopedTexture dst_texture(gl_); ScopedTextureBinder<GL_TEXTURE_2D> texture_binder(gl_, dst_texture); gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); gl_->TexImage2D( GL_TEXTURE_2D, 0, format, kTestSize, kTestSize, 0, format, type, NULL); ScopedFramebuffer dst_framebuffer(gl_); ScopedFramebufferBinder<GL_FRAMEBUFFER> framebuffer_binder(gl_, dst_framebuffer); gl_->FramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, dst_texture, 0); GLint ext_format = 0, ext_type = 0; gl_->GetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &ext_format); gl_->GetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &ext_type); if ((ext_format == format) && (ext_type == type)) { supports_format = true; } return supports_format; } bool GLHelperReadbackSupport::IsReadbackConfigSupported( SkBitmap::Config texture_format) { switch (format_support_table_[texture_format]) { case FORMAT_SUPPORTED: return true; case FORMAT_NOT_SUPPORTED: return false; default: NOTREACHED(); return false; } } } // namespace content <commit_msg>Revert 255420 "Revert 255386 "Support ARGB_8888 by default in GL..."<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/common/gpu/client/gl_helper_readback_support.h" #include "base/logging.h" namespace content { GLHelperReadbackSupport::GLHelperReadbackSupport(gpu::gles2::GLES2Interface* gl) : gl_(gl) { InitializeReadbackSupport(); } GLHelperReadbackSupport::~GLHelperReadbackSupport() {} void GLHelperReadbackSupport::InitializeReadbackSupport() { // We are concerned about 16, 32-bit formats only. // The below are the most used 16, 32-bit formats. // In future if any new format support is needed that should be added here. // Initialize the array with FORMAT_NOT_SUPPORTED as we dont know the // supported formats yet. for (int i = 0; i < SkBitmap::kConfigCount; ++i) { format_support_table_[i] = FORMAT_NOT_SUPPORTED; } CheckForReadbackSupport(SkBitmap::kRGB_565_Config); CheckForReadbackSupport(SkBitmap::kARGB_4444_Config); CheckForReadbackSupport(SkBitmap::kARGB_8888_Config); // Further any formats, support should be checked here. } void GLHelperReadbackSupport::CheckForReadbackSupport( SkBitmap::Config texture_format) { bool supports_format = false; switch (texture_format) { case SkBitmap::kRGB_565_Config: supports_format = SupportsFormat(GL_RGB, GL_UNSIGNED_SHORT_5_6_5); break; case SkBitmap::kARGB_8888_Config: // This is the baseline, assume always true. supports_format = true; break; case SkBitmap::kARGB_4444_Config: supports_format = false; break; default: NOTREACHED(); supports_format = false; break; } DCHECK((int)texture_format < (int)SkBitmap::kConfigCount); format_support_table_[texture_format] = supports_format ? FORMAT_SUPPORTED : FORMAT_NOT_SUPPORTED; } bool GLHelperReadbackSupport::SupportsFormat(GLint format, GLint type) { const int kTestSize = 64; bool supports_format = false; content::ScopedTexture dst_texture(gl_); ScopedTextureBinder<GL_TEXTURE_2D> texture_binder(gl_, dst_texture); gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); gl_->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); gl_->TexImage2D( GL_TEXTURE_2D, 0, format, kTestSize, kTestSize, 0, format, type, NULL); ScopedFramebuffer dst_framebuffer(gl_); ScopedFramebufferBinder<GL_FRAMEBUFFER> framebuffer_binder(gl_, dst_framebuffer); gl_->FramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, dst_texture, 0); GLint ext_format = 0, ext_type = 0; gl_->GetIntegerv(GL_IMPLEMENTATION_COLOR_READ_FORMAT, &ext_format); gl_->GetIntegerv(GL_IMPLEMENTATION_COLOR_READ_TYPE, &ext_type); if ((ext_format == format) && (ext_type == type)) { supports_format = true; } return supports_format; } bool GLHelperReadbackSupport::IsReadbackConfigSupported( SkBitmap::Config texture_format) { switch (format_support_table_[texture_format]) { case FORMAT_SUPPORTED: return true; case FORMAT_NOT_SUPPORTED: return false; default: NOTREACHED(); return false; } } } // namespace content <|endoftext|>
<commit_before>//===-- MachineInstr.cpp --------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Methods common to all machine instructions. // // FIXME: Now that MachineInstrs have parent pointers, they should always // print themselves using their MachineFunction's TargetMachine. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/Value.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/MRegisterInfo.h" #include "Support/LeakDetector.h" using namespace llvm; // Global variable holding an array of descriptors for machine instructions. // The actual object needs to be created separately for each target machine. // This variable is initialized and reset by class TargetInstrInfo. // // FIXME: This should be a property of the target so that more than one target // at a time can be active... // namespace llvm { extern const TargetInstrDescriptor *TargetInstrDescriptors; } // Constructor for instructions with variable #operands MachineInstr::MachineInstr(short opcode, unsigned numOperands) : Opcode(opcode), numImplicitRefs(0), operands(numOperands, MachineOperand()), parent(0) { // Make sure that we get added to a machine basicblock LeakDetector::addGarbageObject(this); } /// MachineInstr ctor - This constructor only does a _reserve_ of the operands, /// not a resize for them. It is expected that if you use this that you call /// add* methods below to fill up the operands, instead of the Set methods. /// Eventually, the "resizing" ctors will be phased out. /// MachineInstr::MachineInstr(short opcode, unsigned numOperands, bool XX, bool YY) : Opcode(opcode), numImplicitRefs(0), parent(0) { operands.reserve(numOperands); // Make sure that we get added to a machine basicblock LeakDetector::addGarbageObject(this); } /// MachineInstr ctor - Work exactly the same as the ctor above, except that the /// MachineInstr is created and added to the end of the specified basic block. /// MachineInstr::MachineInstr(MachineBasicBlock *MBB, short opcode, unsigned numOperands) : Opcode(opcode), numImplicitRefs(0), parent(0) { assert(MBB && "Cannot use inserting ctor with null basic block!"); operands.reserve(numOperands); // Make sure that we get added to a machine basicblock LeakDetector::addGarbageObject(this); MBB->push_back(this); // Add instruction to end of basic block! } MachineInstr::~MachineInstr() { LeakDetector::removeGarbageObject(this); } /// OperandComplete - Return true if it's illegal to add a new operand /// bool MachineInstr::OperandsComplete() const { int NumOperands = TargetInstrDescriptors[Opcode].numOperands; if (NumOperands >= 0 && getNumOperands() >= (unsigned)NumOperands) return true; // Broken: we have all the operands of this instruction! return false; } /// replace - Support for replacing opcode and operands of a MachineInstr in /// place. This only resets the size of the operand vector and initializes it. /// The new operands must be set explicitly later. /// void MachineInstr::replace(short opcode, unsigned numOperands) { assert(getNumImplicitRefs() == 0 && "This is probably broken because implicit refs are going to be lost."); Opcode = opcode; operands.clear(); operands.resize(numOperands, MachineOperand()); } void MachineInstr::SetMachineOperandVal(unsigned i, MachineOperand::MachineOperandType opTy, Value* V) { assert(i < operands.size()); // may be explicit or implicit op operands[i].opType = opTy; operands[i].value = V; operands[i].regNum = -1; } void MachineInstr::SetMachineOperandConst(unsigned i, MachineOperand::MachineOperandType opTy, int64_t intValue) { assert(i < getNumOperands()); // must be explicit op assert(TargetInstrDescriptors[Opcode].resultPos != (int) i && "immed. constant cannot be defined"); operands[i].opType = opTy; operands[i].value = NULL; operands[i].immedVal = intValue; operands[i].regNum = -1; operands[i].flags = 0; } void MachineInstr::SetMachineOperandReg(unsigned i, int regNum) { assert(i < getNumOperands()); // must be explicit op operands[i].opType = MachineOperand::MO_MachineRegister; operands[i].value = NULL; operands[i].regNum = regNum; } // Used only by the SPARC back-end. void MachineInstr::SetRegForOperand(unsigned i, int regNum) { assert(i < getNumOperands()); // must be explicit op operands[i].setRegForValue(regNum); } // Used only by the SPARC back-end. void MachineInstr::SetRegForImplicitRef(unsigned i, int regNum) { getImplicitOp(i).setRegForValue(regNum); } /// substituteValue - Substitute all occurrences of Value* oldVal with newVal /// in all operands and all implicit refs. If defsOnly == true, substitute defs /// only. /// /// FIXME: Fold this into its single caller, at SparcInstrSelection.cpp:2865, /// or make it a static function in that file. /// unsigned MachineInstr::substituteValue(const Value* oldVal, Value* newVal, bool defsOnly, bool notDefsAndUses, bool& someArgsWereIgnored) { assert((!defsOnly || !notDefsAndUses) && "notDefsAndUses is irrelevant if defsOnly == true."); unsigned numSubst = 0; // Substitute operands for (MachineInstr::val_op_iterator O = begin(), E = end(); O != E; ++O) if (*O == oldVal) if (!defsOnly || notDefsAndUses && (O.isDef() && !O.isUse()) || !notDefsAndUses && O.isDef()) { O.getMachineOperand().value = newVal; ++numSubst; } else someArgsWereIgnored = true; // Substitute implicit refs for (unsigned i=0, N=getNumImplicitRefs(); i < N; ++i) if (getImplicitRef(i) == oldVal) if (!defsOnly || notDefsAndUses && (getImplicitOp(i).isDef() && !getImplicitOp(i).isUse()) || !notDefsAndUses && getImplicitOp(i).isDef()) { getImplicitOp(i).value = newVal; ++numSubst; } else someArgsWereIgnored = true; return numSubst; } void MachineInstr::dump() const { std::cerr << " " << *this; } static inline std::ostream& OutputValue(std::ostream &os, const Value* val) { os << "(val "; os << (void*) val; // print address always if (val && val->hasName()) os << " " << val->getName(); // print name also, if available os << ")"; return os; } static inline void OutputReg(std::ostream &os, unsigned RegNo, const MRegisterInfo *MRI = 0) { if (!RegNo || MRegisterInfo::isPhysicalRegister(RegNo)) { if (MRI) os << "%" << MRI->get(RegNo).Name; else os << "%mreg(" << RegNo << ")"; } else os << "%reg" << RegNo; } static void print(const MachineOperand &MO, std::ostream &OS, const TargetMachine &TM) { const MRegisterInfo *MRI = TM.getRegisterInfo(); bool CloseParen = true; if (MO.isHiBits32()) OS << "%lm("; else if (MO.isLoBits32()) OS << "%lo("; else if (MO.isHiBits64()) OS << "%hh("; else if (MO.isLoBits64()) OS << "%hm("; else CloseParen = false; switch (MO.getType()) { case MachineOperand::MO_VirtualRegister: if (MO.getVRegValue()) { OS << "%reg"; OutputValue(OS, MO.getVRegValue()); if (MO.hasAllocatedReg()) OS << "=="; } if (MO.hasAllocatedReg()) OutputReg(OS, MO.getReg(), MRI); break; case MachineOperand::MO_CCRegister: OS << "%ccreg"; OutputValue(OS, MO.getVRegValue()); if (MO.hasAllocatedReg()) { OS << "=="; OutputReg(OS, MO.getReg(), MRI); } break; case MachineOperand::MO_MachineRegister: OutputReg(OS, MO.getMachineRegNum(), MRI); break; case MachineOperand::MO_SignExtendedImmed: OS << (long)MO.getImmedValue(); break; case MachineOperand::MO_UnextendedImmed: OS << (long)MO.getImmedValue(); break; case MachineOperand::MO_PCRelativeDisp: { const Value* opVal = MO.getVRegValue(); bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal); OS << "%disp(" << (isLabel? "label " : "addr-of-val "); if (opVal->hasName()) OS << opVal->getName(); else OS << (const void*) opVal; OS << ")"; break; } case MachineOperand::MO_MachineBasicBlock: OS << "bb<" << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName() << "," << (void*)MO.getMachineBasicBlock()->getBasicBlock() << ">"; break; case MachineOperand::MO_FrameIndex: OS << "<fi#" << MO.getFrameIndex() << ">"; break; case MachineOperand::MO_ConstantPoolIndex: OS << "<cp#" << MO.getConstantPoolIndex() << ">"; break; case MachineOperand::MO_GlobalAddress: OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">"; break; case MachineOperand::MO_ExternalSymbol: OS << "<es:" << MO.getSymbolName() << ">"; break; default: assert(0 && "Unrecognized operand type"); } if (CloseParen) OS << ")"; } void MachineInstr::print(std::ostream &OS, const TargetMachine &TM) const { unsigned StartOp = 0; // Specialize printing if op#0 is definition if (getNumOperands() && getOperand(0).isDef() && !getOperand(0).isUse()) { ::print(getOperand(0), OS, TM); OS << " = "; ++StartOp; // Don't print this operand again! } OS << TM.getInstrInfo().getName(getOpcode()); for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) { const MachineOperand& mop = getOperand(i); if (i != StartOp) OS << ","; OS << " "; ::print(mop, OS, TM); if (mop.isDef()) if (mop.isUse()) OS << "<def&use>"; else OS << "<def>"; } // code for printing implicit references if (getNumImplicitRefs()) { OS << "\tImplicitRefs: "; for(unsigned i = 0, e = getNumImplicitRefs(); i != e; ++i) { OS << "\t"; OutputValue(OS, getImplicitRef(i)); if (getImplicitOp(i).isDef()) if (getImplicitOp(i).isUse()) OS << "<def&use>"; else OS << "<def>"; } } OS << "\n"; } namespace llvm { std::ostream &operator<<(std::ostream &os, const MachineInstr &MI) { // If the instruction is embedded into a basic block, we can find the target // info for the instruction. if (const MachineBasicBlock *MBB = MI.getParent()) { const MachineFunction *MF = MBB->getParent(); MI.print(os, MF->getTarget()); return os; } // Otherwise, print it out in the "raw" format without symbolic register names // and such. os << TargetInstrDescriptors[MI.getOpcode()].Name; for (unsigned i=0, N=MI.getNumOperands(); i < N; i++) { os << "\t" << MI.getOperand(i); if (MI.getOperand(i).isDef()) if (MI.getOperand(i).isUse()) os << "<d&u>"; else os << "<d>"; } // code for printing implicit references unsigned NumOfImpRefs = MI.getNumImplicitRefs(); if (NumOfImpRefs > 0) { os << "\tImplicit: "; for (unsigned z=0; z < NumOfImpRefs; z++) { OutputValue(os, MI.getImplicitRef(z)); if (MI.getImplicitOp(z).isDef()) if (MI.getImplicitOp(z).isUse()) os << "<d&u>"; else os << "<d>"; os << "\t"; } } return os << "\n"; } std::ostream &operator<<(std::ostream &OS, const MachineOperand &MO) { if (MO.isHiBits32()) OS << "%lm("; else if (MO.isLoBits32()) OS << "%lo("; else if (MO.isHiBits64()) OS << "%hh("; else if (MO.isLoBits64()) OS << "%hm("; switch (MO.getType()) { case MachineOperand::MO_VirtualRegister: if (MO.hasAllocatedReg()) OutputReg(OS, MO.getReg()); if (MO.getVRegValue()) { if (MO.hasAllocatedReg()) OS << "=="; OS << "%vreg"; OutputValue(OS, MO.getVRegValue()); } break; case MachineOperand::MO_CCRegister: OS << "%ccreg"; OutputValue(OS, MO.getVRegValue()); if (MO.hasAllocatedReg()) { OS << "=="; OutputReg(OS, MO.getReg()); } break; case MachineOperand::MO_MachineRegister: OutputReg(OS, MO.getMachineRegNum()); break; case MachineOperand::MO_SignExtendedImmed: OS << (long)MO.getImmedValue(); break; case MachineOperand::MO_UnextendedImmed: OS << (long)MO.getImmedValue(); break; case MachineOperand::MO_PCRelativeDisp: { const Value* opVal = MO.getVRegValue(); bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal); OS << "%disp(" << (isLabel? "label " : "addr-of-val "); if (opVal->hasName()) OS << opVal->getName(); else OS << (const void*) opVal; OS << ")"; break; } case MachineOperand::MO_MachineBasicBlock: OS << "bb<" << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName() << "," << (void*)MO.getMachineBasicBlock()->getBasicBlock() << ">"; break; case MachineOperand::MO_FrameIndex: OS << "<fi#" << MO.getFrameIndex() << ">"; break; case MachineOperand::MO_ConstantPoolIndex: OS << "<cp#" << MO.getConstantPoolIndex() << ">"; break; case MachineOperand::MO_GlobalAddress: OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">"; break; case MachineOperand::MO_ExternalSymbol: OS << "<es:" << MO.getSymbolName() << ">"; break; default: assert(0 && "Unrecognized operand type"); break; } if (MO.isHiBits32() || MO.isLoBits32() || MO.isHiBits64() || MO.isLoBits64()) OS << ")"; return OS; } } <commit_msg>int64_t -> int<commit_after>//===-- MachineInstr.cpp --------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Methods common to all machine instructions. // // FIXME: Now that MachineInstrs have parent pointers, they should always // print themselves using their MachineFunction's TargetMachine. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/Value.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/MRegisterInfo.h" #include "Support/LeakDetector.h" using namespace llvm; // Global variable holding an array of descriptors for machine instructions. // The actual object needs to be created separately for each target machine. // This variable is initialized and reset by class TargetInstrInfo. // // FIXME: This should be a property of the target so that more than one target // at a time can be active... // namespace llvm { extern const TargetInstrDescriptor *TargetInstrDescriptors; } // Constructor for instructions with variable #operands MachineInstr::MachineInstr(short opcode, unsigned numOperands) : Opcode(opcode), numImplicitRefs(0), operands(numOperands, MachineOperand()), parent(0) { // Make sure that we get added to a machine basicblock LeakDetector::addGarbageObject(this); } /// MachineInstr ctor - This constructor only does a _reserve_ of the operands, /// not a resize for them. It is expected that if you use this that you call /// add* methods below to fill up the operands, instead of the Set methods. /// Eventually, the "resizing" ctors will be phased out. /// MachineInstr::MachineInstr(short opcode, unsigned numOperands, bool XX, bool YY) : Opcode(opcode), numImplicitRefs(0), parent(0) { operands.reserve(numOperands); // Make sure that we get added to a machine basicblock LeakDetector::addGarbageObject(this); } /// MachineInstr ctor - Work exactly the same as the ctor above, except that the /// MachineInstr is created and added to the end of the specified basic block. /// MachineInstr::MachineInstr(MachineBasicBlock *MBB, short opcode, unsigned numOperands) : Opcode(opcode), numImplicitRefs(0), parent(0) { assert(MBB && "Cannot use inserting ctor with null basic block!"); operands.reserve(numOperands); // Make sure that we get added to a machine basicblock LeakDetector::addGarbageObject(this); MBB->push_back(this); // Add instruction to end of basic block! } MachineInstr::~MachineInstr() { LeakDetector::removeGarbageObject(this); } /// OperandComplete - Return true if it's illegal to add a new operand /// bool MachineInstr::OperandsComplete() const { int NumOperands = TargetInstrDescriptors[Opcode].numOperands; if (NumOperands >= 0 && getNumOperands() >= (unsigned)NumOperands) return true; // Broken: we have all the operands of this instruction! return false; } /// replace - Support for replacing opcode and operands of a MachineInstr in /// place. This only resets the size of the operand vector and initializes it. /// The new operands must be set explicitly later. /// void MachineInstr::replace(short opcode, unsigned numOperands) { assert(getNumImplicitRefs() == 0 && "This is probably broken because implicit refs are going to be lost."); Opcode = opcode; operands.clear(); operands.resize(numOperands, MachineOperand()); } void MachineInstr::SetMachineOperandVal(unsigned i, MachineOperand::MachineOperandType opTy, Value* V) { assert(i < operands.size()); // may be explicit or implicit op operands[i].opType = opTy; operands[i].value = V; operands[i].regNum = -1; } void MachineInstr::SetMachineOperandConst(unsigned i, MachineOperand::MachineOperandType opTy, int intValue) { assert(i < getNumOperands()); // must be explicit op assert(TargetInstrDescriptors[Opcode].resultPos != (int) i && "immed. constant cannot be defined"); operands[i].opType = opTy; operands[i].value = NULL; operands[i].immedVal = intValue; operands[i].regNum = -1; operands[i].flags = 0; } void MachineInstr::SetMachineOperandReg(unsigned i, int regNum) { assert(i < getNumOperands()); // must be explicit op operands[i].opType = MachineOperand::MO_MachineRegister; operands[i].value = NULL; operands[i].regNum = regNum; } // Used only by the SPARC back-end. void MachineInstr::SetRegForOperand(unsigned i, int regNum) { assert(i < getNumOperands()); // must be explicit op operands[i].setRegForValue(regNum); } // Used only by the SPARC back-end. void MachineInstr::SetRegForImplicitRef(unsigned i, int regNum) { getImplicitOp(i).setRegForValue(regNum); } /// substituteValue - Substitute all occurrences of Value* oldVal with newVal /// in all operands and all implicit refs. If defsOnly == true, substitute defs /// only. /// /// FIXME: Fold this into its single caller, at SparcInstrSelection.cpp:2865, /// or make it a static function in that file. /// unsigned MachineInstr::substituteValue(const Value* oldVal, Value* newVal, bool defsOnly, bool notDefsAndUses, bool& someArgsWereIgnored) { assert((!defsOnly || !notDefsAndUses) && "notDefsAndUses is irrelevant if defsOnly == true."); unsigned numSubst = 0; // Substitute operands for (MachineInstr::val_op_iterator O = begin(), E = end(); O != E; ++O) if (*O == oldVal) if (!defsOnly || notDefsAndUses && (O.isDef() && !O.isUse()) || !notDefsAndUses && O.isDef()) { O.getMachineOperand().value = newVal; ++numSubst; } else someArgsWereIgnored = true; // Substitute implicit refs for (unsigned i=0, N=getNumImplicitRefs(); i < N; ++i) if (getImplicitRef(i) == oldVal) if (!defsOnly || notDefsAndUses && (getImplicitOp(i).isDef() && !getImplicitOp(i).isUse()) || !notDefsAndUses && getImplicitOp(i).isDef()) { getImplicitOp(i).value = newVal; ++numSubst; } else someArgsWereIgnored = true; return numSubst; } void MachineInstr::dump() const { std::cerr << " " << *this; } static inline std::ostream& OutputValue(std::ostream &os, const Value* val) { os << "(val "; os << (void*) val; // print address always if (val && val->hasName()) os << " " << val->getName(); // print name also, if available os << ")"; return os; } static inline void OutputReg(std::ostream &os, unsigned RegNo, const MRegisterInfo *MRI = 0) { if (!RegNo || MRegisterInfo::isPhysicalRegister(RegNo)) { if (MRI) os << "%" << MRI->get(RegNo).Name; else os << "%mreg(" << RegNo << ")"; } else os << "%reg" << RegNo; } static void print(const MachineOperand &MO, std::ostream &OS, const TargetMachine &TM) { const MRegisterInfo *MRI = TM.getRegisterInfo(); bool CloseParen = true; if (MO.isHiBits32()) OS << "%lm("; else if (MO.isLoBits32()) OS << "%lo("; else if (MO.isHiBits64()) OS << "%hh("; else if (MO.isLoBits64()) OS << "%hm("; else CloseParen = false; switch (MO.getType()) { case MachineOperand::MO_VirtualRegister: if (MO.getVRegValue()) { OS << "%reg"; OutputValue(OS, MO.getVRegValue()); if (MO.hasAllocatedReg()) OS << "=="; } if (MO.hasAllocatedReg()) OutputReg(OS, MO.getReg(), MRI); break; case MachineOperand::MO_CCRegister: OS << "%ccreg"; OutputValue(OS, MO.getVRegValue()); if (MO.hasAllocatedReg()) { OS << "=="; OutputReg(OS, MO.getReg(), MRI); } break; case MachineOperand::MO_MachineRegister: OutputReg(OS, MO.getMachineRegNum(), MRI); break; case MachineOperand::MO_SignExtendedImmed: OS << (long)MO.getImmedValue(); break; case MachineOperand::MO_UnextendedImmed: OS << (long)MO.getImmedValue(); break; case MachineOperand::MO_PCRelativeDisp: { const Value* opVal = MO.getVRegValue(); bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal); OS << "%disp(" << (isLabel? "label " : "addr-of-val "); if (opVal->hasName()) OS << opVal->getName(); else OS << (const void*) opVal; OS << ")"; break; } case MachineOperand::MO_MachineBasicBlock: OS << "bb<" << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName() << "," << (void*)MO.getMachineBasicBlock()->getBasicBlock() << ">"; break; case MachineOperand::MO_FrameIndex: OS << "<fi#" << MO.getFrameIndex() << ">"; break; case MachineOperand::MO_ConstantPoolIndex: OS << "<cp#" << MO.getConstantPoolIndex() << ">"; break; case MachineOperand::MO_GlobalAddress: OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">"; break; case MachineOperand::MO_ExternalSymbol: OS << "<es:" << MO.getSymbolName() << ">"; break; default: assert(0 && "Unrecognized operand type"); } if (CloseParen) OS << ")"; } void MachineInstr::print(std::ostream &OS, const TargetMachine &TM) const { unsigned StartOp = 0; // Specialize printing if op#0 is definition if (getNumOperands() && getOperand(0).isDef() && !getOperand(0).isUse()) { ::print(getOperand(0), OS, TM); OS << " = "; ++StartOp; // Don't print this operand again! } OS << TM.getInstrInfo().getName(getOpcode()); for (unsigned i = StartOp, e = getNumOperands(); i != e; ++i) { const MachineOperand& mop = getOperand(i); if (i != StartOp) OS << ","; OS << " "; ::print(mop, OS, TM); if (mop.isDef()) if (mop.isUse()) OS << "<def&use>"; else OS << "<def>"; } // code for printing implicit references if (getNumImplicitRefs()) { OS << "\tImplicitRefs: "; for(unsigned i = 0, e = getNumImplicitRefs(); i != e; ++i) { OS << "\t"; OutputValue(OS, getImplicitRef(i)); if (getImplicitOp(i).isDef()) if (getImplicitOp(i).isUse()) OS << "<def&use>"; else OS << "<def>"; } } OS << "\n"; } namespace llvm { std::ostream &operator<<(std::ostream &os, const MachineInstr &MI) { // If the instruction is embedded into a basic block, we can find the target // info for the instruction. if (const MachineBasicBlock *MBB = MI.getParent()) { const MachineFunction *MF = MBB->getParent(); MI.print(os, MF->getTarget()); return os; } // Otherwise, print it out in the "raw" format without symbolic register names // and such. os << TargetInstrDescriptors[MI.getOpcode()].Name; for (unsigned i=0, N=MI.getNumOperands(); i < N; i++) { os << "\t" << MI.getOperand(i); if (MI.getOperand(i).isDef()) if (MI.getOperand(i).isUse()) os << "<d&u>"; else os << "<d>"; } // code for printing implicit references unsigned NumOfImpRefs = MI.getNumImplicitRefs(); if (NumOfImpRefs > 0) { os << "\tImplicit: "; for (unsigned z=0; z < NumOfImpRefs; z++) { OutputValue(os, MI.getImplicitRef(z)); if (MI.getImplicitOp(z).isDef()) if (MI.getImplicitOp(z).isUse()) os << "<d&u>"; else os << "<d>"; os << "\t"; } } return os << "\n"; } std::ostream &operator<<(std::ostream &OS, const MachineOperand &MO) { if (MO.isHiBits32()) OS << "%lm("; else if (MO.isLoBits32()) OS << "%lo("; else if (MO.isHiBits64()) OS << "%hh("; else if (MO.isLoBits64()) OS << "%hm("; switch (MO.getType()) { case MachineOperand::MO_VirtualRegister: if (MO.hasAllocatedReg()) OutputReg(OS, MO.getReg()); if (MO.getVRegValue()) { if (MO.hasAllocatedReg()) OS << "=="; OS << "%vreg"; OutputValue(OS, MO.getVRegValue()); } break; case MachineOperand::MO_CCRegister: OS << "%ccreg"; OutputValue(OS, MO.getVRegValue()); if (MO.hasAllocatedReg()) { OS << "=="; OutputReg(OS, MO.getReg()); } break; case MachineOperand::MO_MachineRegister: OutputReg(OS, MO.getMachineRegNum()); break; case MachineOperand::MO_SignExtendedImmed: OS << (long)MO.getImmedValue(); break; case MachineOperand::MO_UnextendedImmed: OS << (long)MO.getImmedValue(); break; case MachineOperand::MO_PCRelativeDisp: { const Value* opVal = MO.getVRegValue(); bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal); OS << "%disp(" << (isLabel? "label " : "addr-of-val "); if (opVal->hasName()) OS << opVal->getName(); else OS << (const void*) opVal; OS << ")"; break; } case MachineOperand::MO_MachineBasicBlock: OS << "bb<" << ((Value*)MO.getMachineBasicBlock()->getBasicBlock())->getName() << "," << (void*)MO.getMachineBasicBlock()->getBasicBlock() << ">"; break; case MachineOperand::MO_FrameIndex: OS << "<fi#" << MO.getFrameIndex() << ">"; break; case MachineOperand::MO_ConstantPoolIndex: OS << "<cp#" << MO.getConstantPoolIndex() << ">"; break; case MachineOperand::MO_GlobalAddress: OS << "<ga:" << ((Value*)MO.getGlobal())->getName() << ">"; break; case MachineOperand::MO_ExternalSymbol: OS << "<es:" << MO.getSymbolName() << ">"; break; default: assert(0 && "Unrecognized operand type"); break; } if (MO.isHiBits32() || MO.isLoBits32() || MO.isHiBits64() || MO.isLoBits64()) OS << ")"; return OS; } } <|endoftext|>
<commit_before>// Copyright 2020 Chia Network Inc // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in coiance 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 iied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SRC_BLSSCHEMES_HPP_ #define SRC_BLSSCHEMES_HPP_ #include <iostream> #include <vector> #include <relic_conf.h> #if defined GMP && ARITH == GMP #include <gmp.h> #endif #include "elements.hpp" #include "privatekey.hpp" using std::vector; // These are all MPL schemes namespace bls { class Bytes; class CoreMPL { public: CoreMPL() = delete; CoreMPL(const std::string& strId) : strCiphersuiteId(strId) {} // Generates a private key from a seed, similar to HD key generation // (hashes the seed), and reduces it mod the group order virtual PrivateKey KeyGen(const vector<uint8_t>& seed); virtual PrivateKey KeyGen(const Bytes& seed); // Generates a public key from a secret key virtual vector<uint8_t> SkToPk(const PrivateKey &seckey); virtual G1Element SkToG1(const PrivateKey &seckey); virtual G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message); virtual G2Element Sign(const PrivateKey& seckey, const Bytes& message); virtual bool Verify(const vector<uint8_t> &pubkey, const vector<uint8_t> &message, const vector<uint8_t> &signature); virtual bool Verify(const Bytes& pubkey, const Bytes& message, const Bytes& signature); virtual bool Verify(const G1Element &pubkey, const vector<uint8_t> &message, const G2Element &signature); virtual bool Verify(const G1Element& pubkey, const Bytes& message, const G2Element& signature); virtual vector<uint8_t> Aggregate(const vector<vector<uint8_t>> &signatures); virtual vector<uint8_t> Aggregate(const vector<Bytes>& signatures); virtual G2Element Aggregate(const vector<G2Element> &signatures); virtual G1Element Aggregate(const vector<G1Element> &publicKeys); virtual G2Element AggregateSecure(const std::vector<G1Element>& vecPublicKeys, const std::vector<G2Element>& vecSignatures, const Bytes& message); virtual bool VerifySecure(const std::vector<G1Element>& vecPublicKeys, const G2Element& signature, const Bytes& message); virtual bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys, const vector<vector<uint8_t>> &messages, const vector<uint8_t> &signature); virtual bool AggregateVerify(const vector<Bytes>& pubkeys, const vector<Bytes>& messages, const Bytes& signature); virtual bool AggregateVerify(const vector<G1Element> &pubkeys, const vector<vector<uint8_t>> &messages, const G2Element &signature); virtual bool AggregateVerify(const vector<G1Element>& pubkeys, const vector<Bytes>& messages, const G2Element& signature); PrivateKey DeriveChildSk(const PrivateKey& sk, uint32_t index); PrivateKey DeriveChildSkUnhardened(const PrivateKey& sk, uint32_t index); G1Element DeriveChildPkUnhardened(const G1Element& sk, uint32_t index); protected: const std::string& strCiphersuiteId; bool NativeVerify(g1_t *pubKeys, g2_t *mappedHashes, size_t length); G2Element AggregateSecure(std::vector<G1Element> const &vecPublicKeys, std::vector<G2Element> const &vecSignatures, const Bytes& message, bool fLegacy); bool VerifySecure(const std::vector<G1Element>& vecPublicKeys, const G2Element& signature, const Bytes& message, bool fLegacy); }; class BasicSchemeMPL : public CoreMPL { public: static const std::string CIPHERSUITE_ID; BasicSchemeMPL() : CoreMPL(BasicSchemeMPL::CIPHERSUITE_ID) {} bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys, const vector<vector<uint8_t>> &messages, const vector<uint8_t> &signature) override; bool AggregateVerify(const vector<Bytes>& pubkeys, const vector<Bytes>& messages, const Bytes& signature) override; bool AggregateVerify(const vector<G1Element> &pubkeys, const vector<vector<uint8_t>> &messages, const G2Element &signature) override; bool AggregateVerify(const vector<G1Element>& pubkeys, const vector<Bytes>& messages, const G2Element& signature) override; }; class AugSchemeMPL : public CoreMPL { public: static const std::string CIPHERSUITE_ID; AugSchemeMPL() : CoreMPL(AugSchemeMPL::CIPHERSUITE_ID) {} G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message) override; G2Element Sign(const PrivateKey& seckey, const Bytes& message) override; // Used for prepending different augMessage G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message, const G1Element &prepend_pk); // Used for prepending different augMessage G2Element Sign(const PrivateKey& seckey, const Bytes& message, const G1Element& prepend_pk); bool Verify(const vector<uint8_t> &pubkey, const vector<uint8_t> &message, const vector<uint8_t> &signature) override; bool Verify(const Bytes& pubkey, const Bytes& message, const Bytes& signature) override; bool Verify(const G1Element &pubkey, const vector<uint8_t> &message, const G2Element &signature) override; bool Verify(const G1Element& pubkey, const Bytes& message, const G2Element& signature) override; bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys, const vector<vector<uint8_t>> &messages, const vector<uint8_t> &signature) override; bool AggregateVerify(const vector<Bytes>& pubkeys, const vector<Bytes>& messages, const Bytes& signature) override; bool AggregateVerify(const vector<G1Element> &pubkeys, const vector<vector<uint8_t>> &messages, const G2Element &signature) override; bool AggregateVerify(const vector<G1Element>& pubkeys, const vector<Bytes>& messages, const G2Element& signature) override; }; class PopSchemeMPL : public CoreMPL { public: static const std::string CIPHERSUITE_ID; static const std::string POP_CIPHERSUITE_ID; PopSchemeMPL() : CoreMPL(PopSchemeMPL::CIPHERSUITE_ID) {} G2Element PopProve(const PrivateKey &seckey); bool PopVerify(const G1Element &pubkey, const G2Element &signature_proof); bool PopVerify(const vector<uint8_t> &pubkey, const vector<uint8_t> &proof); bool PopVerify(const Bytes& pubkey, const Bytes& proof); bool FastAggregateVerify(const vector<G1Element> &pubkeys, const vector<uint8_t> &message, const G2Element &signature); bool FastAggregateVerify(const vector<G1Element>& pubkeys, const Bytes& message, const G2Element& signature); bool FastAggregateVerify(const vector<vector<uint8_t>> &pubkeys, const vector<uint8_t> &message, const vector<uint8_t> &signature); bool FastAggregateVerify(const vector<Bytes>& pubkeys, const Bytes& message, const Bytes& signature); }; /** * This scheme reflects the Sign/Verify behaviour of older bls-signatures library versions (<0.1.29). */ class LegacySchemeMPL : public CoreMPL { public: LegacySchemeMPL() : CoreMPL(std::string{}) {} virtual vector<uint8_t> SkToPk(const PrivateKey &seckey) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } G2Element Sign(const PrivateKey &seckey, const Bytes& message) final; bool Verify(const vector<uint8_t>& pubkey, const vector<uint8_t>& message, const vector<uint8_t>& signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } bool Verify(const G1Element& pubkey, const vector<uint8_t>& message, const G2Element& signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } bool Verify(const Bytes& pubkey, const Bytes& message, const Bytes& signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } bool Verify(const G1Element &pubkey, const Bytes& message, const G2Element &signature) final; vector<uint8_t> Aggregate(const vector<vector<uint8_t>> &signatures) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } G2Element AggregateSecure(const std::vector<G1Element>& vecPublicKeys, const std::vector<G2Element>& vecSignatures, const Bytes& message) final; bool VerifySecure(const std::vector<G1Element>& vecPublicKeys, const G2Element& signature, const Bytes& message) final; bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys, const vector<vector<uint8_t>> &messages, const vector<uint8_t> &signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } bool AggregateVerify(const vector<Bytes> &pubkeys, const vector<Bytes> &messages, const Bytes &signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } bool AggregateVerify(const vector<G1Element> &pubkeys, const vector<vector<uint8_t>> &messages, const G2Element &signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } bool AggregateVerify(const vector<G1Element> &pubkeys, const vector<Bytes> &messages, const G2Element &signature) final; }; } // end namespace bls #endif // SRC_BLSSCHEMES_HPP_ <commit_msg>add virtual dtor's for scheme's in new BLS impl<commit_after>// Copyright 2020 Chia Network Inc // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in coiance 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 iied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef SRC_BLSSCHEMES_HPP_ #define SRC_BLSSCHEMES_HPP_ #include <iostream> #include <vector> #include <relic_conf.h> #if defined GMP && ARITH == GMP #include <gmp.h> #endif #include "elements.hpp" #include "privatekey.hpp" using std::vector; // These are all MPL schemes namespace bls { class Bytes; class CoreMPL { public: virtual ~CoreMPL() {}; CoreMPL() = delete; CoreMPL(const std::string& strId) : strCiphersuiteId(strId) {} // Generates a private key from a seed, similar to HD key generation // (hashes the seed), and reduces it mod the group order virtual PrivateKey KeyGen(const vector<uint8_t>& seed); virtual PrivateKey KeyGen(const Bytes& seed); // Generates a public key from a secret key virtual vector<uint8_t> SkToPk(const PrivateKey &seckey); virtual G1Element SkToG1(const PrivateKey &seckey); virtual G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message); virtual G2Element Sign(const PrivateKey& seckey, const Bytes& message); virtual bool Verify(const vector<uint8_t> &pubkey, const vector<uint8_t> &message, const vector<uint8_t> &signature); virtual bool Verify(const Bytes& pubkey, const Bytes& message, const Bytes& signature); virtual bool Verify(const G1Element &pubkey, const vector<uint8_t> &message, const G2Element &signature); virtual bool Verify(const G1Element& pubkey, const Bytes& message, const G2Element& signature); virtual vector<uint8_t> Aggregate(const vector<vector<uint8_t>> &signatures); virtual vector<uint8_t> Aggregate(const vector<Bytes>& signatures); virtual G2Element Aggregate(const vector<G2Element> &signatures); virtual G1Element Aggregate(const vector<G1Element> &publicKeys); virtual G2Element AggregateSecure(const std::vector<G1Element>& vecPublicKeys, const std::vector<G2Element>& vecSignatures, const Bytes& message); virtual bool VerifySecure(const std::vector<G1Element>& vecPublicKeys, const G2Element& signature, const Bytes& message); virtual bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys, const vector<vector<uint8_t>> &messages, const vector<uint8_t> &signature); virtual bool AggregateVerify(const vector<Bytes>& pubkeys, const vector<Bytes>& messages, const Bytes& signature); virtual bool AggregateVerify(const vector<G1Element> &pubkeys, const vector<vector<uint8_t>> &messages, const G2Element &signature); virtual bool AggregateVerify(const vector<G1Element>& pubkeys, const vector<Bytes>& messages, const G2Element& signature); PrivateKey DeriveChildSk(const PrivateKey& sk, uint32_t index); PrivateKey DeriveChildSkUnhardened(const PrivateKey& sk, uint32_t index); G1Element DeriveChildPkUnhardened(const G1Element& sk, uint32_t index); protected: const std::string& strCiphersuiteId; bool NativeVerify(g1_t *pubKeys, g2_t *mappedHashes, size_t length); G2Element AggregateSecure(std::vector<G1Element> const &vecPublicKeys, std::vector<G2Element> const &vecSignatures, const Bytes& message, bool fLegacy); bool VerifySecure(const std::vector<G1Element>& vecPublicKeys, const G2Element& signature, const Bytes& message, bool fLegacy); }; class BasicSchemeMPL : public CoreMPL { public: virtual ~BasicSchemeMPL() {}; static const std::string CIPHERSUITE_ID; BasicSchemeMPL() : CoreMPL(BasicSchemeMPL::CIPHERSUITE_ID) {} bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys, const vector<vector<uint8_t>> &messages, const vector<uint8_t> &signature) override; bool AggregateVerify(const vector<Bytes>& pubkeys, const vector<Bytes>& messages, const Bytes& signature) override; bool AggregateVerify(const vector<G1Element> &pubkeys, const vector<vector<uint8_t>> &messages, const G2Element &signature) override; bool AggregateVerify(const vector<G1Element>& pubkeys, const vector<Bytes>& messages, const G2Element& signature) override; }; class AugSchemeMPL : public CoreMPL { public: virtual ~AugSchemeMPL() {}; static const std::string CIPHERSUITE_ID; AugSchemeMPL() : CoreMPL(AugSchemeMPL::CIPHERSUITE_ID) {} G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message) override; G2Element Sign(const PrivateKey& seckey, const Bytes& message) override; // Used for prepending different augMessage G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message, const G1Element &prepend_pk); // Used for prepending different augMessage G2Element Sign(const PrivateKey& seckey, const Bytes& message, const G1Element& prepend_pk); bool Verify(const vector<uint8_t> &pubkey, const vector<uint8_t> &message, const vector<uint8_t> &signature) override; bool Verify(const Bytes& pubkey, const Bytes& message, const Bytes& signature) override; bool Verify(const G1Element &pubkey, const vector<uint8_t> &message, const G2Element &signature) override; bool Verify(const G1Element& pubkey, const Bytes& message, const G2Element& signature) override; bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys, const vector<vector<uint8_t>> &messages, const vector<uint8_t> &signature) override; bool AggregateVerify(const vector<Bytes>& pubkeys, const vector<Bytes>& messages, const Bytes& signature) override; bool AggregateVerify(const vector<G1Element> &pubkeys, const vector<vector<uint8_t>> &messages, const G2Element &signature) override; bool AggregateVerify(const vector<G1Element>& pubkeys, const vector<Bytes>& messages, const G2Element& signature) override; }; class PopSchemeMPL : public CoreMPL { public: virtual ~PopSchemeMPL() {}; static const std::string CIPHERSUITE_ID; static const std::string POP_CIPHERSUITE_ID; PopSchemeMPL() : CoreMPL(PopSchemeMPL::CIPHERSUITE_ID) {} G2Element PopProve(const PrivateKey &seckey); bool PopVerify(const G1Element &pubkey, const G2Element &signature_proof); bool PopVerify(const vector<uint8_t> &pubkey, const vector<uint8_t> &proof); bool PopVerify(const Bytes& pubkey, const Bytes& proof); bool FastAggregateVerify(const vector<G1Element> &pubkeys, const vector<uint8_t> &message, const G2Element &signature); bool FastAggregateVerify(const vector<G1Element>& pubkeys, const Bytes& message, const G2Element& signature); bool FastAggregateVerify(const vector<vector<uint8_t>> &pubkeys, const vector<uint8_t> &message, const vector<uint8_t> &signature); bool FastAggregateVerify(const vector<Bytes>& pubkeys, const Bytes& message, const Bytes& signature); }; /** * This scheme reflects the Sign/Verify behaviour of older bls-signatures library versions (<0.1.29). */ class LegacySchemeMPL : public CoreMPL { public: virtual ~LegacySchemeMPL() {}; LegacySchemeMPL() : CoreMPL(std::string{}) {} virtual vector<uint8_t> SkToPk(const PrivateKey &seckey) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } G2Element Sign(const PrivateKey &seckey, const Bytes& message) final; bool Verify(const vector<uint8_t>& pubkey, const vector<uint8_t>& message, const vector<uint8_t>& signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } bool Verify(const G1Element& pubkey, const vector<uint8_t>& message, const G2Element& signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } bool Verify(const Bytes& pubkey, const Bytes& message, const Bytes& signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } bool Verify(const G1Element &pubkey, const Bytes& message, const G2Element &signature) final; vector<uint8_t> Aggregate(const vector<vector<uint8_t>> &signatures) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } G2Element AggregateSecure(const std::vector<G1Element>& vecPublicKeys, const std::vector<G2Element>& vecSignatures, const Bytes& message) final; bool VerifySecure(const std::vector<G1Element>& vecPublicKeys, const G2Element& signature, const Bytes& message) final; bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys, const vector<vector<uint8_t>> &messages, const vector<uint8_t> &signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } bool AggregateVerify(const vector<Bytes> &pubkeys, const vector<Bytes> &messages, const Bytes &signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } bool AggregateVerify(const vector<G1Element> &pubkeys, const vector<vector<uint8_t>> &messages, const G2Element &signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); } bool AggregateVerify(const vector<G1Element> &pubkeys, const vector<Bytes> &messages, const G2Element &signature) final; }; } // end namespace bls #endif // SRC_BLSSCHEMES_HPP_ <|endoftext|>
<commit_before>// dune-multiscale // Copyright Holders: Patrick Henning, Rene Milk // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #include "common.hh" #include <dune/multiscale/msfem/algorithm.hh> #include <dune/multiscale/problems/elliptic/selector.hh> int main(int argc, char** argv) { try { init(argc, argv); using namespace Dune::Multiscale; using namespace Dune::Multiscale::MsFEM; //!TODO include base in config DSC_PROFILER.startTiming("msfem.all"); const std::string datadir = DSC_CONFIG_GET("global.datadir", "data/"); // generate directories for data output DSC::testCreateDirectory(datadir); DSC_LOG_INFO << boost::format("Data will be saved under: %s\nLogs will be saved under: %s/%s/ms.log.log\n") % datadir % datadir % DSC_CONFIG_GET("logging.dir", "log"); // syntax: info_from_par_file / default / validation of the value // coarse_grid_level denotes the (starting) grid refinement level for the global coarse scale problem, i.e. it describes 'H' int coarse_grid_level_ = DSC_CONFIG_GETV( "msfem.coarse_grid_level", 4, DSC::ValidateLess< int >( -1 ) ); // syntax: info_from_par_file / default int number_of_layers_ = DSC_CONFIG_GET("msfem.oversampling_layers", 4); switch ( DSC_CONFIG_GET( "msfem.oversampling_strategy", 1 ) ) { case 1: break; case 2: break; default: DUNE_THROW(Dune::InvalidStateException, "Oversampling Strategy must be 1 or 2."); } //if (!( (DSC_CONFIG_GET( "msfem.oversampling_strategy", 1 ) == 1) || (DSC_CONFIG_GET( "msfem.oversampling_strategy", 1 ) == 2) )) // data for the model problem; the information manager // (see 'problem_specification.hh' for details) const Problem::ModelProblemData info; // total_refinement_level denotes the (starting) grid refinement level for the global fine scale problem, i.e. it describes 'h' int total_refinement_level_ = DSC_CONFIG_GETV( "msfem.fine_grid_level", 4, DSC::ValidateLess< int >(coarse_grid_level_-1) ); // name of the grid file that describes the macro-grid: const std::string macroGridName = info.getMacroGridFile(); DSC_LOG_INFO << "Error File for Elliptic Model Problem " << Dune::Stuff::Common::getTypename(info) << " with epsilon = " << DSC_CONFIG_GET("problem.epsilon", 1.0f) << "." << std::endl << std::endl; if (DSC_CONFIG_GET("msfem.uniform", true)) { if ( DSC_CONFIG_GET("msfem.petrov_galerkin", true) ) DSC_LOG_INFO << "Use MsFEM in Petrov-Galerkin formulation with an uniform computation, i.e.:" << std::endl; else DSC_LOG_INFO << "Use MsFEM in classical (symmetric) formulation with an uniform computation, i.e.:" << std::endl; DSC_LOG_INFO << "Uniformly refined coarse and fine mesh and" << std::endl; DSC_LOG_INFO << "the same number of layers for each (oversampled) local grid computation." << std::endl << std::endl; DSC_LOG_INFO << "Computations were made for:" << std::endl << std::endl; DSC_LOG_INFO << "Refinement Level for (uniform) Fine Grid = " << total_refinement_level_ << std::endl; DSC_LOG_INFO << "Refinement Level for (uniform) Coarse Grid = " << coarse_grid_level_ << std::endl; DSC_LOG_INFO << "Oversampling Strategy = " << DSC_CONFIG_GET( "msfem.oversampling_strategy", 1 ) << std::endl; DSC_LOG_INFO << "Number of layers for oversampling = " << number_of_layers_ << std::endl; if ( DSC_CONFIG_GET("msfem.fem_comparison",false) ) { DSC_LOG_INFO << std::endl << "Comparison with standard FEM computation on the MsFEM Fine Grid, i.e. on Refinement Level " << total_refinement_level_ << std::endl; } DSC_LOG_INFO << std::endl << std::endl; } else { if ( DSC_CONFIG_GET("msfem.petrov_galerkin", true) ) DSC_LOG_INFO << "Use MsFEM in Petrov-Galerkin formulation with an adaptive computation, i.e.:" << std::endl; else DSC_LOG_INFO << "Use MsFEM in classical (symmetric) formulation with an adaptive computation, i.e.:" << std::endl; DSC_LOG_INFO << "Starting with a uniformly refined coarse and fine mesh and" << std::endl; DSC_LOG_INFO << "the same number of layers for each (oversampled) local grid computation." << std::endl << std::endl; DSC_LOG_INFO << "Error tolerance = " << DSC_CONFIG_GET("msfem.error_tolerance", 1e-6) << std::endl << std::endl; DSC_LOG_INFO << "Computations were made for:" << std::endl << std::endl; DSC_LOG_INFO << "(Starting) Refinement Level for (uniform) Fine Grid = " << total_refinement_level_ << std::endl; DSC_LOG_INFO << "(Starting) Refinement Level for (uniform) Coarse Grid = " << coarse_grid_level_ << std::endl; DSC_LOG_INFO << "Oversampling Strategy = " << DSC_CONFIG_GET( "msfem.oversampling_strategy", 1 ) << std::endl; DSC_LOG_INFO << "(Starting) Number of layers for oversampling = " << number_of_layers_ << std::endl; if ( DSC_CONFIG_GET("msfem.fem_comparison",false) ) { DSC_LOG_INFO << std::endl << "Comparison with a standard FEM computation on the MsFEM Fine Grid." << std::endl; } DSC_LOG_INFO << std::endl << std::endl; } //! ---------------------- local error indicators -------------------------------- // ----- local error indicators (for each coarse grid element T) ------------- const int max_loop_number = 10; // local coarse residual, i.e. H ||f||_{L^2(T)} CommonTraits::RangeVectorVector loc_coarse_residual_(max_loop_number); // local coarse grid jumps (contribute to the total coarse residual) CommonTraits::RangeVectorVector loc_coarse_grid_jumps_(max_loop_number); // local projection error (we project to get a globaly continous approximation) CommonTraits::RangeVectorVector loc_projection_error_(max_loop_number); // local jump in the conservative flux CommonTraits::RangeVectorVector loc_conservative_flux_jumps_(max_loop_number); // local approximation error CommonTraits::RangeVectorVector loc_approximation_error_(max_loop_number); // local sum over the fine grid jumps (for a fixed subgrid that cooresponds with a coarse entity T) CommonTraits::RangeVectorVector loc_fine_grid_jumps_(max_loop_number); CommonTraits::RangeVector total_coarse_residual_(max_loop_number); CommonTraits::RangeVector total_projection_error_(max_loop_number); CommonTraits::RangeVector total_coarse_grid_jumps_(max_loop_number); CommonTraits::RangeVector total_conservative_flux_jumps_(max_loop_number); CommonTraits::RangeVector total_approximation_error_(max_loop_number); CommonTraits::RangeVector total_fine_grid_jumps_(max_loop_number); CommonTraits::RangeVector total_estimated_H1_error_(max_loop_number); //! TODO put these into something like a named tuple/class std::vector<CommonTraits::RangeVectorVector*> locals = {{ &loc_coarse_residual_, &loc_coarse_grid_jumps_, &loc_projection_error_, &loc_conservative_flux_jumps_, &loc_approximation_error_, &loc_fine_grid_jumps_}}; std::vector<CommonTraits::RangeVector*> totals = {{&total_coarse_residual_, &total_projection_error_, &total_coarse_grid_jumps_, &total_conservative_flux_jumps_, &total_approximation_error_, &total_fine_grid_jumps_ }}; unsigned int loop_number = 0; while (algorithm(macroGridName, loop_number++, total_refinement_level_, coarse_grid_level_, number_of_layers_, locals, totals, total_estimated_H1_error_)) {} // the reference problem generaly has a 'refinement_difference_for_referenceproblem' higher resolution than the //normal // macro problem const auto cpu_time = DSC_PROFILER.stopTiming("msfem.all"); DSC_LOG_INFO << "Total runtime of the program: " << cpu_time << "ms" << std::endl; DSC_PROFILER.outputTimings("profiler"); return 0; } catch (Dune::Exception& e) { std::cerr << e.what() << std::endl; } catch (const std::exception& ex) { std::cerr << "Caught std::exception: " << ex.what() << "\n"; } catch (const std::string& ex) { std::cerr << "Caught string-type exception: " << ex << "\n"; } catch (...) { std::cerr << "Exception of non-known type thrown!\n"; } return 1; } // main <commit_msg>Better timing output in parallel runs<commit_after>// dune-multiscale // Copyright Holders: Patrick Henning, Rene Milk // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #include "common.hh" #include <dune/multiscale/msfem/algorithm.hh> #include <dune/multiscale/problems/elliptic/selector.hh> int main(int argc, char** argv) { try { init(argc, argv); using namespace Dune::Multiscale; using namespace Dune::Multiscale::MsFEM; //!TODO include base in config DSC_PROFILER.startTiming("msfem.all"); const std::string datadir = DSC_CONFIG_GET("global.datadir", "data/"); // generate directories for data output DSC::testCreateDirectory(datadir); DSC_LOG_INFO << boost::format("Data will be saved under: %s\nLogs will be saved under: %s/%s/ms.log.log\n") % datadir % datadir % DSC_CONFIG_GET("logging.dir", "log"); // syntax: info_from_par_file / default / validation of the value // coarse_grid_level denotes the (starting) grid refinement level for the global coarse scale problem, i.e. it describes 'H' int coarse_grid_level_ = DSC_CONFIG_GETV( "msfem.coarse_grid_level", 4, DSC::ValidateLess< int >( -1 ) ); // syntax: info_from_par_file / default int number_of_layers_ = DSC_CONFIG_GET("msfem.oversampling_layers", 4); switch ( DSC_CONFIG_GET( "msfem.oversampling_strategy", 1 ) ) { case 1: break; case 2: break; default: DUNE_THROW(Dune::InvalidStateException, "Oversampling Strategy must be 1 or 2."); } //if (!( (DSC_CONFIG_GET( "msfem.oversampling_strategy", 1 ) == 1) || (DSC_CONFIG_GET( "msfem.oversampling_strategy", 1 ) == 2) )) // data for the model problem; the information manager // (see 'problem_specification.hh' for details) const Problem::ModelProblemData info; // total_refinement_level denotes the (starting) grid refinement level for the global fine scale problem, i.e. it describes 'h' int total_refinement_level_ = DSC_CONFIG_GETV( "msfem.fine_grid_level", 4, DSC::ValidateLess< int >(coarse_grid_level_-1) ); // name of the grid file that describes the macro-grid: const std::string macroGridName = info.getMacroGridFile(); DSC_LOG_INFO << "Error File for Elliptic Model Problem " << Dune::Stuff::Common::getTypename(info) << " with epsilon = " << DSC_CONFIG_GET("problem.epsilon", 1.0f) << "." << std::endl << std::endl; if (DSC_CONFIG_GET("msfem.uniform", true)) { if ( DSC_CONFIG_GET("msfem.petrov_galerkin", true) ) DSC_LOG_INFO << "Use MsFEM in Petrov-Galerkin formulation with an uniform computation, i.e.:" << std::endl; else DSC_LOG_INFO << "Use MsFEM in classical (symmetric) formulation with an uniform computation, i.e.:" << std::endl; DSC_LOG_INFO << "Uniformly refined coarse and fine mesh and" << std::endl; DSC_LOG_INFO << "the same number of layers for each (oversampled) local grid computation." << std::endl << std::endl; DSC_LOG_INFO << "Computations were made for:" << std::endl << std::endl; DSC_LOG_INFO << "Refinement Level for (uniform) Fine Grid = " << total_refinement_level_ << std::endl; DSC_LOG_INFO << "Refinement Level for (uniform) Coarse Grid = " << coarse_grid_level_ << std::endl; DSC_LOG_INFO << "Oversampling Strategy = " << DSC_CONFIG_GET( "msfem.oversampling_strategy", 1 ) << std::endl; DSC_LOG_INFO << "Number of layers for oversampling = " << number_of_layers_ << std::endl; if ( DSC_CONFIG_GET("msfem.fem_comparison",false) ) { DSC_LOG_INFO << std::endl << "Comparison with standard FEM computation on the MsFEM Fine Grid, i.e. on Refinement Level " << total_refinement_level_ << std::endl; } DSC_LOG_INFO << std::endl << std::endl; } else { if ( DSC_CONFIG_GET("msfem.petrov_galerkin", true) ) DSC_LOG_INFO << "Use MsFEM in Petrov-Galerkin formulation with an adaptive computation, i.e.:" << std::endl; else DSC_LOG_INFO << "Use MsFEM in classical (symmetric) formulation with an adaptive computation, i.e.:" << std::endl; DSC_LOG_INFO << "Starting with a uniformly refined coarse and fine mesh and" << std::endl; DSC_LOG_INFO << "the same number of layers for each (oversampled) local grid computation." << std::endl << std::endl; DSC_LOG_INFO << "Error tolerance = " << DSC_CONFIG_GET("msfem.error_tolerance", 1e-6) << std::endl << std::endl; DSC_LOG_INFO << "Computations were made for:" << std::endl << std::endl; DSC_LOG_INFO << "(Starting) Refinement Level for (uniform) Fine Grid = " << total_refinement_level_ << std::endl; DSC_LOG_INFO << "(Starting) Refinement Level for (uniform) Coarse Grid = " << coarse_grid_level_ << std::endl; DSC_LOG_INFO << "Oversampling Strategy = " << DSC_CONFIG_GET( "msfem.oversampling_strategy", 1 ) << std::endl; DSC_LOG_INFO << "(Starting) Number of layers for oversampling = " << number_of_layers_ << std::endl; if ( DSC_CONFIG_GET("msfem.fem_comparison",false) ) { DSC_LOG_INFO << std::endl << "Comparison with a standard FEM computation on the MsFEM Fine Grid." << std::endl; } DSC_LOG_INFO << std::endl << std::endl; } //! ---------------------- local error indicators -------------------------------- // ----- local error indicators (for each coarse grid element T) ------------- const int max_loop_number = 10; // local coarse residual, i.e. H ||f||_{L^2(T)} CommonTraits::RangeVectorVector loc_coarse_residual_(max_loop_number); // local coarse grid jumps (contribute to the total coarse residual) CommonTraits::RangeVectorVector loc_coarse_grid_jumps_(max_loop_number); // local projection error (we project to get a globaly continous approximation) CommonTraits::RangeVectorVector loc_projection_error_(max_loop_number); // local jump in the conservative flux CommonTraits::RangeVectorVector loc_conservative_flux_jumps_(max_loop_number); // local approximation error CommonTraits::RangeVectorVector loc_approximation_error_(max_loop_number); // local sum over the fine grid jumps (for a fixed subgrid that cooresponds with a coarse entity T) CommonTraits::RangeVectorVector loc_fine_grid_jumps_(max_loop_number); CommonTraits::RangeVector total_coarse_residual_(max_loop_number); CommonTraits::RangeVector total_projection_error_(max_loop_number); CommonTraits::RangeVector total_coarse_grid_jumps_(max_loop_number); CommonTraits::RangeVector total_conservative_flux_jumps_(max_loop_number); CommonTraits::RangeVector total_approximation_error_(max_loop_number); CommonTraits::RangeVector total_fine_grid_jumps_(max_loop_number); CommonTraits::RangeVector total_estimated_H1_error_(max_loop_number); //! TODO put these into something like a named tuple/class std::vector<CommonTraits::RangeVectorVector*> locals = {{ &loc_coarse_residual_, &loc_coarse_grid_jumps_, &loc_projection_error_, &loc_conservative_flux_jumps_, &loc_approximation_error_, &loc_fine_grid_jumps_}}; std::vector<CommonTraits::RangeVector*> totals = {{&total_coarse_residual_, &total_projection_error_, &total_coarse_grid_jumps_, &total_conservative_flux_jumps_, &total_approximation_error_, &total_fine_grid_jumps_ }}; unsigned int loop_number = 0; while (algorithm(macroGridName, loop_number++, total_refinement_level_, coarse_grid_level_, number_of_layers_, locals, totals, total_estimated_H1_error_)) {} // the reference problem generaly has a 'refinement_difference_for_referenceproblem' higher resolution than the //normal // macro problem auto cpu_time = DSC_PROFILER.stopTiming("msfem.all"); auto max_cpu_time = Dune::MPIManager::comm().max(cpu_time); if (Dune::MPIManager::rank()==0) { DSC_LOG_INFO << "Maximum total runtime of the program over all processes: " << max_cpu_time << "ms" << std::endl; DSC_PROFILER.outputTimings("profiler"); } return 0; } catch (Dune::Exception& e) { std::cerr << e.what() << std::endl; } catch (const std::exception& ex) { std::cerr << "Caught std::exception: " << ex.what() << "\n"; } catch (const std::string& ex) { std::cerr << "Caught string-type exception: " << ex << "\n"; } catch (...) { std::cerr << "Exception of non-known type thrown!\n"; } return 1; } // main <|endoftext|>
<commit_before>#include "catch.hpp" // mapnik vector tile tile class #include "vector_tile_tile.hpp" TEST_CASE("Vector tile base class") { mapnik::box2d<double> global_extent(-20037508.342789,-20037508.342789,20037508.342789,20037508.342789); SECTION("default constructed") { mapnik::vector_tile_impl::tile default_tile(global_extent); CHECK(default_tile.size() == 0); CHECK(default_tile.data()[0] == '\0'); CHECK(std::abs(default_tile.scale() - 9783.9396205024) < 0.00001); std::string str; default_tile.serialize_to_string(str); CHECK(str == ""); CHECK(default_tile.is_painted() == false); CHECK(default_tile.is_empty() == true); CHECK(default_tile.extent() == global_extent); CHECK(default_tile.get_buffered_extent() == global_extent); CHECK(default_tile.tile_size() == 4096); CHECK(default_tile.get_painted_layers().empty() == true); CHECK(default_tile.get_empty_layers().empty() == true); CHECK(default_tile.get_layers().empty() == true); CHECK(default_tile.get_layers_set().empty() == true); CHECK(default_tile.has_layer("anything") == false); vector_tile::Tile t; t = default_tile.get_tile(); CHECK(t.layers_size() == 0); } SECTION("construction with zero tile_size") { mapnik::vector_tile_impl::tile zero_size_tile(global_extent, 0); CHECK(zero_size_tile.tile_size() == 0); CHECK(std::abs(zero_size_tile.scale() - 40075016.6855780035) < 0.00001); CHECK(zero_size_tile.get_buffered_extent() == global_extent); } SECTION("construction with negative tile_size") { mapnik::vector_tile_impl::tile negative_size_tile(global_extent, -1); CHECK(negative_size_tile.tile_size() == 4294967295); CHECK(std::abs(negative_size_tile.scale() - 0.0093306919) < 0.0000001); CHECK(negative_size_tile.get_buffered_extent() == global_extent); } SECTION("construction with positive buffer size") { mapnik::vector_tile_impl::tile positive_buffer_tile(global_extent, 4096, 10); mapnik::box2d<double> buffered_extent(-20135347.7389940246939659,-20135347.7389940246939659,20135347.7389940246939659,20135347.7389940246939659); CHECK(positive_buffer_tile.get_buffered_extent() == buffered_extent); CHECK(positive_buffer_tile.buffer_size() == 10); } SECTION("construction with very negative buffer size") { mapnik::vector_tile_impl::tile negative_buffer_tile(global_extent, 4096, -4000); mapnik::box2d<double> buffered_extent(0.0, 0.0, 0.0, 0.0); CHECK(negative_buffer_tile.get_buffered_extent() == buffered_extent); CHECK(negative_buffer_tile.buffer_size() == -4000); } SECTION("add bogus layer buffer") { mapnik::vector_tile_impl::tile tile(global_extent); std::string bogus_layer_buffer = "blahblah"; tile.append_layer_buffer(bogus_layer_buffer.data(), bogus_layer_buffer.length(), "bogus"); const std::set<std::string> expected_set{"bogus"}; const std::set<std::string> empty_set; const std::vector<std::string> expected_vec{"bogus"}; CHECK(tile.get_painted_layers() == expected_set); CHECK(tile.get_empty_layers() == empty_set); CHECK(tile.get_layers() == expected_vec); CHECK(tile.get_layers_set() == expected_set); CHECK(tile.has_layer("bogus") == true); CHECK(tile.is_painted() == true); CHECK(tile.is_empty() == false); CHECK(tile.size() == 10); std::string str; tile.serialize_to_string(str); CHECK(str == "\32\10blahblah"); std::string buffer(tile.data()); // Check the buffer itself protozero::pbf_reader read_back(buffer); if (read_back.next(3)) { std::string blah_blah = read_back.get_string(); CHECK(blah_blah == "blahblah"); } // Check the provided reader protozero::pbf_reader tile_reader = tile.get_reader(); if (tile_reader.next(3)) { std::string blah_blah = tile_reader.get_string(); CHECK(blah_blah == "blahblah"); } protozero::pbf_reader layer_reader; CHECK_THROWS_AS(tile.layer_reader("bogus", layer_reader), protozero::end_of_buffer_exception); protozero::pbf_reader layer_reader_by_index; bool status = tile.layer_reader(0, layer_reader_by_index); CHECK(status == true); CHECK_THROWS_AS(layer_reader_by_index.next(1), protozero::end_of_buffer_exception); vector_tile::Tile bogus_tile = tile.get_tile(); CHECK(bogus_tile.layers_size() == 1); vector_tile::Tile_Layer bogus_layer = bogus_tile.layers(0); CHECK(bogus_layer.version() == 1); CHECK(bogus_layer.name() == ""); CHECK(bogus_layer.features_size() == 0); CHECK(bogus_layer.keys_size() == 0); CHECK(bogus_layer.values_size() == 0); CHECK(bogus_layer.extent() == 4096); } SECTION("Add valid layer") { mapnik::vector_tile_impl::tile tile(global_extent); // Create layer vector_tile::Tile_Layer layer; layer.set_version(2); layer.set_name("valid"); std::string layer_buffer; layer.SerializePartialToString(&layer_buffer); tile.append_layer_buffer(layer_buffer.data(), layer_buffer.length(), "valid"); const std::set<std::string> expected_set{"valid"}; const std::set<std::string> empty_set; const std::vector<std::string> expected_vec{"valid"}; CHECK(tile.get_painted_layers() == expected_set); CHECK(tile.get_empty_layers() == empty_set); CHECK(tile.get_layers() == expected_vec); CHECK(tile.get_layers_set() == expected_set); CHECK(tile.has_layer("valid") == true); CHECK(tile.is_painted() == true); CHECK(tile.is_empty() == false); protozero::pbf_reader layer_reader_by_name; bool status_by_name = tile.layer_reader("valid", layer_reader_by_name); CHECK(status_by_name == true); if(layer_reader_by_name.next(1)) { CHECK(layer_reader_by_name.get_string() == "valid"); } protozero::pbf_reader layer_reader_by_index; bool status_by_index = tile.layer_reader(0, layer_reader_by_index); CHECK(status_by_index == true); if(layer_reader_by_index.next(1)) { CHECK(layer_reader_by_index.get_string() == "valid"); } vector_tile::Tile parsed_tile = tile.get_tile(); CHECK(parsed_tile.layers_size() == 1); vector_tile::Tile_Layer parsed_layer = parsed_tile.layers(0); CHECK(parsed_layer.version() == 2); CHECK(parsed_layer.name() == "valid"); } SECTION("layer_reader by name works by name in buffer") { mapnik::vector_tile_impl::tile tile(global_extent); // Create layer vector_tile::Tile_Layer layer; layer.set_version(2); layer.set_name("buffer name"); std::string layer_buffer; layer.SerializePartialToString(&layer_buffer); tile.append_layer_buffer(layer_buffer.data(), layer_buffer.length(), "layer name"); const std::set<std::string> expected_set{"layer name"}; const std::set<std::string> empty_set; const std::vector<std::string> expected_vec{"layer name"}; CHECK(tile.get_painted_layers() == expected_set); CHECK(tile.get_layers() == expected_vec); CHECK(tile.get_layers_set() == expected_set); CHECK(tile.has_layer("layer name") == true); CHECK(tile.has_layer("buffer name") == false); protozero::pbf_reader layer_reader_by_buffer_name; bool status_by_buffer_name = tile.layer_reader("buffer name", layer_reader_by_buffer_name); CHECK(status_by_buffer_name == true); if(layer_reader_by_buffer_name.next(1)) { CHECK(layer_reader_by_buffer_name.get_string() == "buffer name"); } protozero::pbf_reader layer_reader_by_name; bool status_by_layer_name = tile.layer_reader("layer name", layer_reader_by_name); CHECK(status_by_layer_name == false); } } <commit_msg>Add deterministic layer ordering test<commit_after>#include "catch.hpp" // mapnik vector tile tile class #include "vector_tile_tile.hpp" TEST_CASE("Vector tile base class") { mapnik::box2d<double> global_extent(-20037508.342789,-20037508.342789,20037508.342789,20037508.342789); SECTION("default constructed") { mapnik::vector_tile_impl::tile default_tile(global_extent); CHECK(default_tile.size() == 0); CHECK(default_tile.data()[0] == '\0'); CHECK(std::abs(default_tile.scale() - 9783.9396205024) < 0.00001); std::string str; default_tile.serialize_to_string(str); CHECK(str == ""); CHECK(default_tile.is_painted() == false); CHECK(default_tile.is_empty() == true); CHECK(default_tile.extent() == global_extent); CHECK(default_tile.get_buffered_extent() == global_extent); CHECK(default_tile.tile_size() == 4096); CHECK(default_tile.get_painted_layers().empty() == true); CHECK(default_tile.get_empty_layers().empty() == true); CHECK(default_tile.get_layers().empty() == true); CHECK(default_tile.get_layers_set().empty() == true); CHECK(default_tile.has_layer("anything") == false); vector_tile::Tile t; t = default_tile.get_tile(); CHECK(t.layers_size() == 0); } SECTION("construction with zero tile_size") { mapnik::vector_tile_impl::tile zero_size_tile(global_extent, 0); CHECK(zero_size_tile.tile_size() == 0); CHECK(std::abs(zero_size_tile.scale() - 40075016.6855780035) < 0.00001); CHECK(zero_size_tile.get_buffered_extent() == global_extent); } SECTION("construction with negative tile_size") { mapnik::vector_tile_impl::tile negative_size_tile(global_extent, -1); CHECK(negative_size_tile.tile_size() == 4294967295); CHECK(std::abs(negative_size_tile.scale() - 0.0093306919) < 0.0000001); CHECK(negative_size_tile.get_buffered_extent() == global_extent); } SECTION("construction with positive buffer size") { mapnik::vector_tile_impl::tile positive_buffer_tile(global_extent, 4096, 10); mapnik::box2d<double> buffered_extent(-20135347.7389940246939659,-20135347.7389940246939659,20135347.7389940246939659,20135347.7389940246939659); CHECK(positive_buffer_tile.get_buffered_extent() == buffered_extent); CHECK(positive_buffer_tile.buffer_size() == 10); } SECTION("construction with very negative buffer size") { mapnik::vector_tile_impl::tile negative_buffer_tile(global_extent, 4096, -4000); mapnik::box2d<double> buffered_extent(0.0, 0.0, 0.0, 0.0); CHECK(negative_buffer_tile.get_buffered_extent() == buffered_extent); CHECK(negative_buffer_tile.buffer_size() == -4000); } SECTION("add bogus layer buffer") { mapnik::vector_tile_impl::tile tile(global_extent); std::string bogus_layer_buffer = "blahblah"; tile.append_layer_buffer(bogus_layer_buffer.data(), bogus_layer_buffer.length(), "bogus"); const std::set<std::string> expected_set{"bogus"}; const std::set<std::string> empty_set; const std::vector<std::string> expected_vec{"bogus"}; CHECK(tile.get_painted_layers() == expected_set); CHECK(tile.get_empty_layers() == empty_set); CHECK(tile.get_layers() == expected_vec); CHECK(tile.get_layers_set() == expected_set); CHECK(tile.has_layer("bogus") == true); CHECK(tile.is_painted() == true); CHECK(tile.is_empty() == false); CHECK(tile.size() == 10); std::string str; tile.serialize_to_string(str); CHECK(str == "\32\10blahblah"); std::string buffer(tile.data()); // Check the buffer itself protozero::pbf_reader read_back(buffer); if (read_back.next(3)) { std::string blah_blah = read_back.get_string(); CHECK(blah_blah == "blahblah"); } // Check the provided reader protozero::pbf_reader tile_reader = tile.get_reader(); if (tile_reader.next(3)) { std::string blah_blah = tile_reader.get_string(); CHECK(blah_blah == "blahblah"); } protozero::pbf_reader layer_reader; CHECK_THROWS_AS(tile.layer_reader("bogus", layer_reader), protozero::end_of_buffer_exception); protozero::pbf_reader layer_reader_by_index; bool status = tile.layer_reader(0, layer_reader_by_index); CHECK(status == true); CHECK_THROWS_AS(layer_reader_by_index.next(1), protozero::end_of_buffer_exception); vector_tile::Tile bogus_tile = tile.get_tile(); CHECK(bogus_tile.layers_size() == 1); vector_tile::Tile_Layer bogus_layer = bogus_tile.layers(0); CHECK(bogus_layer.version() == 1); CHECK(bogus_layer.name() == ""); CHECK(bogus_layer.features_size() == 0); CHECK(bogus_layer.keys_size() == 0); CHECK(bogus_layer.values_size() == 0); CHECK(bogus_layer.extent() == 4096); } SECTION("Add valid layer") { mapnik::vector_tile_impl::tile tile(global_extent); // Create layer vector_tile::Tile_Layer layer; layer.set_version(2); layer.set_name("valid"); std::string layer_buffer; layer.SerializePartialToString(&layer_buffer); tile.append_layer_buffer(layer_buffer.data(), layer_buffer.length(), "valid"); const std::set<std::string> expected_set{"valid"}; const std::set<std::string> empty_set; const std::vector<std::string> expected_vec{"valid"}; CHECK(tile.get_painted_layers() == expected_set); CHECK(tile.get_empty_layers() == empty_set); CHECK(tile.get_layers() == expected_vec); CHECK(tile.get_layers_set() == expected_set); CHECK(tile.has_layer("valid") == true); CHECK(tile.is_painted() == true); CHECK(tile.is_empty() == false); protozero::pbf_reader layer_reader_by_name; bool status_by_name = tile.layer_reader("valid", layer_reader_by_name); CHECK(status_by_name == true); if(layer_reader_by_name.next(1)) { CHECK(layer_reader_by_name.get_string() == "valid"); } protozero::pbf_reader layer_reader_by_index; bool status_by_index = tile.layer_reader(0, layer_reader_by_index); CHECK(status_by_index == true); if(layer_reader_by_index.next(1)) { CHECK(layer_reader_by_index.get_string() == "valid"); } vector_tile::Tile parsed_tile = tile.get_tile(); CHECK(parsed_tile.layers_size() == 1); vector_tile::Tile_Layer parsed_layer = parsed_tile.layers(0); CHECK(parsed_layer.version() == 2); CHECK(parsed_layer.name() == "valid"); } SECTION("layer_reader by name works by name in buffer") { // Note - if the names of the layer are different // between the layer in the buffer and in the // tile object, `has_layer` will use the one // in the tile object, but `layer_reader` will // use the name in the buffer mapnik::vector_tile_impl::tile tile(global_extent); // Create layer vector_tile::Tile_Layer layer; layer.set_version(2); layer.set_name("buffer name"); // Add layer to tile std::string layer_buffer; layer.SerializePartialToString(&layer_buffer); tile.append_layer_buffer(layer_buffer.data(), layer_buffer.length(), "layer name"); const std::set<std::string> expected_set{"layer name"}; const std::vector<std::string> expected_vec{"layer name"}; // Confirm the use of "layer name" in these methods CHECK(tile.get_painted_layers() == expected_set); CHECK(tile.get_layers() == expected_vec); CHECK(tile.get_layers_set() == expected_set); CHECK(tile.has_layer("layer name") == true); CHECK(tile.has_layer("buffer name") == false); // Confirm the use of "buffer name" in this method protozero::pbf_reader layer_reader_by_buffer_name; bool status_by_buffer_name = tile.layer_reader("buffer name", layer_reader_by_buffer_name); CHECK(status_by_buffer_name == true); if(layer_reader_by_buffer_name.next(1)) { CHECK(layer_reader_by_buffer_name.get_string() == "buffer name"); } protozero::pbf_reader layer_reader_by_name; bool status_by_layer_name = tile.layer_reader("layer name", layer_reader_by_name); CHECK(status_by_layer_name == false); } SECTION("layer ordering is deterministic") { // Newly added layers from buffers are added to the end of // the tile, and are read from the tile in the same order // as they are added mapnik::vector_tile_impl::tile tile(global_extent); // Create layers vector_tile::Tile_Layer layer1, layer2; layer1.set_version(2); layer1.set_name("layer1"); layer2.set_version(2); layer2.set_name("layer2"); std::string layer1_buffer, layer2_buffer; layer1.SerializePartialToString(&layer1_buffer); tile.append_layer_buffer(layer1_buffer.data(), layer1_buffer.length(), "layer1"); layer2.SerializePartialToString(&layer2_buffer); tile.append_layer_buffer(layer2_buffer.data(), layer2_buffer.length(), "layer2"); const std::vector<std::string> expected_vec{"layer1", "layer2"}; // Both of the layers are here, in order CHECK(tile.get_layers() == expected_vec); CHECK(tile.has_layer("layer1") == true); CHECK(tile.has_layer("layer2") == true); // layer_reader reads them in the same order protozero::pbf_reader layer_reader1, layer_reader2; bool status1 = tile.layer_reader(0, layer_reader1); CHECK(status1 == true); if(layer_reader1.next(1)) { CHECK(layer_reader1.get_string() == "layer1"); } bool status2 = tile.layer_reader(0, layer_reader2); CHECK(status2 == true); if(layer_reader2.next(1)) { CHECK(layer_reader2.get_string() == "layer1"); } } } <|endoftext|>
<commit_before>/****************************************************************************** * * Project: integrating laszip into liblas - http://liblas.org - * Purpose: * Author: Martin Isenburg * isenburg at cs.unc.edu * ****************************************************************************** * Copyright (c) 2010, Martin Isenburg * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Licence as published * by the Free Software Foundation. * * See the COPYING file for more information. * ****************************************************************************/ /* =============================================================================== FILE: bytestreamin_istream.hpp CONTENTS: PROGRAMMERS: martin [email protected] COPYRIGHT: copyright (C) 2010 martin [email protected] This software 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. CHANGE HISTORY: 12 December 2010 -- created from ByteStreamOutFile after Howard got pushy (-; =============================================================================== */ #ifndef BYTE_STREAM_IN_ISTREAM_H #define BYTE_STREAM_IN_ISTREAM_H #include "bytestreamin.hpp" #if _MSC_VER < 1300 #include <istream.h> #else #include <fstream> #endif using namespace std; class ByteStreamInIstream : public ByteStreamIn { public: ByteStreamInIstream(istream* stream); /* read a single byte */ unsigned int getByte(); /* read an array of bytes */ bool getBytes(unsigned char* bytes, unsigned int num_bytes); /* returns how many bytes were read since last reset */ unsigned int byteCount() const; /* reset byte counter */ void resetCount(); /* destructor */ ~ByteStreamInIstream(){}; private: istream* stream; ios::off_type start; }; inline ByteStreamInIstream::ByteStreamInIstream(istream* stream) { this->stream = stream; resetCount(); } inline unsigned int ByteStreamInIstream::getByte() { int byte = stream->get(); if (stream->bad()) { byte = 0; } return (unsigned int)byte; } inline bool ByteStreamInIstream::getBytes(unsigned char* bytes, unsigned int num_bytes) { // http://stackoverflow.com/questions/604431/c-reading-unsigned-char-from-file-stream // std::ifstream only provides a specialization for char, not unsigned char. // WARNING, unsafe cast!!! -- hobu stream->read( (char*)bytes, num_bytes); return !!(stream->good()); } unsigned int ByteStreamInIstream::byteCount() const { ios::pos_type end = stream->tellg(); ios::off_type size = end - start; return static_cast<unsigned int>(size); } void ByteStreamInIstream::resetCount() { start = stream->tellg(); } #endif <commit_msg>eof instead of bad<commit_after>/****************************************************************************** * * Project: integrating laszip into liblas - http://liblas.org - * Purpose: * Author: Martin Isenburg * isenburg at cs.unc.edu * ****************************************************************************** * Copyright (c) 2010, Martin Isenburg * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Licence as published * by the Free Software Foundation. * * See the COPYING file for more information. * ****************************************************************************/ /* =============================================================================== FILE: bytestreamin_istream.hpp CONTENTS: PROGRAMMERS: martin [email protected] COPYRIGHT: copyright (C) 2010 martin [email protected] This software 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. CHANGE HISTORY: 12 December 2010 -- created from ByteStreamOutFile after Howard got pushy (-; =============================================================================== */ #ifndef BYTE_STREAM_IN_ISTREAM_H #define BYTE_STREAM_IN_ISTREAM_H #include "bytestreamin.hpp" #if _MSC_VER < 1300 #include <istream.h> #else #include <fstream> #endif using namespace std; class ByteStreamInIstream : public ByteStreamIn { public: ByteStreamInIstream(istream* stream); /* read a single byte */ unsigned int getByte(); /* read an array of bytes */ bool getBytes(unsigned char* bytes, unsigned int num_bytes); /* returns how many bytes were read since last reset */ unsigned int byteCount() const; /* reset byte counter */ void resetCount(); /* destructor */ ~ByteStreamInIstream(){}; private: istream* stream; ios::off_type start; }; inline ByteStreamInIstream::ByteStreamInIstream(istream* stream) { this->stream = stream; resetCount(); } inline unsigned int ByteStreamInIstream::getByte() { int byte = stream->get(); if (stream->eof()) { byte = 0; } return (unsigned int)byte; } inline bool ByteStreamInIstream::getBytes(unsigned char* bytes, unsigned int num_bytes) { // http://stackoverflow.com/questions/604431/c-reading-unsigned-char-from-file-stream // std::ifstream only provides a specialization for char, not unsigned char. // WARNING, unsafe cast!!! -- hobu stream->read( (char*)bytes, num_bytes); return !!(stream->good()); } unsigned int ByteStreamInIstream::byteCount() const { ios::pos_type end = stream->tellg(); ios::off_type size = end - start; return static_cast<unsigned int>(size); } void ByteStreamInIstream::resetCount() { start = stream->tellg(); } #endif <|endoftext|>
<commit_before>#include <stdio.h> #include <climits> #include "engine/engine.hpp" #include "engine/pathfinding/astar.hpp" #include "engine/pathfinding/path.hpp" namespace qrw { Engine::Engine() : board(0), status(EES_UNDEFINED) { players[0].setName("Player The First"); players[0].setId(0); players[1].setName("Player The Second"); players[1].setId(1); pathfinder = new AStar(); } Engine::~Engine() { delete pathfinder; } void Engine::init(int boardwidth, int boardheight) { delete board; board = new Board(boardwidth, boardheight); pathfinder->setBoard(board); currentplayer = 0; getCurrentPlayer().setActive(true); status = EES_PREPARE; int maxarmysize = INT_MAX; // int maxarmysize = getMaxPlayerUnits(); players[0].getArmy().deleteAllUnits(); players[0].getArmy().setMaxSize(maxarmysize); players[1].getArmy().deleteAllUnits(); players[1].getArmy().setMaxSize(maxarmysize); } void Engine::startGame() { currentplayer = 0; status = EES_RUNNING; } ENGINSTATES Engine::getStatus() { return status; } int Engine::getMaxPlayerUnits() { if(board) return (board->getHeight() * board->getWidth()) / 3; return 0; } void Engine::createPlayerUnits(int playerid, std::map<UNITTYPES, int> unitcounts) { Player* player = getPlayer(playerid); UNITTYPES unittype; Unit* unit; for(auto iter = unitcounts.begin(); iter != unitcounts.end(); ++iter) { unittype = iter->first; for(int i = 0; i < iter->second; ++i) { // Create new unit switch(unittype) { case EUT_SWORDMAN: unit = new Unit(EUT_SWORDMAN, 5, 2, 1, 1, 3, player, board); break; case EUT_ARCHER: unit = new Unit(EUT_ARCHER, 5, 2, 1, 3, 2, player, board); break; default: unit = new Unit(EUT_SPEARMAN, 5, 2, 1, 2, 2, player, board); break; } // Add new unit to army player->getArmy().addUnit(unit); } } } // bool Engine::setUnits(int playeroneunits[EUT_NUMBEROFUNITTYPES], // int playertwounits[EUT_NUMBEROFUNITTYPES]) // { // players[0].clearUnits(); // players[1].clearUnits(); // if(status != EES_PREPARE) // return false; // setPlayerUnits(0, playeroneunits); // setPlayerUnits(1, playertwounits); // return true; // } // void Engine::setPlayerUnits(int id, int unitnumbers[EUT_NUMBEROFUNITTYPES]) // { // Player* player = getPlayer(id); // int i; // // Attention! player is "overwritten" in the method Player::addUnit(...). // for(i = 0; i < unitnumbers[EUT_SWORDMAN]; ++i) // player->addUnit(new Unit(EUT_SWORDMAN, 2, 1, 1, 3, player)); // for(i = 0; i < unitnumbers[EUT_ARCHER]; ++i) // player->addUnit(new Unit(EUT_ARCHER, 2, 1, 3, 2, player)); // for(i = 0; i < unitnumbers[EUT_SPEARMAN]; ++i) // player->addUnit(new Unit(EUT_SPEARMAN, 2, 1, 2, 2, player)); // } Board* Engine::getBoard() { return board; } Player& Engine::getCurrentPlayer() { return players[currentplayer]; } void Engine::endTurn() { // Reset movement of current players units. Army& army = getCurrentPlayer().getArmy(); for(int i = 0; i < EUT_NUMBEROFUNITTYPES; ++i) { std::set<Unit*>& unitset = army.getUnitsByType((UNITTYPES)i); for(auto iter = unitset.begin(); iter != unitset.end(); ++iter) (*iter)->setCurrentMovement((*iter)->getMovement()); } // change player and update active flags. getCurrentPlayer().setActive(false); currentplayer = (currentplayer + 1) % 2; getCurrentPlayer().setActive(true); } /** * @Return: 0 - success, -1 - wrong player, -2 origin empty, * -3 on destination is unit of same player, -4 origin out of range, * -5 dest out of ranage, -6 not enough movement, * -7 game not running, -8 unit on origin died, -9 enemy unit * was not defeated, -10 enemy out of range, -11 defender died */ int Engine::moveUnitIngame(Coordinates origin, Coordinates destination) { // Game is not running if(status != EES_RUNNING) return -7; Square* orsquare = board->getSquare(origin); // index out of range if(orsquare == 0) return -4; // no unit on this square if(orsquare->getUnit() == 0) return -2; Square* destsquare = board->getSquare(destination); // index out of range if(destsquare == 0) return -5; Unit* srcunit = orsquare->getUnit(); // Unit does not belong to current player if(srcunit->getPlayer() != &getCurrentPlayer()) return -1; int distance = orsquare->getDistance(destsquare); if(distance > 1) { Path* path = pathfinder->findPath(orsquare->getCoordinates(), destsquare->getCoordinates()); if(path == 0) { delete path; return -5; } distance = path->getMovementCosts(); delete path; } // Distance is too far if(distance > srcunit->getCurrentMovement()) return -6; // Is there a unit on the destination? Unit* destunit = destsquare->getUnit(); if(destunit != 0) { // unit on destination belongs to same player if(destunit->getPlayer() == srcunit->getPlayer()) return -3; // otherwise: battle // Check for range printf("distance: %d", distance); if(distance > srcunit->getRange()) return -10; // get modificators int attackmods[] = {0, 0}; int defensemods[] = {0, 0}; if(orsquare->getTerrain() != NULL) { attackmods[0] = orsquare->getTerrain()->getModificators()[0]; attackmods[1] = orsquare->getTerrain()->getModificators()[1]; } if(destsquare->getTerrain() != NULL) { defensemods[0] = destsquare->getTerrain()->getModificators()[0]; defensemods[1] = destsquare->getTerrain()->getModificators()[1]; } srcunit->attack(destunit, attackmods, defensemods); srcunit->setCurrentMovement(0); // Attacker died if(srcunit->getHP() == 0) { orsquare->setUnit(0); return -8; } // No one died else if(destunit->getHP() > 0) { return -9; } // Defender died else { orsquare->setUnit(0); destsquare->setUnit(srcunit); return -11; } } srcunit->setCurrentMovement(srcunit->getCurrentMovement() - distance); orsquare->setUnit(0); destsquare->setUnit(srcunit); return 0; } int Engine::moveUnitDeployment(Coordinates origin, Coordinates destination) { Square* orsquare = board->getSquare(origin); if(orsquare->getUnit() == NULL) return -1; Square* destsquare = board->getSquare(destination); if(destsquare->getUnit() != NULL) return -1; destsquare->setUnit(orsquare->getUnit()); orsquare->setUnit(NULL); return 0; } bool Engine::placeUnit(Coordinates position, int playerid, UNITTYPES unittype) { if(status != EES_PREPARE) return false; Square* square = board->getSquare(position); if(square == 0) return false; if(square->getUnit() != 0) return false; Player* player = getPlayer(playerid); Unit* unit = *(player->getArmy().getUndeployedUnitsByType(unittype).begin()); if(unit) { player->getArmy().markUnitAsDeployed(unit); square->setUnit(unit); return true; } return false; } bool Engine::placeTerrain(Coordinates position, TERRAINTYPES terraintype) { if(status != EES_PREPARE) return false; Square* square = board->getSquare(position); if(square == NULL) return false; if(square->getTerrain() != NULL) delete square->getTerrain(); Terrain* terrain; switch(terraintype) { case ET_WOOD: terrain = new Terrain(ET_WOOD, -1, 1); break; case ET_HILL: terrain = new Terrain(ET_HILL, 1, -1); break; default: terrain = new Terrain(ET_WALL, 1, 1); break; } square->setTerrain(terrain); return true; } bool Engine::removeTerrain(Coordinates position) { if(status != EES_PREPARE) return false; Square* square = board->getSquare(position); if(square == NULL) return false; if(square->getTerrain()) delete square->getTerrain(); square->setTerrain(NULL); } Player* Engine::getPlayer(int id) { if(id == 0 || id == 1) return &players[id]; return 0; } Path* Engine::findPath(const Coordinates& start, const Coordinates& end) { return pathfinder->findPath(start, end); } } <commit_msg>Engine now sets Square to Units.<commit_after>#include <stdio.h> #include <climits> #include "engine/engine.hpp" #include "engine/pathfinding/astar.hpp" #include "engine/pathfinding/path.hpp" namespace qrw { Engine::Engine() : board(0), status(EES_UNDEFINED) { players[0].setName("Player The First"); players[0].setId(0); players[1].setName("Player The Second"); players[1].setId(1); pathfinder = new AStar(); } Engine::~Engine() { delete pathfinder; } void Engine::init(int boardwidth, int boardheight) { delete board; board = new Board(boardwidth, boardheight); pathfinder->setBoard(board); currentplayer = 0; getCurrentPlayer().setActive(true); status = EES_PREPARE; int maxarmysize = INT_MAX; // int maxarmysize = getMaxPlayerUnits(); players[0].getArmy().deleteAllUnits(); players[0].getArmy().setMaxSize(maxarmysize); players[1].getArmy().deleteAllUnits(); players[1].getArmy().setMaxSize(maxarmysize); } void Engine::startGame() { currentplayer = 0; status = EES_RUNNING; } ENGINSTATES Engine::getStatus() { return status; } int Engine::getMaxPlayerUnits() { if(board) return (board->getHeight() * board->getWidth()) / 3; return 0; } void Engine::createPlayerUnits(int playerid, std::map<UNITTYPES, int> unitcounts) { Player* player = getPlayer(playerid); UNITTYPES unittype; Unit* unit; for(auto iter = unitcounts.begin(); iter != unitcounts.end(); ++iter) { unittype = iter->first; for(int i = 0; i < iter->second; ++i) { // Create new unit switch(unittype) { case EUT_SWORDMAN: unit = new Unit(EUT_SWORDMAN, 5, 2, 1, 1, 3, player, board); break; case EUT_ARCHER: unit = new Unit(EUT_ARCHER, 5, 2, 1, 3, 2, player, board); break; default: unit = new Unit(EUT_SPEARMAN, 5, 2, 1, 2, 2, player, board); break; } // Add new unit to army player->getArmy().addUnit(unit); } } } // bool Engine::setUnits(int playeroneunits[EUT_NUMBEROFUNITTYPES], // int playertwounits[EUT_NUMBEROFUNITTYPES]) // { // players[0].clearUnits(); // players[1].clearUnits(); // if(status != EES_PREPARE) // return false; // setPlayerUnits(0, playeroneunits); // setPlayerUnits(1, playertwounits); // return true; // } // void Engine::setPlayerUnits(int id, int unitnumbers[EUT_NUMBEROFUNITTYPES]) // { // Player* player = getPlayer(id); // int i; // // Attention! player is "overwritten" in the method Player::addUnit(...). // for(i = 0; i < unitnumbers[EUT_SWORDMAN]; ++i) // player->addUnit(new Unit(EUT_SWORDMAN, 2, 1, 1, 3, player)); // for(i = 0; i < unitnumbers[EUT_ARCHER]; ++i) // player->addUnit(new Unit(EUT_ARCHER, 2, 1, 3, 2, player)); // for(i = 0; i < unitnumbers[EUT_SPEARMAN]; ++i) // player->addUnit(new Unit(EUT_SPEARMAN, 2, 1, 2, 2, player)); // } Board* Engine::getBoard() { return board; } Player& Engine::getCurrentPlayer() { return players[currentplayer]; } void Engine::endTurn() { // Reset movement of current players units. Army& army = getCurrentPlayer().getArmy(); for(int i = 0; i < EUT_NUMBEROFUNITTYPES; ++i) { std::set<Unit*>& unitset = army.getUnitsByType((UNITTYPES)i); for(auto iter = unitset.begin(); iter != unitset.end(); ++iter) (*iter)->setCurrentMovement((*iter)->getMovement()); } // change player and update active flags. getCurrentPlayer().setActive(false); currentplayer = (currentplayer + 1) % 2; getCurrentPlayer().setActive(true); } /** * @Return: 0 - success, -1 - wrong player, -2 origin empty, * -3 on destination is unit of same player, -4 origin out of range, * -5 dest out of ranage, -6 not enough movement, * -7 game not running, -8 unit on origin died, -9 enemy unit * was not defeated, -10 enemy out of range, -11 defender died */ int Engine::moveUnitIngame(Coordinates origin, Coordinates destination) { // Game is not running if(status != EES_RUNNING) return -7; Square* orsquare = board->getSquare(origin); // index out of range if(orsquare == 0) return -4; // no unit on this square if(orsquare->getUnit() == 0) return -2; Square* destsquare = board->getSquare(destination); // index out of range if(destsquare == 0) return -5; Unit* srcunit = orsquare->getUnit(); // Unit does not belong to current player if(srcunit->getPlayer() != &getCurrentPlayer()) return -1; int distance = orsquare->getDistance(destsquare); if(distance > 1) { Path* path = pathfinder->findPath(orsquare->getCoordinates(), destsquare->getCoordinates()); if(path == 0) { delete path; return -5; } distance = path->getMovementCosts(); delete path; } // Distance is too far if(distance > srcunit->getCurrentMovement()) return -6; // Is there a unit on the destination? Unit* destunit = destsquare->getUnit(); if(destunit != 0) { // unit on destination belongs to same player if(destunit->getPlayer() == srcunit->getPlayer()) return -3; // otherwise: battle // Check for range printf("distance: %d", distance); if(distance > srcunit->getRange()) return -10; // get modificators int attackmods[] = {0, 0}; int defensemods[] = {0, 0}; if(orsquare->getTerrain() != NULL) { attackmods[0] = orsquare->getTerrain()->getModificators()[0]; attackmods[1] = orsquare->getTerrain()->getModificators()[1]; } if(destsquare->getTerrain() != NULL) { defensemods[0] = destsquare->getTerrain()->getModificators()[0]; defensemods[1] = destsquare->getTerrain()->getModificators()[1]; } srcunit->attack(destunit, attackmods, defensemods); srcunit->setCurrentMovement(0); // Attacker died if(srcunit->getHP() == 0) { orsquare->setUnit(0); return -8; } // No one died else if(destunit->getHP() > 0) { return -9; } // Defender died else { orsquare->setUnit(0); destsquare->setUnit(srcunit); return -11; } } srcunit->setCurrentMovement(srcunit->getCurrentMovement() - distance); orsquare->setUnit(0); destsquare->setUnit(srcunit); return 0; } int Engine::moveUnitDeployment(Coordinates origin, Coordinates destination) { Square* orsquare = board->getSquare(origin); if(orsquare->getUnit() == NULL) return -1; Square* destsquare = board->getSquare(destination); if(destsquare->getUnit() != NULL) return -1; destsquare->setUnit(orsquare->getUnit()); orsquare->setUnit(NULL); return 0; } bool Engine::placeUnit(Coordinates position, int playerid, UNITTYPES unittype) { if(status != EES_PREPARE) return false; Square* square = board->getSquare(position); if(square == 0) return false; if(square->getUnit() != 0) return false; Player* player = getPlayer(playerid); Unit* unit = *(player->getArmy().getUndeployedUnitsByType(unittype).begin()); if(unit) { player->getArmy().markUnitAsDeployed(unit); square->setUnit(unit); unit->setSquare(square); return true; } return false; } bool Engine::placeTerrain(Coordinates position, TERRAINTYPES terraintype) { if(status != EES_PREPARE) return false; Square* square = board->getSquare(position); if(square == NULL) return false; if(square->getTerrain() != NULL) delete square->getTerrain(); Terrain* terrain; switch(terraintype) { case ET_WOOD: terrain = new Terrain(ET_WOOD, -1, 1); break; case ET_HILL: terrain = new Terrain(ET_HILL, 1, -1); break; default: terrain = new Terrain(ET_WALL, 1, 1); break; } square->setTerrain(terrain); return true; } bool Engine::removeTerrain(Coordinates position) { if(status != EES_PREPARE) return false; Square* square = board->getSquare(position); if(square == NULL) return false; if(square->getTerrain()) delete square->getTerrain(); square->setTerrain(NULL); } Player* Engine::getPlayer(int id) { if(id == 0 || id == 1) return &players[id]; return 0; } Path* Engine::findPath(const Coordinates& start, const Coordinates& end) { return pathfinder->findPath(start, end); } } <|endoftext|>
<commit_before><commit_msg>removed wrong assert<commit_after><|endoftext|>
<commit_before>#include "libmesh/vectormap.h" #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #define VECTORMAPOBJECTTEST \ CPPUNIT_TEST( testCreate ); \ using namespace libMesh; class VectormapTest : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE ( VectormapTest ); CPPUNIT_TEST( testCreate ); CPPUNIT_TEST( testInsert ); CPPUNIT_TEST_SUITE_END(); private: template <typename Key, typename Val> void create() { vectormap<Key,Val> vm; } template <typename Key, typename Val> void insert() { vectormap<Key,Val> vm; Val val(0); // requires default constructor for val type. for (Key key=1; key<32; key*=2) vm.insert (std::make_pair(key,val)); } public: // virtual void setUp() // {} // virtual void tearDown() // {} void testCreate() { create<int, int> (); create<int*,int> (); create<int*,int*>(); create<int, std::vector<int> >(); } void testInsert() { insert<int, int> (); insert<char,int> (); insert<long,int*>(); insert<int, std::vector<int> >(); } }; CPPUNIT_TEST_SUITE_REGISTRATION ( VectormapTest ); <commit_msg>test iterating<commit_after>#include "libmesh/vectormap.h" #include <cppunit/extensions/HelperMacros.h> #include <cppunit/TestCase.h> #define VECTORMAPOBJECTTEST \ CPPUNIT_TEST( testCreate ); \ using namespace libMesh; class VectormapTest : public CppUnit::TestCase { public: CPPUNIT_TEST_SUITE ( VectormapTest ); CPPUNIT_TEST( testCreate ); CPPUNIT_TEST( testInsert ); CPPUNIT_TEST( testIterate ); CPPUNIT_TEST_SUITE_END(); private: template <typename Key, typename Val> void create() { vectormap<Key,Val> vm; } template <typename Key, typename Val> void insert() { vectormap<Key,Val> vm; Val val(0); // requires default constructor for val type. for (Key key=1; key<32; key*=2) vm.insert (std::make_pair(key,val)); vm.sort(); } template <typename Key, typename Val> void iterate(const Val &default_value=0) { vectormap<Key,Val> vm; Val val(default_value); // requires default constructor for val type. for (Key key=1; key<32; key*=2) vm.insert (std::make_pair(key,val)); vm.sort(); for (typename vectormap<Key,Val>::const_iterator it=vm.begin(); it != vm.end(); ++it) { const Key &ikey = it->first; const Val &ival = it->second; CPPUNIT_ASSERT ( vm.count(ikey) == 1 ); CPPUNIT_ASSERT_EQUAL (vm[ikey], ival); CPPUNIT_ASSERT_EQUAL (ival, val); } } public: // virtual void setUp() // {} // virtual void tearDown() // {} void testCreate() { create<int, int> (); create<int*,int> (); create<int*,int*>(); create<int, std::vector<int> >(); } void testInsert() { insert<int, int> (); insert<char,int> (); insert<long,int*>(); insert<int, std::vector<int> >(); } void testIterate() { iterate<int, int> (); iterate<char,int> (); iterate<long,int*>(); iterate<int, std::string>("test_string"); } }; CPPUNIT_TEST_SUITE_REGISTRATION ( VectormapTest ); <|endoftext|>
<commit_before>//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2006/11/01 // Author: Blake Lewis (Kosmix Corp.) // // Copyright 2006 Kosmix Corp. // // This file is part of Kosmos File System (KFS). // // 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 "libkfsClient/KfsClient.h" extern "C" { #define FUSE_USE_VERSION 25 #define _FILE_OFFSET_BITS 64 #include <fuse.h> #include <sys/stat.h> #include <string.h> } using std::vector; using namespace KFS; static char *FUSE_KFS_PROPERTIES = "./kfs.prp"; static KFS::KfsClientPtr client; void * fuse_init() { client = getKfsClientFactory()->GetClient(FUSE_KFS_PROPERTIES); return client->IsInitialized() ? client.get() : NULL; } void fuse_destroy(void *cookie) { client.reset(); } static int fuse_getattr(const char *path, struct stat *s) { return client->Stat(path, *s); } static int fuse_mkdir(const char *path, mode_t mode) { return client->Mkdir(path); } static int fuse_unlink(const char *path) { return client->Remove(path); } static int fuse_rmdir(const char *path) { return client->Rmdir(path); } static int fuse_rename(const char *src, const char *dst) { return client->Rename(src, dst, false); } static int fuse_truncate(const char *path, off_t size) { int fd = client->Open(path, O_WRONLY); if (fd < 0) return fd; int status = client->Truncate(fd, size); client->Close(fd); return status; } static int fuse_open(const char *path, struct fuse_file_info *finfo) { int res = client->Open(path, finfo->flags); if (res >= 0) return 0; return res; } static int fuse_create(const char *path, mode_t mode, struct fuse_file_info *finfo) { int res = client->Create(path); if (res >= 0) return 0; return res; } static int fuse_read(const char *path, char *buf, size_t nread, off_t off, struct fuse_file_info *finfo) { int fd = client->Open(path, O_RDONLY); if (fd < 0) return fd; int status = client->Seek(fd, off, SEEK_SET); if (status == 0) status = client->Read(fd, buf, nread); client->Close(fd); return status; } static int fuse_write(const char *path, const char *buf, size_t nwrite, off_t off, struct fuse_file_info *finfo) { int fd = client->Open(path, O_WRONLY); if (fd < 0) return fd; int status = client->Seek(fd, off, SEEK_SET); if (status == 0) status = client->Write(fd, buf, nwrite); client->Close(fd); return status; } static int fuse_flush(const char *path, struct fuse_file_info *finfo) { int fd = client->Fileno(path); if (fd < 0) return fd; return client->Sync(fd); } static int fuse_fsync(const char *path, int flags, struct fuse_file_info *finfo) { int fd = client->Open(path, O_RDONLY); if (fd < 0) return fd; return client->Sync(fd); } static int fuse_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *finfo) { vector <KfsFileAttr> contents; int status = client->ReaddirPlus(path, contents); if (status < 0) return status; int n = contents.size(); for (int i = 0; i != n; i++) { struct stat s; memset(&s, 0, sizeof s); s.st_ino = contents[i].fileId; s.st_mode = contents[i].isDirectory ? S_IFDIR : S_IFREG; if (filler(buf, contents[i].filename.c_str(), &s, 0) != 0) break; } return 0; } struct fuse_operations ops = { fuse_getattr, NULL, /* readlink */ NULL, /* getdir */ NULL, /* mknod */ fuse_mkdir, fuse_unlink, fuse_rmdir, NULL, /* symlink */ fuse_rename, NULL, /* link */ NULL, /* chmod */ NULL, /* chown */ fuse_truncate, NULL, /* utime */ fuse_open, fuse_read, fuse_write, NULL, /* statfs */ fuse_flush, /* flush */ NULL, /* release */ fuse_fsync, /* fsync */ NULL, /* setxattr */ NULL, /* getxattr */ NULL, /* listxattr */ NULL, /* removexattr */ NULL, /* opendir */ fuse_readdir, NULL, /* releasedir */ NULL, /* fsyncdir */ fuse_init, fuse_destroy, NULL, /* access */ fuse_create, /* create */ NULL, /* ftruncate */ NULL /* fgetattr */ }; int main(int argc, char **argv) { return fuse_main(argc, argv, &ops); } <commit_msg> -- Updating fuse based on a patch that was submitted by Tong-Hong Kuo.<commit_after>//---------------------------------------------------------- -*- Mode: C++ -*- // $Id$ // // Created 2006/11/01 // Author: Blake Lewis (Kosmix Corp.) // // Copyright 2006 Kosmix Corp. // // This file is part of Kosmos File System (KFS). // // 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 "libkfsClient/KfsClient.h" extern "C" { #define FUSE_USE_VERSION 25 #define _FILE_OFFSET_BITS 64 #include <fuse.h> #include <sys/stat.h> #include <string.h> } using std::vector; using namespace KFS; static char *FUSE_KFS_PROPERTIES = "./kfs.prp"; static KFS::KfsClientPtr client; void * fuse_init() { client = getKfsClientFactory()->GetClient(FUSE_KFS_PROPERTIES); return client->IsInitialized() ? client.get() : NULL; } void fuse_destroy(void *cookie) { client.reset(); } static int fuse_getattr(const char *path, struct stat *s) { return client->Stat(path, *s); } static int fuse_mkdir(const char *path, mode_t mode) { return client->Mkdir(path); } static int fuse_unlink(const char *path) { return client->Remove(path); } static int fuse_rmdir(const char *path) { return client->Rmdir(path); } static int fuse_rename(const char *src, const char *dst) { return client->Rename(src, dst, false); } static int fuse_truncate(const char *path, off_t size) { int fd = client->Open(path, O_WRONLY); if (fd < 0) return fd; int status = client->Truncate(fd, size); client->Close(fd); return status; } static int fuse_open(const char *path, struct fuse_file_info *finfo) { int res = client->Open(path, finfo->flags); if (res < 0) return res; finfo->fh = res; return 0; } static int fuse_release(const char *path, struct fuse_file_info *finfo) { int res = finfo->fh; client->Close(res); finfo->fh = -1; return 0; } static int fuse_create(const char *path, mode_t mode, struct fuse_file_info *finfo) { int res = client->Open(path, finfo->flags); if (res < 0) return res; finfo->fh = res; return 0; } static int fuse_read(const char *path, char *buf, size_t nread, off_t off, struct fuse_file_info *finfo) { int fd = finfo->fh; if (fd < 0) return fd; client->Seek(fd, off); int status = client->Read(fd, buf, nread); return status; } static int fuse_write(const char *path, const char *buf, size_t nwrite, off_t off, struct fuse_file_info *finfo) { int fd = finfo->fh; if (fd < 0) return fd; client->Seek(fd, off); int status = client->Write(fd, buf, nwrite); return status; } static int fuse_flush(const char *path, struct fuse_file_info *finfo) { int fd = finfo->fh; //int fd = client->Fileno(path); if (fd < 0) return fd; return client->Sync(fd); } static int fuse_fsync(const char *path, int flags, struct fuse_file_info *finfo) { int fd = finfo->fh; //int fd = client->Fileno(path); if (fd < 0) return fd; return client->Sync(fd); } static int fuse_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *finfo) { vector <KfsFileAttr> contents; int status = client->ReaddirPlus(path, contents); if (status < 0) return status; int n = contents.size(); for (int i = 0; i != n; i++) { struct stat s; memset(&s, 0, sizeof s); s.st_ino = contents[i].fileId; s.st_mode = contents[i].isDirectory ? S_IFDIR : S_IFREG; if (filler(buf, contents[i].filename.c_str(), &s, 0) != 0) break; } return 0; } struct fuse_operations ops = { fuse_getattr, NULL, /* readlink */ NULL, /* getdir */ NULL, /* mknod */ fuse_mkdir, fuse_unlink, fuse_rmdir, NULL, /* symlink */ fuse_rename, NULL, /* link */ NULL, /* chmod */ NULL, /* chown */ fuse_truncate, NULL, /* utime */ fuse_open, fuse_read, fuse_write, NULL, /* statfs */ fuse_flush, /* flush */ fuse_release, /* release */ fuse_fsync, /* fsync */ NULL, /* setxattr */ NULL, /* getxattr */ NULL, /* listxattr */ NULL, /* removexattr */ NULL, /* opendir */ fuse_readdir, NULL, /* releasedir */ NULL, /* fsyncdir */ fuse_init, fuse_destroy, NULL, /* access */ fuse_create, /* create */ NULL, /* ftruncate */ NULL /* fgetattr */ }; int main(int argc, char **argv) { return fuse_main(argc, argv, &ops); } <|endoftext|>
<commit_before>/* Copyright (c) 2010, The Barbarian Group 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. 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 "cinder/app/App.h" #include "cinder/params/Params.h" #include "AntTweakBar.h" #include <boost/assign/list_of.hpp> using namespace std; namespace cinder { namespace params { namespace { #define SYNONYM(ck,ak) ((int)cinder::app::KeyEvent::KEY_ ## ck, TW_KEY_ ## ak) #define HOMONYM(k) SYNONYM(k,k) std::map<int,TwKeySpecial> specialKeys = boost::assign::map_list_of HOMONYM(RIGHT) HOMONYM(LEFT) HOMONYM(BACKSPACE) HOMONYM(DELETE) HOMONYM(TAB) HOMONYM(F1) HOMONYM(F2) HOMONYM(F3) HOMONYM(F4) HOMONYM(F5) HOMONYM(F6) HOMONYM(F7) HOMONYM(F8) HOMONYM(F9) HOMONYM(F10) HOMONYM(F11) HOMONYM(F12) HOMONYM(F13) HOMONYM(F14) HOMONYM(F15) HOMONYM(HOME) HOMONYM(END) SYNONYM(PAGEUP,PAGE_UP) SYNONYM(PAGEDOWN,PAGE_DOWN) ; #undef SYNONYM #undef HOMONYM bool mouseDown( app::MouseEvent event ) { TwMouseButtonID button; if( event.isLeft() ) button = TW_MOUSE_LEFT; else if( event.isRight() ) button = TW_MOUSE_RIGHT; else button = TW_MOUSE_MIDDLE; return TwMouseButton( TW_MOUSE_PRESSED, button ) != 0; } bool mouseUp( app::MouseEvent event ) { TwMouseButtonID button; if( event.isLeft() ) button = TW_MOUSE_LEFT; else if( event.isRight() ) button = TW_MOUSE_RIGHT; else button = TW_MOUSE_MIDDLE; return TwMouseButton( TW_MOUSE_RELEASED, button ) != 0; } bool mouseWheel( app::MouseEvent event ) { static float sWheelPos = 0; sWheelPos += event.getWheelIncrement(); return TwMouseWheel( (int)(sWheelPos) ) != 0; } bool mouseMove( app::MouseEvent event ) { return TwMouseMotion( event.getX(), event.getY() ) != 0; } bool keyDown( app::KeyEvent event ) { int kmod = 0; if( event.isShiftDown() ) kmod |= TW_KMOD_SHIFT; if( event.isControlDown() ) kmod |= TW_KMOD_CTRL; if( event.isAltDown() ) kmod |= TW_KMOD_ALT; return TwKeyPressed( (specialKeys.count( event.getCode() ) > 0) ? specialKeys[event.getCode()] : event.getChar(), kmod ) != 0; } bool resize( app::ResizeEvent event ) { TwWindowSize( event.getWidth(), event.getHeight() ); return false; } void TW_CALL implStdStringToClient( std::string& destinationClientString, const std::string& sourceLibraryString ) { // copy strings from the library to the client app destinationClientString = sourceLibraryString; } class AntMgr { public: AntMgr() { if( ! TwInit( TW_OPENGL, NULL ) ) { throw Exception(); } app::App::get()->registerMouseDown( mouseDown ); app::App::get()->registerMouseUp( mouseUp ); app::App::get()->registerMouseWheel( mouseWheel ); app::App::get()->registerMouseMove( mouseMove ); app::App::get()->registerMouseDrag( mouseMove ); app::App::get()->registerKeyDown( keyDown ); app::App::get()->registerResize( resize ); } ~AntMgr() { TwTerminate(); } }; } // anonymous namespace void initAntGl() { static std::shared_ptr<AntMgr> mgr; if( ! mgr ) mgr = std::shared_ptr<AntMgr>( new AntMgr ); } InterfaceGl::InterfaceGl( const std::string &title, const Vec2i &size, const ColorA color ) { initAntGl(); mBar = std::shared_ptr<TwBar>( TwNewBar( title.c_str() ), TwDeleteBar ); char optionsStr[1024]; sprintf( optionsStr, "`%s` size='%d %d' color='%d %d %d' alpha=%d", title.c_str(), size.x, size.y, (int)(color.r * 255), (int)(color.g * 255), (int)(color.b * 255), (int)(color.a * 255) ); TwDefine( optionsStr ); TwCopyStdStringToClientFunc( implStdStringToClient ); } void InterfaceGl::draw() { TwDraw(); } void InterfaceGl::show( bool visible ) { int32_t visibleInt = ( visible ) ? 1 : 0; TwSetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt ); } void InterfaceGl::hide() { int32_t visibleInt = 0; TwSetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt ); } bool InterfaceGl::isVisible() const { int32_t visibleInt; TwGetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt ); return visibleInt != 0; } void InterfaceGl::implAddParam( const std::string &name, void *param, int type, const std::string &optionsStr, bool readOnly ) { if( readOnly ) TwAddVarRO( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() ); else TwAddVarRW( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() ); } void InterfaceGl::addParam( const std::string &name, bool *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_BOOLCPP, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, float *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_FLOAT, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, int32_t *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_INT32, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, Vec3f *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_DIR3F, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, Quatf *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_QUAT4F, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, Color *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_COLOR3F, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, ColorA *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_COLOR4F, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, std::string *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_STDSTRING, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, const std::vector<std::string> &enumNames, int *param, const std::string &optionsStr, bool readOnly ) { TwEnumVal *ev = new TwEnumVal[enumNames.size()]; for( size_t v = 0; v < enumNames.size(); ++v ) { ev[v].Value = v; ev[v].Label = const_cast<char*>( enumNames[v].c_str() ); } TwType evType = TwDefineEnum( (name + "EnumType").c_str(), ev, enumNames.size() ); if( readOnly ) TwAddVarRO( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() ); else TwAddVarRW( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() ); delete [] ev; } void InterfaceGl::addSeparator( const std::string &name, const std::string &optionsStr ) { TwAddSeparator( mBar.get(), name.c_str(), optionsStr.c_str() ); } void InterfaceGl::addText( const std::string &name, const std::string &optionsStr ) { TwAddButton( mBar.get(), name.c_str(), NULL, NULL, optionsStr.c_str() ); } namespace { // anonymous namespace void TW_CALL implButtonCallback( void *clientData ) { std::function<void ()> *fn = reinterpret_cast<std::function<void ()>*>( clientData ); (*fn)(); } } // anonymous namespace void InterfaceGl::addButton( const std::string &name, const std::function<void ()> &callback, const std::string &optionsStr ) { std::shared_ptr<std::function<void ()> > callbackPtr( new std::function<void ()>( callback ) ); mButtonCallbacks.push_back( callbackPtr ); TwAddButton( mBar.get(), name.c_str(), implButtonCallback, (void*)callbackPtr.get(), optionsStr.c_str() ); } void InterfaceGl::setOptions( const std::string &name, const std::string &optionsStr ) { std::string target = "`" + (std::string)TwGetBarName( mBar.get() ) + "`"; if( !( name.empty() ) ) target += "/`" + name + "`"; TwDefine( ( target + " " + optionsStr ).c_str() ); } } } // namespace cinder::params <commit_msg>Fixed MSW conflict due to its DELETE macro<commit_after>/* Copyright (c) 2010, The Barbarian Group 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. 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 "cinder/app/App.h" #include "cinder/params/Params.h" #include "AntTweakBar.h" #include <boost/assign/list_of.hpp> using namespace std; namespace cinder { namespace params { namespace { #undef DELETE #define SYNONYM(ck,ak) ((int)cinder::app::KeyEvent::KEY_ ## ck, TW_KEY_ ## ak) #define HOMONYM(k) SYNONYM(k,k) std::map<int,TwKeySpecial> specialKeys = boost::assign::map_list_of HOMONYM(RIGHT) HOMONYM(LEFT) HOMONYM(BACKSPACE) HOMONYM(DELETE) HOMONYM(TAB) HOMONYM(F1) HOMONYM(F2) HOMONYM(F3) HOMONYM(F4) HOMONYM(F5) HOMONYM(F6) HOMONYM(F7) HOMONYM(F8) HOMONYM(F9) HOMONYM(F10) HOMONYM(F11) HOMONYM(F12) HOMONYM(F13) HOMONYM(F14) HOMONYM(F15) HOMONYM(HOME) HOMONYM(END) SYNONYM(PAGEUP,PAGE_UP) SYNONYM(PAGEDOWN,PAGE_DOWN) ; #undef SYNONYM #undef HOMONYM bool mouseDown( app::MouseEvent event ) { TwMouseButtonID button; if( event.isLeft() ) button = TW_MOUSE_LEFT; else if( event.isRight() ) button = TW_MOUSE_RIGHT; else button = TW_MOUSE_MIDDLE; return TwMouseButton( TW_MOUSE_PRESSED, button ) != 0; } bool mouseUp( app::MouseEvent event ) { TwMouseButtonID button; if( event.isLeft() ) button = TW_MOUSE_LEFT; else if( event.isRight() ) button = TW_MOUSE_RIGHT; else button = TW_MOUSE_MIDDLE; return TwMouseButton( TW_MOUSE_RELEASED, button ) != 0; } bool mouseWheel( app::MouseEvent event ) { static float sWheelPos = 0; sWheelPos += event.getWheelIncrement(); return TwMouseWheel( (int)(sWheelPos) ) != 0; } bool mouseMove( app::MouseEvent event ) { return TwMouseMotion( event.getX(), event.getY() ) != 0; } bool keyDown( app::KeyEvent event ) { int kmod = 0; if( event.isShiftDown() ) kmod |= TW_KMOD_SHIFT; if( event.isControlDown() ) kmod |= TW_KMOD_CTRL; if( event.isAltDown() ) kmod |= TW_KMOD_ALT; return TwKeyPressed( (specialKeys.count( event.getCode() ) > 0) ? specialKeys[event.getCode()] : event.getChar(), kmod ) != 0; } bool resize( app::ResizeEvent event ) { TwWindowSize( event.getWidth(), event.getHeight() ); return false; } void TW_CALL implStdStringToClient( std::string& destinationClientString, const std::string& sourceLibraryString ) { // copy strings from the library to the client app destinationClientString = sourceLibraryString; } class AntMgr { public: AntMgr() { if( ! TwInit( TW_OPENGL, NULL ) ) { throw Exception(); } app::App::get()->registerMouseDown( mouseDown ); app::App::get()->registerMouseUp( mouseUp ); app::App::get()->registerMouseWheel( mouseWheel ); app::App::get()->registerMouseMove( mouseMove ); app::App::get()->registerMouseDrag( mouseMove ); app::App::get()->registerKeyDown( keyDown ); app::App::get()->registerResize( resize ); } ~AntMgr() { TwTerminate(); } }; } // anonymous namespace void initAntGl() { static std::shared_ptr<AntMgr> mgr; if( ! mgr ) mgr = std::shared_ptr<AntMgr>( new AntMgr ); } InterfaceGl::InterfaceGl( const std::string &title, const Vec2i &size, const ColorA color ) { initAntGl(); mBar = std::shared_ptr<TwBar>( TwNewBar( title.c_str() ), TwDeleteBar ); char optionsStr[1024]; sprintf( optionsStr, "`%s` size='%d %d' color='%d %d %d' alpha=%d", title.c_str(), size.x, size.y, (int)(color.r * 255), (int)(color.g * 255), (int)(color.b * 255), (int)(color.a * 255) ); TwDefine( optionsStr ); TwCopyStdStringToClientFunc( implStdStringToClient ); } void InterfaceGl::draw() { TwDraw(); } void InterfaceGl::show( bool visible ) { int32_t visibleInt = ( visible ) ? 1 : 0; TwSetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt ); } void InterfaceGl::hide() { int32_t visibleInt = 0; TwSetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt ); } bool InterfaceGl::isVisible() const { int32_t visibleInt; TwGetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt ); return visibleInt != 0; } void InterfaceGl::implAddParam( const std::string &name, void *param, int type, const std::string &optionsStr, bool readOnly ) { if( readOnly ) TwAddVarRO( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() ); else TwAddVarRW( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() ); } void InterfaceGl::addParam( const std::string &name, bool *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_BOOLCPP, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, float *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_FLOAT, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, int32_t *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_INT32, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, Vec3f *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_DIR3F, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, Quatf *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_QUAT4F, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, Color *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_COLOR3F, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, ColorA *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_COLOR4F, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, std::string *param, const std::string &optionsStr, bool readOnly ) { implAddParam( name, param, TW_TYPE_STDSTRING, optionsStr, readOnly ); } void InterfaceGl::addParam( const std::string &name, const std::vector<std::string> &enumNames, int *param, const std::string &optionsStr, bool readOnly ) { TwEnumVal *ev = new TwEnumVal[enumNames.size()]; for( size_t v = 0; v < enumNames.size(); ++v ) { ev[v].Value = v; ev[v].Label = const_cast<char*>( enumNames[v].c_str() ); } TwType evType = TwDefineEnum( (name + "EnumType").c_str(), ev, enumNames.size() ); if( readOnly ) TwAddVarRO( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() ); else TwAddVarRW( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() ); delete [] ev; } void InterfaceGl::addSeparator( const std::string &name, const std::string &optionsStr ) { TwAddSeparator( mBar.get(), name.c_str(), optionsStr.c_str() ); } void InterfaceGl::addText( const std::string &name, const std::string &optionsStr ) { TwAddButton( mBar.get(), name.c_str(), NULL, NULL, optionsStr.c_str() ); } namespace { // anonymous namespace void TW_CALL implButtonCallback( void *clientData ) { std::function<void ()> *fn = reinterpret_cast<std::function<void ()>*>( clientData ); (*fn)(); } } // anonymous namespace void InterfaceGl::addButton( const std::string &name, const std::function<void ()> &callback, const std::string &optionsStr ) { std::shared_ptr<std::function<void ()> > callbackPtr( new std::function<void ()>( callback ) ); mButtonCallbacks.push_back( callbackPtr ); TwAddButton( mBar.get(), name.c_str(), implButtonCallback, (void*)callbackPtr.get(), optionsStr.c_str() ); } void InterfaceGl::setOptions( const std::string &name, const std::string &optionsStr ) { std::string target = "`" + (std::string)TwGetBarName( mBar.get() ) + "`"; if( !( name.empty() ) ) target += "/`" + name + "`"; TwDefine( ( target + " " + optionsStr ).c_str() ); } } } // namespace cinder::params <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2012, Howard Butler, [email protected] * * 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 Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include <pdal/filters/Index.hpp> #include <pdal/PointBuffer.hpp> #include <pdal/Utils.hpp> #include <boost/concept_check.hpp> // ignore_unused_variable_warning #include <algorithm> #include <cmath> namespace pdal { namespace filters { Index::Index(Stage& prevStage, const Options& options) : pdal::Filter(prevStage, options) { return; } void Index::initialize() { Filter::initialize(); m_dimensions = getOptions().getValueOrDefault<boost::uint32_t>("dimensions", 3); return; } const Options Index::getDefaultOptions() const { Options options; Option x("x_dim", std::string("X"), "Dimension name to use for 'X' data"); Option y("y_dim", std::string("Y"), "Dimension name to use for 'Y' data"); Option z("z_dim", std::string("Z"), "Dimension name to use for 'Z' data"); Option filename("filename", "", "Filename to store the index in"); options.add(x); options.add(y); options.add(z); options.add(filename); return options; } void Index::processBuffer(PointBuffer& /* data */) const { return; } pdal::StageSequentialIterator* Index::createSequentialIterator(PointBuffer& buffer) const { return new pdal::filters::iterators::sequential::Index(*this, buffer); } namespace iterators { namespace sequential { Index::Index(const pdal::filters::Index& filter, PointBuffer& buffer) : pdal::FilterSequentialIterator(filter, buffer) , m_stage(filter) #ifdef PDAL_HAVE_FLANN , m_index(0) , m_dataset(0) #endif , m_xDim(0) , m_yDim(0) , m_zDim(0) { return; } void Index::readBeginImpl() { } void Index::readBufferBeginImpl(PointBuffer& buffer) { // Cache dimension positions if (!m_xDim && !m_yDim && !m_zDim) { pdal::Schema const& schema = buffer.getSchema(); std::string x_name = m_stage.getOptions().getValueOrDefault<std::string>("x_dim", "X"); std::string y_name = m_stage.getOptions().getValueOrDefault<std::string>("x_dim", "Y"); std::string z_name = m_stage.getOptions().getValueOrDefault<std::string>("x_dim", "Z"); m_stage.log()->get(logDEBUG2) << "Indexing PointBuffer with X: '" << x_name << "' Y: '" << y_name << "' Z: '" << z_name << " with " << m_stage.getDimensions() << " dimensions" << std::endl; m_xDim = &schema.getDimension(x_name); m_yDim = &schema.getDimension(y_name); m_zDim = &schema.getDimension(z_name); if (!m_stage.getNumPoints()) throw pdal_error("Unable to create index from pipeline that has an indeterminate number of points!"); } } std::vector<boost::uint32_t> Index::query(double const& x, double const& y, double const& z, double distance, boost::uint32_t k) { std::vector<boost::uint32_t> output; #ifdef PDAL_HAVE_FLANN std::vector<float> distances; distances.resize(k); std::vector<int> indices; indices.resize(k); std::vector<float> query(m_stage.getDimensions()); query[0] = x; query[1] = y; if (m_stage.getDimensions() > 2) query[2] = z; bool logOutput = m_stage.log()->getLevel() > logDEBUG4; m_stage.log()->floatPrecision(8); if (logOutput) m_stage.log()->get(logDEBUG2) << "Searching for x: " << x << " y: " << y << " z: " << z << " with distance threshold " << distance << std::endl; flann::Matrix<int> k_indices_mat (&indices[0], 1, k); flann::Matrix<float> k_distances_mat (&distances[0], 1, k); m_index->knnSearch (flann::Matrix<float> (&query[0], 1, m_stage.getDimensions()), k_indices_mat, k_distances_mat, k, flann::SearchParams(128)); for(unsigned i=0; i < k; ++i) { // if distance is 0, just return the nearest one, otherwise filter by distance if (Utils::compare_distance<float>((float)distance, 0)) { if (logOutput) m_stage.log()->get(logDEBUG4) << "Query found: " << "index: " << indices[i] << " distance: " << distances[i] <<std::endl; output.push_back(indices[i]); } else { if (::sqrt(distances[i]) < distance) { if (logOutput) m_stage.log()->get(logDEBUG4) << "Query found: " << "index: " << indices[i] << " distance: " << distances[i] <<std::endl; output.push_back(indices[i]); } } } #endif return output; } boost::uint32_t Index::readBufferImpl(PointBuffer& data) { const boost::uint32_t numRead = getPrevIterator().read(data); bool logOutput = m_stage.log()->getLevel() > logDEBUG4; m_stage.log()->floatPrecision(8); if (logOutput) { m_stage.log()->get(logDEBUG2) << "inserting data into index data array of capacity: " << data.getCapacity() << std::endl; } for (boost::uint32_t pointIndex=0; pointIndex<numRead; pointIndex++) { float x = static_cast<float>(getScaledValue(data, *m_xDim, pointIndex)); float y = static_cast<float>(getScaledValue(data, *m_yDim, pointIndex)); float z = static_cast<float>(getScaledValue(data, *m_zDim, pointIndex)); #ifdef PDAL_HAVE_FLANN m_data.push_back(x); m_data.push_back(y); if (m_stage.getDimensions() > 2) m_data.push_back(z); if (logOutput) { m_stage.log()->get(logDEBUG4) << "index: " << pointIndex << " x: " << x << " y: " << y << " z: " << z << std::endl; } #endif } return numRead; } double Index::getScaledValue(PointBuffer& data, Dimension const& d, std::size_t pointIndex) const { double output(0.0); float flt(0.0); boost::int8_t i8(0); boost::uint8_t u8(0); boost::int16_t i16(0); boost::uint16_t u16(0); boost::int32_t i32(0); boost::uint32_t u32(0); boost::int64_t i64(0); boost::uint64_t u64(0); boost::uint32_t size = d.getByteSize(); switch (d.getInterpretation()) { case dimension::Float: if (size == 4) { flt = data.getField<float>(d, pointIndex); output = static_cast<double>(flt); } if (size == 8) { output = data.getField<double>(d, pointIndex); } break; case dimension::SignedInteger: case dimension::SignedByte: if (size == 1) { i8 = data.getField<boost::int8_t>(d, pointIndex); output = d.applyScaling<boost::int8_t>(i8); } if (size == 2) { i16 = data.getField<boost::int16_t>(d, pointIndex); output = d.applyScaling<boost::int16_t>(i16); } if (size == 4) { i32 = data.getField<boost::int32_t>(d, pointIndex); output = d.applyScaling<boost::int32_t>(i32); } if (size == 8) { i64 = data.getField<boost::int64_t>(d, pointIndex); output = d.applyScaling<boost::int64_t>(i64); } break; case dimension::UnsignedInteger: case dimension::UnsignedByte: if (size == 1) { u8 = data.getField<boost::uint8_t>(d, pointIndex); output = d.applyScaling<boost::uint8_t>(u8); } if (size == 2) { u16 = data.getField<boost::uint16_t>(d, pointIndex); output = d.applyScaling<boost::uint16_t>(u16); } if (size == 4) { u32 = data.getField<boost::uint32_t>(d, pointIndex); output = d.applyScaling<boost::uint32_t>(u32); } if (size == 8) { u64 = data.getField<boost::uint64_t>(d, pointIndex); output = d.applyScaling<boost::uint64_t>(u64); } break; case dimension::Pointer: // stored as 64 bits, even on a 32-bit box case dimension::Undefined: throw pdal_error("Dimension data type unable to be reprojected"); } return output; } void Index::readEndImpl() { #ifdef PDAL_HAVE_FLANN // Build the index m_dataset = new flann::Matrix<float>(&m_data[0], m_stage.getNumPoints(), m_stage.getDimensions()); m_index = new flann::Index<flann::L2<float> >(*m_dataset, flann::KDTreeIndexParams(4)); m_index->buildIndex(); m_stage.log()->get(logDEBUG2) << "Built index" <<std::endl; #endif } boost::uint64_t Index::skipImpl(boost::uint64_t count) { getPrevIterator().skip(count); return count; } bool Index::atEndImpl() const { return getPrevIterator().atEnd(); } } } // iterators::sequential } } // namespaces <commit_msg>moved FLANN guards, for vs2010 lint<commit_after>/****************************************************************************** * Copyright (c) 2012, Howard Butler, [email protected] * * 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 Hobu, Inc. or Flaxen Geo Consulting nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. ****************************************************************************/ #include <pdal/filters/Index.hpp> #include <pdal/PointBuffer.hpp> #include <pdal/Utils.hpp> #include <boost/concept_check.hpp> // ignore_unused_variable_warning #include <algorithm> #include <cmath> namespace pdal { namespace filters { Index::Index(Stage& prevStage, const Options& options) : pdal::Filter(prevStage, options) { return; } void Index::initialize() { Filter::initialize(); m_dimensions = getOptions().getValueOrDefault<boost::uint32_t>("dimensions", 3); return; } const Options Index::getDefaultOptions() const { Options options; Option x("x_dim", std::string("X"), "Dimension name to use for 'X' data"); Option y("y_dim", std::string("Y"), "Dimension name to use for 'Y' data"); Option z("z_dim", std::string("Z"), "Dimension name to use for 'Z' data"); Option filename("filename", "", "Filename to store the index in"); options.add(x); options.add(y); options.add(z); options.add(filename); return options; } void Index::processBuffer(PointBuffer& /* data */) const { return; } pdal::StageSequentialIterator* Index::createSequentialIterator(PointBuffer& buffer) const { return new pdal::filters::iterators::sequential::Index(*this, buffer); } namespace iterators { namespace sequential { Index::Index(const pdal::filters::Index& filter, PointBuffer& buffer) : pdal::FilterSequentialIterator(filter, buffer) , m_stage(filter) #ifdef PDAL_HAVE_FLANN , m_index(0) , m_dataset(0) #endif , m_xDim(0) , m_yDim(0) , m_zDim(0) { return; } void Index::readBeginImpl() { } void Index::readBufferBeginImpl(PointBuffer& buffer) { // Cache dimension positions if (!m_xDim && !m_yDim && !m_zDim) { pdal::Schema const& schema = buffer.getSchema(); std::string x_name = m_stage.getOptions().getValueOrDefault<std::string>("x_dim", "X"); std::string y_name = m_stage.getOptions().getValueOrDefault<std::string>("x_dim", "Y"); std::string z_name = m_stage.getOptions().getValueOrDefault<std::string>("x_dim", "Z"); m_stage.log()->get(logDEBUG2) << "Indexing PointBuffer with X: '" << x_name << "' Y: '" << y_name << "' Z: '" << z_name << " with " << m_stage.getDimensions() << " dimensions" << std::endl; m_xDim = &schema.getDimension(x_name); m_yDim = &schema.getDimension(y_name); m_zDim = &schema.getDimension(z_name); if (!m_stage.getNumPoints()) throw pdal_error("Unable to create index from pipeline that has an indeterminate number of points!"); } } std::vector<boost::uint32_t> Index::query(double const& x, double const& y, double const& z, double distance, boost::uint32_t k) { std::vector<boost::uint32_t> output; #ifdef PDAL_HAVE_FLANN std::vector<float> distances; distances.resize(k); std::vector<int> indices; indices.resize(k); std::vector<float> query(m_stage.getDimensions()); query[0] = x; query[1] = y; if (m_stage.getDimensions() > 2) query[2] = z; bool logOutput = m_stage.log()->getLevel() > logDEBUG4; m_stage.log()->floatPrecision(8); if (logOutput) m_stage.log()->get(logDEBUG2) << "Searching for x: " << x << " y: " << y << " z: " << z << " with distance threshold " << distance << std::endl; flann::Matrix<int> k_indices_mat (&indices[0], 1, k); flann::Matrix<float> k_distances_mat (&distances[0], 1, k); m_index->knnSearch (flann::Matrix<float> (&query[0], 1, m_stage.getDimensions()), k_indices_mat, k_distances_mat, k, flann::SearchParams(128)); for(unsigned i=0; i < k; ++i) { // if distance is 0, just return the nearest one, otherwise filter by distance if (Utils::compare_distance<float>((float)distance, 0)) { if (logOutput) m_stage.log()->get(logDEBUG4) << "Query found: " << "index: " << indices[i] << " distance: " << distances[i] <<std::endl; output.push_back(indices[i]); } else { if (::sqrt(distances[i]) < distance) { if (logOutput) m_stage.log()->get(logDEBUG4) << "Query found: " << "index: " << indices[i] << " distance: " << distances[i] <<std::endl; output.push_back(indices[i]); } } } #else boost::ignore_unused_variable_warning(x); boost::ignore_unused_variable_warning(y); boost::ignore_unused_variable_warning(z); boost::ignore_unused_variable_warning(distance); boost::ignore_unused_variable_warning(k); #endif return output; } boost::uint32_t Index::readBufferImpl(PointBuffer& data) { const boost::uint32_t numRead = getPrevIterator().read(data); bool logOutput = m_stage.log()->getLevel() > logDEBUG4; m_stage.log()->floatPrecision(8); if (logOutput) { m_stage.log()->get(logDEBUG2) << "inserting data into index data array of capacity: " << data.getCapacity() << std::endl; } #ifdef PDAL_HAVE_FLANN for (boost::uint32_t pointIndex=0; pointIndex<numRead; pointIndex++) { float x = static_cast<float>(getScaledValue(data, *m_xDim, pointIndex)); float y = static_cast<float>(getScaledValue(data, *m_yDim, pointIndex)); float z = static_cast<float>(getScaledValue(data, *m_zDim, pointIndex)); m_data.push_back(x); m_data.push_back(y); if (m_stage.getDimensions() > 2) m_data.push_back(z); if (logOutput) { m_stage.log()->get(logDEBUG4) << "index: " << pointIndex << " x: " << x << " y: " << y << " z: " << z << std::endl; } } #endif return numRead; } double Index::getScaledValue(PointBuffer& data, Dimension const& d, std::size_t pointIndex) const { double output(0.0); float flt(0.0); boost::int8_t i8(0); boost::uint8_t u8(0); boost::int16_t i16(0); boost::uint16_t u16(0); boost::int32_t i32(0); boost::uint32_t u32(0); boost::int64_t i64(0); boost::uint64_t u64(0); boost::uint32_t size = d.getByteSize(); switch (d.getInterpretation()) { case dimension::Float: if (size == 4) { flt = data.getField<float>(d, pointIndex); output = static_cast<double>(flt); } if (size == 8) { output = data.getField<double>(d, pointIndex); } break; case dimension::SignedInteger: case dimension::SignedByte: if (size == 1) { i8 = data.getField<boost::int8_t>(d, pointIndex); output = d.applyScaling<boost::int8_t>(i8); } if (size == 2) { i16 = data.getField<boost::int16_t>(d, pointIndex); output = d.applyScaling<boost::int16_t>(i16); } if (size == 4) { i32 = data.getField<boost::int32_t>(d, pointIndex); output = d.applyScaling<boost::int32_t>(i32); } if (size == 8) { i64 = data.getField<boost::int64_t>(d, pointIndex); output = d.applyScaling<boost::int64_t>(i64); } break; case dimension::UnsignedInteger: case dimension::UnsignedByte: if (size == 1) { u8 = data.getField<boost::uint8_t>(d, pointIndex); output = d.applyScaling<boost::uint8_t>(u8); } if (size == 2) { u16 = data.getField<boost::uint16_t>(d, pointIndex); output = d.applyScaling<boost::uint16_t>(u16); } if (size == 4) { u32 = data.getField<boost::uint32_t>(d, pointIndex); output = d.applyScaling<boost::uint32_t>(u32); } if (size == 8) { u64 = data.getField<boost::uint64_t>(d, pointIndex); output = d.applyScaling<boost::uint64_t>(u64); } break; case dimension::Pointer: // stored as 64 bits, even on a 32-bit box case dimension::Undefined: throw pdal_error("Dimension data type unable to be reprojected"); } return output; } void Index::readEndImpl() { #ifdef PDAL_HAVE_FLANN // Build the index m_dataset = new flann::Matrix<float>(&m_data[0], m_stage.getNumPoints(), m_stage.getDimensions()); m_index = new flann::Index<flann::L2<float> >(*m_dataset, flann::KDTreeIndexParams(4)); m_index->buildIndex(); m_stage.log()->get(logDEBUG2) << "Built index" <<std::endl; #endif } boost::uint64_t Index::skipImpl(boost::uint64_t count) { getPrevIterator().skip(count); return count; } bool Index::atEndImpl() const { return getPrevIterator().atEnd(); } } } // iterators::sequential } } // namespaces <|endoftext|>
<commit_before>#include "forwardserver.h" #include "utils.h" namespace forwarder { ReturnCode ForwardServer::initCommon(rapidjson::Value& serverConfig) { desc = serverConfig["desc"].GetString(); peerLimit = serverConfig["peers"].GetInt(); port = serverConfig["port"].GetInt(); admin = serverConfig.HasMember("admin") && serverConfig["admin"].GetBool(); encrypt = serverConfig.HasMember("encrypt") && serverConfig["encrypt"].GetBool(); compress = serverConfig.HasMember("compress") && serverConfig["compress"].GetBool(); base64 = serverConfig.HasMember("base64") && serverConfig["base64"].GetBool(); isClientMode = serverConfig.HasMember("isClient") && serverConfig["isClient"].GetBool(); reconnect = serverConfig.HasMember("reconnect") && serverConfig["reconnect"].GetBool(); if (serverConfig.HasMember("reconnectdelay")) { reconnectdelay = serverConfig["reconnectdelay"].GetUint(); } if (serverConfig.HasMember("address")) { address = serverConfig["address"].GetString(); } if (encrypt) { if (serverConfig.HasMember("encryptkey")) { initCipherKey(serverConfig["encryptkey"].GetString()); } else { std::cout << "[forwarder] no encryptkey" << std::endl; return ReturnCode::Err; } } if (serverConfig.HasMember("destId")) destId = serverConfig["destId"].GetInt(); if (serverConfig.HasMember("timeoutMin")) timeoutMin = serverConfig["timeoutMin"].GetInt(); if (serverConfig.HasMember("timeoutMax")) timeoutMax = serverConfig["timeoutMax"].GetInt(); setRule(Protocol::Forward, HandleRule::Forward); setRule(Protocol::BatchForward, HandleRule::BatchForward); return ReturnCode::Ok; } bool ForwardServer::hasConsistConfig(ForwardServer* server) { if (netType != server->netType) { return false; } if (base64 != server->base64) { return false; } if (encrypt != server->encrypt) { return false; } if (encrypt) { size_t len = sizeof(AES_KEY); for (uint32_t i = 0; i < len; i++) { if (((uint8_t*)(&encryptkey))[i] != ((uint8_t*)(&server->encryptkey))[i]) { return false; } } } return true; } ForwardClient* ForwardServer::getClient(UniqID clientId) { if (clientId) { auto it_client = clients.find(clientId); if (it_client != clients.end()) return it_client->second; } return nullptr; } void ForwardServer::initCipherKey(const char* key){ AES_set_encrypt_key((const unsigned char*)key, 128, &encryptkey); } void ForwardServer::setRule(Protocol p, HandleRule rule) { ruleDict[p] = rule; } HandleRule ForwardServer::getRule(Protocol p) { auto it = ruleDict.find(p); if (it == ruleDict.end()) { return HandleRule::Unknown; } return it->second; } void ForwardServerENet::init(rapidjson::Value& serverConfig) { ENetAddress enetAddress; if (!isClientMode) { enet_address_set_host(&enetAddress, "0.0.0.0"); enetAddress.port = port; } else { enet_address_set_host(&enetAddress, address.c_str()); enetAddress.port = port; } size_t channelLimit = 1; //address.host = ENET_HOST_ANY; enet_uint32 incomingBandwidth = 0; /* assume any amount of incoming bandwidth */ enet_uint32 outgoingBandwidth = 0; /* assume any amount of outgoing bandwidth */ if (serverConfig.HasMember("bandwidth")) { incomingBandwidth = serverConfig["bandwidth"]["incoming"].GetUint(); outgoingBandwidth = serverConfig["bandwidth"]["outgoing"].GetUint(); std::cout << "[forwarder] incomingBandwidth:" << incomingBandwidth << ", outgoingBandwidth:" << outgoingBandwidth << std::endl; } host = enet_host_create(isClientMode? nullptr: &enetAddress, peerLimit, channelLimit, incomingBandwidth, outgoingBandwidth); if (!host) { std::cout << "[forwarder] An error occurred while trying to create an ENet server host." << std::endl; exit(1); return; } if (isClientMode) { enet_host_connect(host, &enetAddress, channelLimit, 0); } } void ForwardServerENet::doReconnect() { std::cout << "[forwarder] ENet doReconnect" << std::endl; ENetAddress enetAddress; enet_address_set_host(&enetAddress, address.c_str()); enetAddress.port = port; size_t channelLimit = 1; enet_host_connect(host, &enetAddress, channelLimit, 0); }; void ForwardServerENet::doDisconnect() { std::cout << "[forwarder] ENet doDisconnect" << std::endl; ForwardClient* client = getClient(clientID); if (!client) { return; } ForwardClientENet* clientENet = dynamic_cast<ForwardClientENet*>(client); auto state = clientENet->peer->state; if(state == ENET_PEER_STATE_CONNECTING || state == ENET_PEER_STATE_CONNECTED){ enet_peer_disconnect(clientENet->peer, 0); } } bool ForwardServerENet::isConnected() { ForwardClient* client = getClient(clientID); if (!client) { return false; } auto state = dynamic_cast<ForwardClientENet*>(client)->peer->state; return state == ENET_PEER_STATE_CONNECTED; } void ForwardServerENet::release() { enet_host_destroy(host); host = nullptr; } void ForwardServerWS::init(rapidjson::Value& serverConfig) { if (!isClientMode) { server.set_error_channels(websocketpp::log::elevel::all); server.set_access_channels(websocketpp::log::alevel::none); server.init_asio(); server.listen(port); server.start_accept(); } else { serverAsClient.set_error_channels(websocketpp::log::elevel::all); serverAsClient.set_access_channels(websocketpp::log::alevel::none); serverAsClient.init_asio(); doReconnect(); } } void ForwardServerWS::release() { if (!isClientMode) { server.stop(); } else { doDisconnect(); serverAsClient.stop(); } hdlToClientId.clear(); } void ForwardServerWS::poll() { if (!isClientMode) { server.poll_one(); } else { serverAsClient.poll_one(); } } void ForwardServerWS::doReconnect() { std::cout << "[forwarder] WS doReconnect" << std::endl; if (isConnected()) { return; } std::string uri = getUri(); websocketpp::lib::error_code ec; WebsocketClient::connection_ptr con = serverAsClient.get_connection(uri, ec); if (ec) { std::cout << "[forwarder] WS error, could not create connection because: " << ec.message() << std::endl; return; } serverAsClient.connect(con); } void ForwardServerWS::doDisconnect() { std::cout << "[forwarder] WS doDisconnect" << std::endl; auto client = getClient(clientID); if (!client) { return; } ForwardClientWS* clientWS = dynamic_cast<ForwardClientWS*>(client); auto hdl = clientWS->hdl; websocketpp::lib::error_code ec; websocketpp::close::status::value code = websocketpp::close::status::normal; std::string reason = ""; serverAsClient.close(hdl, code, reason, ec); if (ec) { std::cout << "[forwarder] WS error, initiating close: " << ec.message() << std::endl; } } bool ForwardServerWS::isConnected() { auto client = getClient(clientID); if (!client) { return false; } auto hdl = dynamic_cast<ForwardClientWS*>(client)->hdl; return server.get_con_from_hdl(hdl)->get_state() == websocketpp::session::state::value::connecting; } } <commit_msg>no message<commit_after>#include "forwardserver.h" #include "utils.h" namespace forwarder { ReturnCode ForwardServer::initCommon(rapidjson::Value& serverConfig) { desc = serverConfig["desc"].GetString(); peerLimit = serverConfig["peers"].GetInt(); port = serverConfig["port"].GetInt(); admin = serverConfig.HasMember("admin") && serverConfig["admin"].GetBool(); encrypt = serverConfig.HasMember("encrypt") && serverConfig["encrypt"].GetBool(); compress = serverConfig.HasMember("compress") && serverConfig["compress"].GetBool(); base64 = serverConfig.HasMember("base64") && serverConfig["base64"].GetBool(); isClientMode = serverConfig.HasMember("isClient") && serverConfig["isClient"].GetBool(); reconnect = serverConfig.HasMember("reconnect") && serverConfig["reconnect"].GetBool(); if (serverConfig.HasMember("reconnectdelay")) { reconnectdelay = serverConfig["reconnectdelay"].GetUint(); } if (serverConfig.HasMember("address")) { address = serverConfig["address"].GetString(); } if (encrypt) { if (serverConfig.HasMember("encryptkey")) { initCipherKey(serverConfig["encryptkey"].GetString()); } else { std::cout << "[forwarder] no encryptkey" << std::endl; return ReturnCode::Err; } } if (serverConfig.HasMember("destId")) destId = serverConfig["destId"].GetInt(); if (serverConfig.HasMember("timeoutMin")) timeoutMin = serverConfig["timeoutMin"].GetInt(); if (serverConfig.HasMember("timeoutMax")) timeoutMax = serverConfig["timeoutMax"].GetInt(); setRule(Protocol::Forward, HandleRule::Forward); setRule(Protocol::BatchForward, HandleRule::BatchForward); return ReturnCode::Ok; } bool ForwardServer::hasConsistConfig(ForwardServer* server) { if (netType != server->netType) { return false; } if (base64 != server->base64) { return false; } if (encrypt != server->encrypt) { return false; } if (encrypt) { size_t len = sizeof(AES_KEY); for (uint32_t i = 0; i < len; i++) { if (((uint8_t*)(&encryptkey))[i] != ((uint8_t*)(&server->encryptkey))[i]) { return false; } } } return true; } ForwardClient* ForwardServer::getClient(UniqID clientId) { if (clientId) { auto it_client = clients.find(clientId); if (it_client != clients.end()) return it_client->second; } return nullptr; } void ForwardServer::initCipherKey(const char* key){ AES_set_encrypt_key((const unsigned char*)key, 128, &encryptkey); } void ForwardServer::setRule(Protocol p, HandleRule rule) { ruleDict[p] = rule; } HandleRule ForwardServer::getRule(Protocol p) { auto it = ruleDict.find(p); if (it == ruleDict.end()) { return HandleRule::Unknown; } return it->second; } void ForwardServerENet::init(rapidjson::Value& serverConfig) { ENetAddress enetAddress; if (!isClientMode) { enet_address_set_host(&enetAddress, "0.0.0.0"); enetAddress.port = port; } else { enet_address_set_host(&enetAddress, address.c_str()); enetAddress.port = port; } size_t channelLimit = 1; //address.host = ENET_HOST_ANY; enet_uint32 incomingBandwidth = 0; /* assume any amount of incoming bandwidth */ enet_uint32 outgoingBandwidth = 0; /* assume any amount of outgoing bandwidth */ if (serverConfig.HasMember("bandwidth")) { incomingBandwidth = serverConfig["bandwidth"]["incoming"].GetUint(); outgoingBandwidth = serverConfig["bandwidth"]["outgoing"].GetUint(); std::cout << "[forwarder] incomingBandwidth:" << incomingBandwidth << ", outgoingBandwidth:" << outgoingBandwidth << std::endl; } host = enet_host_create(isClientMode? nullptr: &enetAddress, peerLimit, channelLimit, incomingBandwidth, outgoingBandwidth); if (!host) { std::cout << "[forwarder] An error occurred while trying to create an ENet server host." << std::endl; exit(1); return; } if (isClientMode) { enet_host_connect(host, &enetAddress, channelLimit, 0); } } void ForwardServerENet::doReconnect() { std::cout << "[forwarder] ENet doReconnect" << std::endl; ENetAddress enetAddress; enet_address_set_host(&enetAddress, address.c_str()); enetAddress.port = port; size_t channelLimit = 1; enet_host_connect(host, &enetAddress, channelLimit, 0); }; void ForwardServerENet::doDisconnect() { std::cout << "[forwarder] ENet doDisconnect" << std::endl; ForwardClient* client = getClient(clientID); if (!client) { return; } ForwardClientENet* clientENet = dynamic_cast<ForwardClientENet*>(client); auto state = clientENet->peer->state; if(state == ENET_PEER_STATE_CONNECTING || state == ENET_PEER_STATE_CONNECTED){ enet_peer_disconnect(clientENet->peer, 0); } } bool ForwardServerENet::isConnected() { ForwardClient* client = getClient(clientID); if (!client) { return false; } auto state = dynamic_cast<ForwardClientENet*>(client)->peer->state; return state == ENET_PEER_STATE_CONNECTED; } void ForwardServerENet::release() { enet_host_destroy(host); host = nullptr; } void ForwardServerWS::init(rapidjson::Value& serverConfig) { if (!isClientMode) { server.set_error_channels(websocketpp::log::elevel::all); server.set_access_channels(websocketpp::log::alevel::none); server.init_asio(); server.listen(port); server.start_accept(); } else { serverAsClient.set_error_channels(websocketpp::log::elevel::all); serverAsClient.set_access_channels(websocketpp::log::alevel::none); serverAsClient.init_asio(); doReconnect(); } } void ForwardServerWS::release() { doDisconnect(); hdlToClientId.clear(); } void ForwardServerWS::poll() { if (!isClientMode) { server.poll_one(); } else { serverAsClient.poll_one(); } } void ForwardServerWS::doReconnect() { std::cout << "[forwarder] WS doReconnect" << std::endl; if (isConnected()) { return; } std::string uri = getUri(); websocketpp::lib::error_code ec; WebsocketClient::connection_ptr con = serverAsClient.get_connection(uri, ec); if (ec) { std::cout << "[forwarder] WS error, could not create connection because: " << ec.message() << std::endl; return; } serverAsClient.connect(con); } void ForwardServerWS::doDisconnect() { std::cout << "[forwarder] WS doDisconnect" << std::endl; std::string reason = ""; websocketpp::lib::error_code ec; websocketpp::close::status::value code = websocketpp::close::status::normal; if (!isClientMode) { server.stop_listening(); server.stop(); } else { auto client = getClient(clientID); if (!client) { return; } ForwardClientWS* clientWS = dynamic_cast<ForwardClientWS*>(client); auto hdl = clientWS->hdl; serverAsClient.close(hdl, code, reason, ec); if (ec) { std::cout << "[forwarder] WS error, initiating close: " << ec.message() << std::endl; } serverAsClient.stop(); } } bool ForwardServerWS::isConnected() { auto client = getClient(clientID); if (!client) { return false; } auto hdl = dynamic_cast<ForwardClientWS*>(client)->hdl; return server.get_con_from_hdl(hdl)->get_state() == websocketpp::session::state::value::connecting; } } <|endoftext|>
<commit_before>/* * InterColComm.cpp * * Created on: Aug 28, 2008 * Author: rasmussn */ #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <string.h> #include "InterColComm.hpp" #include "HyPerCol.hpp" #include "../connections/PVConnection.h" namespace PV { InterColComm::InterColComm(int* argc, char*** argv, HyPerCol* col) { float r; commInit(argc, argv); r = sqrt(commSize); numRows = (int) r; numCols = (int) commSize / numRows; numHyPerCols = numRows * numCols; // TODO - build a communicator based on the new processor grid (don't use MPI_COMM_WORLD) neighborInit(); hc = col; numPublishers = 0; for (int i = 0; i < MAX_PUBLISHERS; i++) { publishers[i] = NULL; } } InterColComm::~InterColComm() { commFinalize(); for (int i = 0; i < MAX_PUBLISHERS; i++) { if (publishers[i] != NULL) { delete publishers[i]; } } } int InterColComm::commInit(int* argc, char*** argv) { MPI_Init(argc, argv); MPI_Comm_rank(MPI_COMM_WORLD, &commRank); MPI_Comm_size(MPI_COMM_WORLD, &commSize); #ifdef DEBUG_OUTPUT printf("[%d]: InterColComm::commInit: size=%d\n", commRank, commSize); fflush(stdout); #endif return 0; } int InterColComm::commFinalize() { MPI_Finalize(); return 0; } int InterColComm::addPublisher(HyPerLayer* pub, size_t size1, size_t size2, int numLevels) { int pubId = pub->getLayerId(); publishers[pubId] = new Publisher(pubId, numNeighbors, size1, numBorders, size2, numLevels); numPublishers += 1; DataStore* store = publishers[pubId]->dataStore(); for (int i = 0; i < numBorders; i++) { for (int delay = 0; delay < numLevels; delay++) { int borderIndex = Publisher::borderStoreIndex(i, numNeighbors); PVLayerCube* border = (PVLayerCube*) store->buffer(borderIndex, delay); pvcube_setAddr(border); pub->initBorder(border, borders[i]); } } return pubId; } int InterColComm::subscribe(HyPerConn* conn) { int pubId = conn->preSynapticLayer()->getLayerId(); assert(pubId < MAX_PUBLISHERS && pubId >= 0); return publishers[pubId]->subscribe(conn); } int InterColComm::publish(HyPerLayer* pub, PVLayerCube* cube) { int pubId = pub->getLayerId(); return publishers[pubId]->publish(pub, neighbors, numNeighbors, borders, numBorders, cube); } /** * deliver all outstanding published messages */ int InterColComm::deliver(int pubId) { #ifdef DEBUG_OUTPUT printf("[%d]: InterColComm::deliver: pubId=%d\n", commRank, pubId); fflush(stdout); #endif return publishers[pubId]->deliver(hc, numNeighbors, numBorders); } /** * Initialize the communication neighbors */ int InterColComm::neighborInit() { int num_neighbors = 0; int num_borders = 0; // initialize neighbor and border lists // (local borders and remote neighbors form the complete neighborhood) this->numNeighbors = numberNeighbors(); this->numBorders = 1 + MAX_NEIGHBORS - this->numNeighbors; for (int i = 0; i < 1 + MAX_NEIGHBORS; i++) { neighbors[i] = 0; int n = neighborIndex(commRank, i); if (n >= 0) { neighbors[num_neighbors++] = n; #ifdef DEBUG_OUTPUT printf("[%d]: neighborInit: neighbor[%d] of %d is %d, i = %d\n", commRank, num_neighbors - 1, this->numNeighbors, n, i); fflush(stdout); #endif } else { borders[num_borders++] = -n; } } assert(this->numNeighbors == num_neighbors); assert(this->numBorders == num_borders); return 0; } /** * Returns the communication row id for the given communication id */ int InterColComm::commRow(int commId) { return (int) commId / this->numCols; } /** * Returns the communication column id for the given communication id */ int InterColComm::commColumn(int commId) { return (commId - this->numCols * commRow(commId)); } /** * Returns true if the given commId has a western neighbor * (false otherwise) */ bool InterColComm::hasWesternNeighbor(int commId) { return commId % this->numHyPerCols; } /** * Returns true if the given commId has an eastern neighbor * (false otherwise) */ bool InterColComm::hasEasternNeighbor(int commId) { return (commId + 1) % this->numHyPerCols; } /** * Returns true if the given commId has a northern neighbor * (false otherwise) */ bool InterColComm::hasNorthernNeighbor(int commId) { return ((commId + this->numHyPerCols) > (this->commSize - 1)) ? 0 : 1; } /** * Returns true if the given commId has a southern neighbor * (false otherwise) */ bool InterColComm::hasSouthernNeighbor(int commId) { return ((commId - this->numHyPerCols) < 0) ? 0 : 1; } /** * Returns the number in communication neighborhood (local included) */ int InterColComm::numberNeighbors() { int n = 1; int hasWest = hasWesternNeighbor(commRank); int hasEast = hasEasternNeighbor(commRank); int hasNorth = hasNorthernNeighbor(commRank); int hasSouth = hasSouthernNeighbor(commRank); if (hasNorth > 0) n += 1; if (hasSouth > 0) n += 1; if (hasWest > 0) { n += 1; if (hasNorth > 0) n += 1; if (hasSouth > 0) n += 1; } if (hasEast > 0) { n += 1; if (hasNorth > 0) n += 1; if (hasSouth > 0) n += 1; } return n; } /** * Returns the communication id of the northwestern HyperColumn */ int InterColComm::northwest(int commId) { if (hasNorthernNeighbor(commId) == 0) return -NORTHWEST; return west(commId + this->numHyPerCols); } /** * Returns the communication id of the northern HyperColumn */ int InterColComm::north(int commId) { if (hasNorthernNeighbor(commId) == 0) return -NORTH; return (commId + this->numHyPerCols); } /** * Returns the communication id of the northeastern HyperColumn */ int InterColComm::northeast(int commId) { if (hasNorthernNeighbor(commId) == 0) return -NORTHEAST; return east(commId + this->numHyPerCols); } /** * Returns the communication id of the western HyperColumn */ int InterColComm::west(int commId) { if (hasWesternNeighbor(commId) == 0) return -WEST; return (commRow(commId) * numHyPerCols + ((commId - 1) % numHyPerCols)); } /** * Returns the communication id of the eastern HyperColumn */ int InterColComm::east(int commId) { if (hasEasternNeighbor(commId) == 0) return -EAST; return (commRow(commId) * numHyPerCols + ((commId + 1) % numHyPerCols)); } /** * Returns the communication id of the southwestern HyperColumn */ int InterColComm::southwest(int commId) { if (hasSouthernNeighbor(commId) == 0) return -SOUTHWEST; return west(commId - this->numHyPerCols); } /** * Returns the communication id of the southern HyperColumn */ int InterColComm::south(int commId) { if (hasSouthernNeighbor(commId) == 0) return -SOUTH; return (commId - this->numHyPerCols); } /** * Returns the communication id of the southeastern HyperColumn */ int InterColComm::southeast(int commId) { if (hasSouthernNeighbor(commId) == 0) return -SOUTHEAST; return east(commId - this->numHyPerCols); } /** * Returns the sender rank for the given connection index */ int InterColComm::neighborIndex(int commId, int index) { switch (index) { case LOCAL: /* local */ return commId; case NORTHWEST : /* northwest */ return northwest(commId); case NORTH : /* north */ return north(commId); case NORTHEAST : /* northeast */ return northeast(commId); case WEST : /* west */ return west(commId); case EAST : /* east */ return east(commId); case SOUTHWEST : /* southwest */ return southwest(commId); case SOUTH : /* south */ return south(commId); case SOUTHEAST : /* southeast */ return southeast(commId); default: fprintf(stderr, "ERROR:neighborIndex: bad index\n"); } return -1; } Publisher::Publisher(int pubId, int numType1, size_t size1, int numType2, size_t size2, int numLevels) { size_t maxSize = (size1 > size2) ? size1 : size2; this->pubId = pubId; this->numSubscribers = 0; this->store = new DataStore(numType1+numType2, maxSize, numLevels); for (int i = 0; i < MAX_SUBSCRIBERS; i++) { this->connection[i] = NULL; } } Publisher::~Publisher() { delete store; } int Publisher::publish(HyPerLayer* pub, int neighbors[], int numNeighbors, int borders[], int numBorders, PVLayerCube* cube) { size_t size = cube->size; assert(size == store->size()); if (numSubscribers < 1) { // no one to deliver to return 0; } // send/recv to/from neighbors for (int i = 0; i < numNeighbors; i++) { // Note - cube->data addr need not be correct as it will be wrong copied in from MPI void* recvBuf = recvBuffer(i); MPI_Irecv(recvBuf, size, MPI_CHAR, neighbors[i], pubId, MPI_COMM_WORLD, &request[i]); MPI_Send(cube, size, MPI_CHAR, neighbors[i], pubId, MPI_COMM_WORLD); #ifdef DEBUG_OUTPUT int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); printf("[%d]: Publisher::publish: neighbor=%d pubId=%d sendbuf=%p recvbuf=%p\n", rank, neighbors[i], i, cube, recvBuf); fflush(stdout); #endif } // // transform cube (and copy) for boundary conditions of neighbor slots that // don't exist in processor topology (i.e., a hypercolumn at edge of image) // for (int i = 0; i < numBorders; i++) { int borderIndex = Publisher::borderStoreIndex(i, numNeighbors); PVLayerCube* border = (PVLayerCube*) recvBuffer(borderIndex); pub->copyToBorder(borders[i], cube, border); } return 0; } /** * deliver all outstanding published messages */ int Publisher::deliver(HyPerCol* hc, int numNeighbors, int numBorders) { if (numSubscribers < 1) { // no one to deliver to return 0; } // deliver delayed information first for (int ic = 0; ic < numSubscribers; ic++) { HyPerConn* conn = connection[ic]; int delay = conn->getDelay(); if (delay > 0) { for (int n = 0; n < numNeighbors; n++) { PVLayerCube* cube = (PVLayerCube*) store->buffer(n, delay); pvcube_setAddr(cube); // fix data address arriving from MPI #ifdef DEBUG_OUTPUT int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); printf("[%d]: Publisher::deliver: neighbor=%d buf=%p\n", rank, n, cube); fflush(stdout); #endif conn->deliver(cube, n); } } } // deliver current (no delay) information last for (int n = 0; n < numNeighbors; n++) { int neighborId = n; /* WARNING - this must be initialized to n to work with PV_PMI */ MPI_Waitany(numNeighbors, request, &neighborId, MPI_STATUS_IGNORE); for (int ic = 0; ic < numSubscribers; ic++) { HyPerConn* conn = this->connection[ic]; if (conn->getDelay() == 0) { PVLayerCube* cube = (PVLayerCube*) store->buffer(neighborId, 0); pvcube_setAddr(cube); // fix data address arriving from MPI #ifdef DEBUG_OUTPUT int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); printf("[%d]: Publisher::deliver: neighbor=%d buf=%p\n", rank, neighborId, cube); fflush(stdout); #endif conn->deliver(cube, neighborId); } } } // deliver border regions for (int i = 0; i < numBorders; i++) { int borderIndex = Publisher::borderStoreIndex(i, numNeighbors); for (int ic = 0; ic < numSubscribers; ic++) { HyPerConn* conn = this->connection[ic]; if (conn->getDelay() == 0) { PVLayerCube* border = (PVLayerCube*) store->buffer(borderIndex, 0); pvcube_setAddr(border); // fix data address arriving from MPI conn->deliver(border, borderIndex); } } } return 0; } int Publisher::subscribe(HyPerConn* conn) { connection[numSubscribers] = conn; numSubscribers += 1; return 0; } } // end namespace PV <commit_msg>Added delay to delivery of border regions.<commit_after>/* * InterColComm.cpp * * Created on: Aug 28, 2008 * Author: rasmussn */ #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <string.h> #include "InterColComm.hpp" #include "HyPerCol.hpp" #include "../connections/PVConnection.h" namespace PV { InterColComm::InterColComm(int* argc, char*** argv, HyPerCol* col) { float r; commInit(argc, argv); r = sqrt(commSize); numRows = (int) r; numCols = (int) commSize / numRows; numHyPerCols = numRows * numCols; // TODO - build a communicator based on the new processor grid (don't use MPI_COMM_WORLD) neighborInit(); hc = col; numPublishers = 0; for (int i = 0; i < MAX_PUBLISHERS; i++) { publishers[i] = NULL; } } InterColComm::~InterColComm() { commFinalize(); for (int i = 0; i < MAX_PUBLISHERS; i++) { if (publishers[i] != NULL) { delete publishers[i]; } } } int InterColComm::commInit(int* argc, char*** argv) { MPI_Init(argc, argv); MPI_Comm_rank(MPI_COMM_WORLD, &commRank); MPI_Comm_size(MPI_COMM_WORLD, &commSize); #ifdef DEBUG_OUTPUT printf("[%d]: InterColComm::commInit: size=%d\n", commRank, commSize); fflush(stdout); #endif return 0; } int InterColComm::commFinalize() { MPI_Finalize(); return 0; } int InterColComm::addPublisher(HyPerLayer* pub, size_t size1, size_t size2, int numLevels) { int pubId = pub->getLayerId(); publishers[pubId] = new Publisher(pubId, numNeighbors, size1, numBorders, size2, numLevels); numPublishers += 1; DataStore* store = publishers[pubId]->dataStore(); for (int i = 0; i < numBorders; i++) { for (int delay = 0; delay < numLevels; delay++) { int borderIndex = Publisher::borderStoreIndex(i, numNeighbors); PVLayerCube* border = (PVLayerCube*) store->buffer(borderIndex, delay); pvcube_setAddr(border); pub->initBorder(border, borders[i]); } } return pubId; } int InterColComm::subscribe(HyPerConn* conn) { int pubId = conn->preSynapticLayer()->getLayerId(); assert(pubId < MAX_PUBLISHERS && pubId >= 0); return publishers[pubId]->subscribe(conn); } int InterColComm::publish(HyPerLayer* pub, PVLayerCube* cube) { int pubId = pub->getLayerId(); return publishers[pubId]->publish(pub, neighbors, numNeighbors, borders, numBorders, cube); } /** * deliver all outstanding published messages */ int InterColComm::deliver(int pubId) { #ifdef DEBUG_OUTPUT printf("[%d]: InterColComm::deliver: pubId=%d\n", commRank, pubId); fflush(stdout); #endif return publishers[pubId]->deliver(hc, numNeighbors, numBorders); } /** * Initialize the communication neighbors */ int InterColComm::neighborInit() { int num_neighbors = 0; int num_borders = 0; // initialize neighbor and border lists // (local borders and remote neighbors form the complete neighborhood) this->numNeighbors = numberNeighbors(); this->numBorders = 1 + MAX_NEIGHBORS - this->numNeighbors; for (int i = 0; i < 1 + MAX_NEIGHBORS; i++) { neighbors[i] = 0; int n = neighborIndex(commRank, i); if (n >= 0) { neighbors[num_neighbors++] = n; #ifdef DEBUG_OUTPUT printf("[%d]: neighborInit: neighbor[%d] of %d is %d, i = %d\n", commRank, num_neighbors - 1, this->numNeighbors, n, i); fflush(stdout); #endif } else { borders[num_borders++] = -n; } } assert(this->numNeighbors == num_neighbors); assert(this->numBorders == num_borders); return 0; } /** * Returns the communication row id for the given communication id */ int InterColComm::commRow(int commId) { return (int) commId / this->numCols; } /** * Returns the communication column id for the given communication id */ int InterColComm::commColumn(int commId) { return (commId - this->numCols * commRow(commId)); } /** * Returns true if the given commId has a western neighbor * (false otherwise) */ bool InterColComm::hasWesternNeighbor(int commId) { return commId % this->numHyPerCols; } /** * Returns true if the given commId has an eastern neighbor * (false otherwise) */ bool InterColComm::hasEasternNeighbor(int commId) { return (commId + 1) % this->numHyPerCols; } /** * Returns true if the given commId has a northern neighbor * (false otherwise) */ bool InterColComm::hasNorthernNeighbor(int commId) { return ((commId + this->numHyPerCols) > (this->commSize - 1)) ? 0 : 1; } /** * Returns true if the given commId has a southern neighbor * (false otherwise) */ bool InterColComm::hasSouthernNeighbor(int commId) { return ((commId - this->numHyPerCols) < 0) ? 0 : 1; } /** * Returns the number in communication neighborhood (local included) */ int InterColComm::numberNeighbors() { int n = 1; int hasWest = hasWesternNeighbor(commRank); int hasEast = hasEasternNeighbor(commRank); int hasNorth = hasNorthernNeighbor(commRank); int hasSouth = hasSouthernNeighbor(commRank); if (hasNorth > 0) n += 1; if (hasSouth > 0) n += 1; if (hasWest > 0) { n += 1; if (hasNorth > 0) n += 1; if (hasSouth > 0) n += 1; } if (hasEast > 0) { n += 1; if (hasNorth > 0) n += 1; if (hasSouth > 0) n += 1; } return n; } /** * Returns the communication id of the northwestern HyperColumn */ int InterColComm::northwest(int commId) { if (hasNorthernNeighbor(commId) == 0) return -NORTHWEST; return west(commId + this->numHyPerCols); } /** * Returns the communication id of the northern HyperColumn */ int InterColComm::north(int commId) { if (hasNorthernNeighbor(commId) == 0) return -NORTH; return (commId + this->numHyPerCols); } /** * Returns the communication id of the northeastern HyperColumn */ int InterColComm::northeast(int commId) { if (hasNorthernNeighbor(commId) == 0) return -NORTHEAST; return east(commId + this->numHyPerCols); } /** * Returns the communication id of the western HyperColumn */ int InterColComm::west(int commId) { if (hasWesternNeighbor(commId) == 0) return -WEST; return (commRow(commId) * numHyPerCols + ((commId - 1) % numHyPerCols)); } /** * Returns the communication id of the eastern HyperColumn */ int InterColComm::east(int commId) { if (hasEasternNeighbor(commId) == 0) return -EAST; return (commRow(commId) * numHyPerCols + ((commId + 1) % numHyPerCols)); } /** * Returns the communication id of the southwestern HyperColumn */ int InterColComm::southwest(int commId) { if (hasSouthernNeighbor(commId) == 0) return -SOUTHWEST; return west(commId - this->numHyPerCols); } /** * Returns the communication id of the southern HyperColumn */ int InterColComm::south(int commId) { if (hasSouthernNeighbor(commId) == 0) return -SOUTH; return (commId - this->numHyPerCols); } /** * Returns the communication id of the southeastern HyperColumn */ int InterColComm::southeast(int commId) { if (hasSouthernNeighbor(commId) == 0) return -SOUTHEAST; return east(commId - this->numHyPerCols); } /** * Returns the sender rank for the given connection index */ int InterColComm::neighborIndex(int commId, int index) { switch (index) { case LOCAL: /* local */ return commId; case NORTHWEST : /* northwest */ return northwest(commId); case NORTH : /* north */ return north(commId); case NORTHEAST : /* northeast */ return northeast(commId); case WEST : /* west */ return west(commId); case EAST : /* east */ return east(commId); case SOUTHWEST : /* southwest */ return southwest(commId); case SOUTH : /* south */ return south(commId); case SOUTHEAST : /* southeast */ return southeast(commId); default: fprintf(stderr, "ERROR:neighborIndex: bad index\n"); } return -1; } Publisher::Publisher(int pubId, int numType1, size_t size1, int numType2, size_t size2, int numLevels) { size_t maxSize = (size1 > size2) ? size1 : size2; this->pubId = pubId; this->numSubscribers = 0; this->store = new DataStore(numType1+numType2, maxSize, numLevels); for (int i = 0; i < MAX_SUBSCRIBERS; i++) { this->connection[i] = NULL; } } Publisher::~Publisher() { delete store; } int Publisher::publish(HyPerLayer* pub, int neighbors[], int numNeighbors, int borders[], int numBorders, PVLayerCube* cube) { size_t size = cube->size; assert(size == store->size()); if (numSubscribers < 1) { // no one to deliver to return 0; } // send/recv to/from neighbors for (int i = 0; i < numNeighbors; i++) { // Note - cube->data addr need not be correct as it will be wrong copied in from MPI void* recvBuf = recvBuffer(i); MPI_Irecv(recvBuf, size, MPI_CHAR, neighbors[i], pubId, MPI_COMM_WORLD, &request[i]); MPI_Send(cube, size, MPI_CHAR, neighbors[i], pubId, MPI_COMM_WORLD); #ifdef DEBUG_OUTPUT int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); printf("[%d]: Publisher::publish: neighbor=%d pubId=%d sendbuf=%p recvbuf=%p\n", rank, neighbors[i], i, cube, recvBuf); fflush(stdout); #endif } // // transform cube (and copy) for boundary conditions of neighbor slots that // don't exist in processor topology (i.e., a hypercolumn at edge of image) // for (int i = 0; i < numBorders; i++) { int borderIndex = Publisher::borderStoreIndex(i, numNeighbors); PVLayerCube* border = (PVLayerCube*) recvBuffer(borderIndex); pub->copyToBorder(borders[i], cube, border); } return 0; } /** * deliver all outstanding published messages */ int Publisher::deliver(HyPerCol* hc, int numNeighbors, int numBorders) { if (numSubscribers < 1) { // no one to deliver to return 0; } // deliver delayed information first for (int ic = 0; ic < numSubscribers; ic++) { HyPerConn* conn = connection[ic]; int delay = conn->getDelay(); if (delay > 0) { for (int n = 0; n < numNeighbors; n++) { PVLayerCube* cube = (PVLayerCube*) store->buffer(n, delay); pvcube_setAddr(cube); // fix data address arriving from MPI #ifdef DEBUG_OUTPUT int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); printf("[%d]: Publisher::deliver: neighbor=%d buf=%p\n", rank, n, cube); fflush(stdout); #endif conn->deliver(cube, n); } } } // deliver current (no delay) information last for (int n = 0; n < numNeighbors; n++) { int neighborId = n; /* WARNING - this must be initialized to n to work with PV_MPI */ MPI_Waitany(numNeighbors, request, &neighborId, MPI_STATUS_IGNORE); for (int ic = 0; ic < numSubscribers; ic++) { HyPerConn* conn = this->connection[ic]; if (conn->getDelay() == 0) { PVLayerCube* cube = (PVLayerCube*) store->buffer(neighborId, 0); pvcube_setAddr(cube); // fix data address arriving from MPI #ifdef DEBUG_OUTPUT int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); printf("[%d]: Publisher::deliver: neighbor=%d buf=%p\n", rank, neighborId, cube); fflush(stdout); #endif conn->deliver(cube, neighborId); } } } // deliver border regions for (int i = 0; i < numBorders; i++) { int borderIndex = Publisher::borderStoreIndex(i, numNeighbors); for (int ic = 0; ic < numSubscribers; ic++) { HyPerConn* conn = this->connection[ic]; int delay = conn->getDelay(); PVLayerCube* border = (PVLayerCube*) store->buffer(borderIndex, delay); pvcube_setAddr(border); // fix data address arriving from MPI conn->deliver(border, borderIndex); } } return 0; } int Publisher::subscribe(HyPerConn* conn) { connection[numSubscribers] = conn; numSubscribers += 1; return 0; } } // end namespace PV <|endoftext|>
<commit_before>/* * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved * * Contact: Lukasz Wojciechowski <[email protected]> * * 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. */ /* * @file Backtrace.cpp * @author Adam Malinowski <[email protected]> * @version 1.0 * @brief Implementation of backtrace utility class. */ #include <cxxabi.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <attributes/attributes.h> #include <log/log.h> #include "Backtrace.h" namespace Cynara { Backtrace &Backtrace::getInstance(void) { static Backtrace m_instance; return m_instance; } Backtrace::Backtrace() : m_fileName(NULL), m_functionName(NULL), m_lineNumber(0) { } Backtrace::~Backtrace() { } void Backtrace::getSourceInfo(unw_word_t proc_address UNUSED) { // TODO: extract filename and line number for symbol at given address m_fileName = "??"; m_functionName = "??"; m_lineNumber = 0; } const std::string Backtrace::buildBacktrace(void) { std::string backtrace; unw_cursor_t cursor; unw_context_t uc; unw_word_t ip, sp; char proc_name[BUFSIZ]; char btstr[BUFSIZ]; unw_word_t offp; int status; unw_getcontext(&uc); // get rid of previous function: Backtrace::getBacktrace unw_init_local(&cursor, &uc); unw_step(&cursor); while (unw_step(&cursor) > 0) { unw_get_reg(&cursor, UNW_REG_IP, &ip); unw_get_reg(&cursor, UNW_REG_SP, &sp); unw_get_proc_name(&cursor, proc_name, sizeof(proc_name), &offp); char *realname = abi::__cxa_demangle(proc_name, 0, 0, &status); getSourceInfo(ip); snprintf(btstr, sizeof(btstr), "ip = %p, sp = %p, %s, %s:%u\n", ip, sp, realname ? realname : proc_name, m_fileName, m_lineNumber); free(realname); backtrace += btstr; } return backtrace; } const std::string Backtrace::getBacktrace(void) { return getInstance().buildBacktrace(); } } /* namespace Cynara */ <commit_msg>Fix build break on DEBUG dbuild type<commit_after>/* * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved * * Contact: Lukasz Wojciechowski <[email protected]> * * 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. */ /* * @file Backtrace.cpp * @author Adam Malinowski <[email protected]> * @version 1.0 * @brief Implementation of backtrace utility class. */ #include <cxxabi.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <iostream> #include <sstream> #include <attributes/attributes.h> #include <log/log.h> #include "Backtrace.h" namespace Cynara { Backtrace &Backtrace::getInstance(void) { static Backtrace m_instance; return m_instance; } Backtrace::Backtrace() : m_fileName(NULL), m_functionName(NULL), m_lineNumber(0) { } Backtrace::~Backtrace() { } void Backtrace::getSourceInfo(unw_word_t proc_address UNUSED) { // TODO: extract filename and line number for symbol at given address m_fileName = "??"; m_functionName = "??"; m_lineNumber = 0; } const std::string Backtrace::buildBacktrace(void) { std::ostringstream backtrace; unw_cursor_t cursor; unw_context_t uc; unw_word_t ip, sp; char proc_name[BUFSIZ]; unw_word_t offp; int status; unw_getcontext(&uc); // get rid of previous function: Backtrace::getBacktrace unw_init_local(&cursor, &uc); unw_step(&cursor); while (unw_step(&cursor) > 0) { unw_get_reg(&cursor, UNW_REG_IP, &ip); unw_get_reg(&cursor, UNW_REG_SP, &sp); unw_get_proc_name(&cursor, proc_name, sizeof(proc_name), &offp); char *realname = abi::__cxa_demangle(proc_name, 0, 0, &status); getSourceInfo(ip); backtrace << std::hex << "ip = 0x" << ip << ", sp = 0x" << sp << ", " << (realname ? realname : proc_name) << ", " << m_fileName << ":" << std::dec << m_lineNumber << std::endl; free(realname); } return backtrace.str(); } const std::string Backtrace::getBacktrace(void) { return getInstance().buildBacktrace(); } } /* namespace Cynara */ <|endoftext|>
<commit_before>#include "contractresult.h" #include "ui_contractresult.h" #include "guiconstants.h" #include "contractabi.h" #include <QMessageBox> ContractResult::ContractResult(QWidget *parent) : QStackedWidget(parent), ui(new Ui::ContractResult) { ui->setupUi(this); ui->groupBoxCallContract->setStyleSheet(STYLE_GROUPBOX); ui->groupBoxResult->setStyleSheet(STYLE_GROUPBOX); ui->groupBoxCreateOrSendTo->setStyleSheet(STYLE_GROUPBOX); ui->scrollAreaParams->setStyleSheet(".QScrollArea { border: none;}"); ui->scrollAreaResult->setStyleSheet(".QScrollArea { border: none;}"); } ContractResult::~ContractResult() { delete ui; } void ContractResult::setResultData(QVariant result, FunctionABI function, QList<QStringList> paramValues, ContractTxType type) { switch (type) { case CreateResult: updateCreateResult(result); setCurrentWidget(ui->pageCreateOrSendToResult); break; case SendToResult: updateSendToResult(result); setCurrentWidget(ui->pageCreateOrSendToResult); break; case CallResult: updateCallResult(result, function, paramValues); setCurrentWidget(ui->pageCallResult); break; default: break; } } void ContractResult::setParamsData(FunctionABI function, QList<QStringList> paramValues) { // Remove previous widget from scroll area QWidget *scrollWidget = ui->scrollAreaParams->widget(); if(scrollWidget) scrollWidget->deleteLater(); // Don't show empty list if(function.inputs.size() == 0) { ui->scrollAreaParams->setVisible(false); return; } QWidget *widgetParams = new QWidget(this); QVBoxLayout *mainLayout = new QVBoxLayout(widgetParams); mainLayout->setSpacing(6); mainLayout->setContentsMargins(0,0,30,0); // Add rows with params and values sent int i = 0; for(std::vector<ParameterABI>::const_iterator param = function.inputs.begin(); param != function.inputs.end(); ++param) { QHBoxLayout *hLayout = new QHBoxLayout(widgetParams); hLayout->setSpacing(10); hLayout->setContentsMargins(0,0,0,0); QVBoxLayout *vNameLayout = new QVBoxLayout(widgetParams); vNameLayout->setSpacing(3); vNameLayout->setContentsMargins(0,0,0,0); QVBoxLayout *paramValuesLayout = new QVBoxLayout(widgetParams); paramValuesLayout->setSpacing(3); paramValuesLayout->setContentsMargins(0,0,0,0); QLabel *paramName = new QLabel(this); paramName->setFixedWidth(160); paramName->setFixedHeight(19); QFontMetrics metrix(paramName->font()); int width = paramName->width() + 10; QString text(QString("%2 <b>%1").arg(QString::fromStdString(param->name)).arg(QString::fromStdString(param->type))); QString clippedText = metrix.elidedText(text, Qt::ElideRight, width); paramName->setText(clippedText); paramName->setToolTip(QString("%2 %1").arg(QString::fromStdString(param->name)).arg(QString::fromStdString(param->type))); vNameLayout->addWidget(paramName); QStringList listValues = paramValues[i]; int spacerSize = 0; for(int j = 0; j < listValues.count(); j++) { QLineEdit *paramValue = new QLineEdit(this); paramValue->setReadOnly(true); paramValue->setText(listValues[j]); paramValuesLayout->addWidget(paramValue); if(j > 0) spacerSize += 22; // Line edit height + spacing } if(spacerSize > 0) vNameLayout->addSpacerItem(new QSpacerItem(20, spacerSize, QSizePolicy::Fixed, QSizePolicy::Fixed)); hLayout->addLayout(vNameLayout); hLayout->addLayout(paramValuesLayout); mainLayout->addLayout(hLayout); i++; } widgetParams->setLayout(mainLayout); widgetParams->adjustSize(); if(widgetParams->sizeHint().height() < 70) ui->scrollAreaParams->setMaximumHeight(widgetParams->sizeHint().height() + 2); else ui->scrollAreaParams->setMaximumHeight(140); ui->scrollAreaParams->setWidget(widgetParams); ui->scrollAreaParams->setVisible(true); } void ContractResult::updateCreateResult(QVariant result) { ui->lineEditContractAddress->setVisible(true); ui->labelContractAddress->setVisible(true); QVariantMap variantMap = result.toMap(); ui->lineEditTxID->setText(variantMap.value("txid").toString()); ui->lineEditSenderAddress->setText(variantMap.value("sender").toString()); ui->lineEditHash160->setText(variantMap.value("hash160").toString()); ui->lineEditContractAddress->setText(variantMap.value("address").toString()); } void ContractResult::updateSendToResult(QVariant result) { ui->lineEditContractAddress->setVisible(false); ui->labelContractAddress->setVisible(false); QVariantMap variantMap = result.toMap(); ui->lineEditTxID->setText(variantMap.value("txid").toString()); ui->lineEditSenderAddress->setText(variantMap.value("sender").toString()); ui->lineEditHash160->setText(variantMap.value("hash160").toString()); } void ContractResult::updateCallResult(QVariant result, FunctionABI function, QList<QStringList> paramValues) { QVariantMap variantMap = result.toMap(); QVariantMap executionResultMap = variantMap.value("executionResult").toMap(); ui->lineEditCallContractAddress->setText(variantMap.value("address").toString()); ui->lineEditFunction->setText(QString::fromStdString(function.name)); setParamsData(function, paramValues); ui->lineEditCallSenderAddress->setText(variantMap.value("sender").toString()); std::string rawData = executionResultMap.value("output").toString().toStdString(); std::vector<std::vector<std::string>> values; std::vector<ParameterABI::ErrorType> errors; if(function.abiOut(rawData, values, errors)) { // Remove previous widget from scroll area QWidget *scrollWidget = ui->scrollAreaResult->widget(); if(scrollWidget) scrollWidget->deleteLater(); if(values.size() > 0) { QWidget *widgetResults = new QWidget(this); QVBoxLayout *mainLayout = new QVBoxLayout(widgetResults); mainLayout->setSpacing(6); mainLayout->setContentsMargins(0,6,0,6); widgetResults->setLayout(mainLayout); for(size_t i = 0; i < values.size(); i++) { QHBoxLayout *hLayout = new QHBoxLayout(widgetResults); hLayout->setSpacing(10); hLayout->setContentsMargins(0,0,0,0); QVBoxLayout *vNameLayout = new QVBoxLayout(widgetResults); vNameLayout->setSpacing(3); vNameLayout->setContentsMargins(0,0,0,0); QVBoxLayout *paramValuesLayout = new QVBoxLayout(widgetResults); paramValuesLayout->setSpacing(3); paramValuesLayout->setContentsMargins(0,0,0,0); QLabel *resultName = new QLabel(this); resultName->setFixedWidth(160); resultName->setFixedHeight(19); QFontMetrics metrix(resultName->font()); int width = resultName->width() + 10; QString text(QString("%2 <b>%1").arg(QString::fromStdString(function.outputs[i].name)).arg(QString::fromStdString(function.outputs[i].type))); QString clippedText = metrix.elidedText(text, Qt::ElideRight, width); resultName->setText(clippedText); resultName->setToolTip(QString("%2 %1").arg(QString::fromStdString(function.outputs[i].name)).arg(QString::fromStdString(function.outputs[i].type))); vNameLayout->addWidget(resultName); std::vector<std::string> listValues = values[i]; int spacerSize = 0; for(size_t j = 0; j < listValues.size(); j++) { QLineEdit *resultValue = new QLineEdit(this); resultValue->setReadOnly(true); resultValue->setText(QString::fromStdString(listValues[j])); paramValuesLayout->addWidget(resultValue); if(j > 0) spacerSize += 22; // Line edit height + spacing } if(spacerSize > 0) vNameLayout->addSpacerItem(new QSpacerItem(20, spacerSize, QSizePolicy::Fixed, QSizePolicy::Fixed)); hLayout->addLayout(vNameLayout); hLayout->addLayout(paramValuesLayout); mainLayout->addLayout(hLayout); } widgetResults->adjustSize(); if(widgetResults->sizeHint().height() < 70) { ui->scrollAreaResult->setMaximumHeight(widgetResults->sizeHint().height() + 2); } else { ui->scrollAreaResult->setMaximumHeight(140); } ui->scrollAreaResult->setWidget(widgetResults); ui->groupBoxResult->setVisible(true); } else { ui->groupBoxResult->setVisible(false); } } else { QString errorMessage; errorMessage = function.errorMessage(errors, false); QMessageBox::warning(this, tr("Create contract"), errorMessage); } } <commit_msg>Update alignment for empty list result<commit_after>#include "contractresult.h" #include "ui_contractresult.h" #include "guiconstants.h" #include "contractabi.h" #include <QMessageBox> ContractResult::ContractResult(QWidget *parent) : QStackedWidget(parent), ui(new Ui::ContractResult) { ui->setupUi(this); ui->groupBoxCallContract->setStyleSheet(STYLE_GROUPBOX); ui->groupBoxResult->setStyleSheet(STYLE_GROUPBOX); ui->groupBoxCreateOrSendTo->setStyleSheet(STYLE_GROUPBOX); ui->scrollAreaParams->setStyleSheet(".QScrollArea { border: none;}"); ui->scrollAreaResult->setStyleSheet(".QScrollArea { border: none;}"); } ContractResult::~ContractResult() { delete ui; } void ContractResult::setResultData(QVariant result, FunctionABI function, QList<QStringList> paramValues, ContractTxType type) { switch (type) { case CreateResult: updateCreateResult(result); setCurrentWidget(ui->pageCreateOrSendToResult); break; case SendToResult: updateSendToResult(result); setCurrentWidget(ui->pageCreateOrSendToResult); break; case CallResult: updateCallResult(result, function, paramValues); setCurrentWidget(ui->pageCallResult); break; default: break; } } void ContractResult::setParamsData(FunctionABI function, QList<QStringList> paramValues) { // Remove previous widget from scroll area QWidget *scrollWidget = ui->scrollAreaParams->widget(); if(scrollWidget) scrollWidget->deleteLater(); // Don't show empty list if(function.inputs.size() == 0) { ui->scrollAreaParams->setVisible(false); return; } QWidget *widgetParams = new QWidget(this); QVBoxLayout *mainLayout = new QVBoxLayout(widgetParams); mainLayout->setSpacing(6); mainLayout->setContentsMargins(0,0,30,0); // Add rows with params and values sent int i = 0; for(std::vector<ParameterABI>::const_iterator param = function.inputs.begin(); param != function.inputs.end(); ++param) { QHBoxLayout *hLayout = new QHBoxLayout(widgetParams); hLayout->setSpacing(10); hLayout->setContentsMargins(0,0,0,0); QVBoxLayout *vNameLayout = new QVBoxLayout(widgetParams); vNameLayout->setSpacing(3); vNameLayout->setContentsMargins(0,0,0,0); QVBoxLayout *paramValuesLayout = new QVBoxLayout(widgetParams); paramValuesLayout->setSpacing(3); paramValuesLayout->setContentsMargins(0,0,0,0); QLabel *paramName = new QLabel(this); paramName->setFixedWidth(160); paramName->setFixedHeight(19); QFontMetrics metrix(paramName->font()); int width = paramName->width() + 10; QString text(QString("%2 <b>%1").arg(QString::fromStdString(param->name)).arg(QString::fromStdString(param->type))); QString clippedText = metrix.elidedText(text, Qt::ElideRight, width); paramName->setText(clippedText); paramName->setToolTip(QString("%2 %1").arg(QString::fromStdString(param->name)).arg(QString::fromStdString(param->type))); vNameLayout->addWidget(paramName); QStringList listValues = paramValues[i]; int spacerSize = 0; for(int j = 0; j < listValues.count(); j++) { QLineEdit *paramValue = new QLineEdit(this); paramValue->setReadOnly(true); paramValue->setText(listValues[j]); paramValuesLayout->addWidget(paramValue); if(j > 0) spacerSize += 22; // Line edit height + spacing } if(spacerSize > 0) vNameLayout->addSpacerItem(new QSpacerItem(20, spacerSize, QSizePolicy::Fixed, QSizePolicy::Fixed)); hLayout->addLayout(vNameLayout); hLayout->addLayout(paramValuesLayout); mainLayout->addLayout(hLayout); i++; } widgetParams->setLayout(mainLayout); widgetParams->adjustSize(); if(widgetParams->sizeHint().height() < 70) ui->scrollAreaParams->setMaximumHeight(widgetParams->sizeHint().height() + 2); else ui->scrollAreaParams->setMaximumHeight(140); ui->scrollAreaParams->setWidget(widgetParams); ui->scrollAreaParams->setVisible(true); } void ContractResult::updateCreateResult(QVariant result) { ui->lineEditContractAddress->setVisible(true); ui->labelContractAddress->setVisible(true); QVariantMap variantMap = result.toMap(); ui->lineEditTxID->setText(variantMap.value("txid").toString()); ui->lineEditSenderAddress->setText(variantMap.value("sender").toString()); ui->lineEditHash160->setText(variantMap.value("hash160").toString()); ui->lineEditContractAddress->setText(variantMap.value("address").toString()); } void ContractResult::updateSendToResult(QVariant result) { ui->lineEditContractAddress->setVisible(false); ui->labelContractAddress->setVisible(false); QVariantMap variantMap = result.toMap(); ui->lineEditTxID->setText(variantMap.value("txid").toString()); ui->lineEditSenderAddress->setText(variantMap.value("sender").toString()); ui->lineEditHash160->setText(variantMap.value("hash160").toString()); } void ContractResult::updateCallResult(QVariant result, FunctionABI function, QList<QStringList> paramValues) { QVariantMap variantMap = result.toMap(); QVariantMap executionResultMap = variantMap.value("executionResult").toMap(); ui->lineEditCallContractAddress->setText(variantMap.value("address").toString()); ui->lineEditFunction->setText(QString::fromStdString(function.name)); setParamsData(function, paramValues); ui->lineEditCallSenderAddress->setText(variantMap.value("sender").toString()); std::string rawData = executionResultMap.value("output").toString().toStdString(); std::vector<std::vector<std::string>> values; std::vector<ParameterABI::ErrorType> errors; if(function.abiOut(rawData, values, errors)) { // Remove previous widget from scroll area QWidget *scrollWidget = ui->scrollAreaResult->widget(); if(scrollWidget) scrollWidget->deleteLater(); if(values.size() > 0) { QWidget *widgetResults = new QWidget(this); QVBoxLayout *mainLayout = new QVBoxLayout(widgetResults); mainLayout->setSpacing(6); mainLayout->setContentsMargins(0,6,0,6); widgetResults->setLayout(mainLayout); for(size_t i = 0; i < values.size(); i++) { QHBoxLayout *hLayout = new QHBoxLayout(widgetResults); hLayout->setSpacing(10); hLayout->setContentsMargins(0,0,0,0); QVBoxLayout *vNameLayout = new QVBoxLayout(widgetResults); vNameLayout->setSpacing(3); vNameLayout->setContentsMargins(0,0,0,0); QVBoxLayout *paramValuesLayout = new QVBoxLayout(widgetResults); paramValuesLayout->setSpacing(3); paramValuesLayout->setContentsMargins(0,0,0,0); QLabel *resultName = new QLabel(this); resultName->setFixedWidth(160); resultName->setFixedHeight(19); QFontMetrics metrix(resultName->font()); int width = resultName->width() + 10; QString text(QString("%2 <b>%1").arg(QString::fromStdString(function.outputs[i].name)).arg(QString::fromStdString(function.outputs[i].type))); QString clippedText = metrix.elidedText(text, Qt::ElideRight, width); resultName->setText(clippedText); resultName->setToolTip(QString("%2 %1").arg(QString::fromStdString(function.outputs[i].name)).arg(QString::fromStdString(function.outputs[i].type))); vNameLayout->addWidget(resultName); std::vector<std::string> listValues = values[i]; hLayout->addLayout(vNameLayout); if(listValues.size() > 0) { int spacerSize = 0; for(size_t j = 0; j < listValues.size(); j++) { QLineEdit *resultValue = new QLineEdit(this); resultValue->setReadOnly(true); resultValue->setText(QString::fromStdString(listValues[j])); paramValuesLayout->addWidget(resultValue); if(j > 0) spacerSize += 22; // Line edit height + spacing } if(spacerSize > 0) vNameLayout->addSpacerItem(new QSpacerItem(20, spacerSize, QSizePolicy::Fixed, QSizePolicy::Fixed)); hLayout->addLayout(paramValuesLayout); } else { hLayout->addSpacerItem(new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Fixed)); } mainLayout->addLayout(hLayout); } widgetResults->adjustSize(); if(widgetResults->sizeHint().height() < 70) { ui->scrollAreaResult->setMaximumHeight(widgetResults->sizeHint().height() + 2); } else { ui->scrollAreaResult->setMaximumHeight(140); } ui->scrollAreaResult->setWidget(widgetResults); ui->groupBoxResult->setVisible(true); } else { ui->groupBoxResult->setVisible(false); } } else { QString errorMessage; errorMessage = function.errorMessage(errors, false); QMessageBox::warning(this, tr("Create contract"), errorMessage); } } <|endoftext|>
<commit_before>#include <mfapi.h> //#include <mfobjects.h> #include <mfidl.h> #include <mferror.h> #include "webmmfbytestreamhandler.hpp" #include "webmmfsource.hpp" #include <new> #include <cassert> #ifdef _DEBUG #include "odbgstream.hpp" using std::endl; #endif _COM_SMARTPTR_TYPEDEF(IMFMediaSource, __uuidof(IMFMediaSource)); namespace WebmMfSourceLib { HRESULT CreateHandler( IClassFactory* pClassFactory, IUnknown* pOuter, const IID& iid, void** ppv) { if (ppv == 0) return E_POINTER; *ppv = 0; if (pOuter) return CLASS_E_NOAGGREGATION; typedef WebmMfByteStreamHandler H; H* const p = new (std::nothrow) H(pClassFactory); if (p == 0) return E_OUTOFMEMORY; IUnknown* const pUnk = p; const HRESULT hr = pUnk->QueryInterface(iid, ppv); const ULONG cRef = pUnk->Release(); cRef; return hr; } #pragma warning(disable:4355) //'this' ptr in member init list WebmMfByteStreamHandler::WebmMfByteStreamHandler( IClassFactory* pClassFactory) : m_pClassFactory(pClassFactory), m_cRef(1), m_bCancel(FALSE), m_async_load(this) { #ifdef _DEBUG wodbgstream os; os << L"WebmMfByteStreamHandler: ctor: this=0x" << (const void*)this << endl; #endif HRESULT hr = m_pClassFactory->LockServer(TRUE); assert(SUCCEEDED(hr)); hr = CLockable::Init(); assert(SUCCEEDED(hr)); } #pragma warning(default:4355) WebmMfByteStreamHandler::~WebmMfByteStreamHandler() { #ifdef _DEBUG wodbgstream os; os << L"WebmMfByteStreamHandler: dtor; this=0x" << (const void*)this << endl; #endif const HRESULT hr = m_pClassFactory->LockServer(FALSE); assert(SUCCEEDED(hr)); } HRESULT WebmMfByteStreamHandler::QueryInterface( const IID& iid, void** ppv) { if (ppv == 0) return E_POINTER; IUnknown*& pUnk = reinterpret_cast<IUnknown*&>(*ppv); if (iid == __uuidof(IUnknown)) { pUnk = this; //must be nondelegating } else if (iid == __uuidof(IMFByteStreamHandler)) { pUnk = static_cast<IMFByteStreamHandler*>(this); } else { pUnk = 0; return E_NOINTERFACE; } pUnk->AddRef(); return S_OK; } ULONG WebmMfByteStreamHandler::AddRef() { const ULONG n = InterlockedIncrement(&m_cRef); #if 0 //def _DEBUG odbgstream os; os << "WebmMfByteStreamHandler::AddRef: n=" << n << endl; #endif return n; } ULONG WebmMfByteStreamHandler::Release() { const LONG n = InterlockedDecrement(&m_cRef); #if 0 //def _DEBUG odbgstream os; os << "WebmMfByteStreamHandler::Release: n=" << n << endl; #endif if (n == 0) delete this; return n; } HRESULT WebmMfByteStreamHandler::BeginCreateObject( IMFByteStream* pByteStream, LPCWSTR pURL, DWORD dwFlags, IPropertyStore*, IUnknown** ppCancelCookie, IMFAsyncCallback* pCallback, IUnknown* pState) { pURL; //? #ifdef _DEBUG wodbgstream os; os << L"WebmMfByteStreamHandler::BeginCreateObject: url=" << (pURL ? pURL : L"<NONE>") << endl; #endif Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; if (ppCancelCookie) *ppCancelCookie = 0; if (pByteStream == 0) return E_INVALIDARG; if (pCallback == 0) return E_INVALIDARG; if ((dwFlags & MF_RESOLUTION_MEDIASOURCE) == 0) return E_INVALIDARG; if (m_pResult) //assume one-at-a-time creation return MF_E_UNEXPECTED; DWORD dw; hr = pByteStream->GetCapabilities(&dw); if (SUCCEEDED(hr)) { #ifdef _DEBUG odbgstream os; os << "webmmfsource::BeginCreateObject: caps:"; if (dw & MFBYTESTREAM_IS_READABLE) os << " READABLE"; if (dw & MFBYTESTREAM_IS_WRITABLE) os << " WRITABLE"; if (dw & MFBYTESTREAM_IS_SEEKABLE) os << " SEEKABLE"; if (dw & MFBYTESTREAM_IS_REMOTE) os << " REMOTE"; if (dw & MFBYTESTREAM_IS_DIRECTORY) os << " DIRECTORY"; if (dw & MFBYTESTREAM_HAS_SLOW_SEEK) os << " SLOW_SEEK"; if (dw & MFBYTESTREAM_IS_PARTIALLY_DOWNLOADED) os << " PARTIALLY_DOWNLOADED"; if (dw & MFBYTESTREAM_SHARE_WRITE) os << " SHARE_WRITE"; os << endl; #endif __noop; //TODO: vet capabilities } WebmMfSource* pSource; hr = WebmMfSource::CreateSource(m_pClassFactory, pByteStream, pSource); if (FAILED(hr)) return hr; const IMFMediaSourcePtr pUnk(pSource, false); IMFAsyncResultPtr pResult; hr = MFCreateAsyncResult(pUnk, pCallback, pState, &pResult); if (FAILED(hr)) return hr; hr = pSource->BeginLoad(&m_async_load); if (FAILED(hr)) return hr; m_pResult = pResult; m_bCancel = FALSE; m_pByteStream = pByteStream; return S_OK; } HRESULT WebmMfByteStreamHandler::EndCreateObject( IMFAsyncResult* pResult, MF_OBJECT_TYPE* pObjectType, IUnknown** ppObject) { Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; #ifdef _DEBUG wodbgstream os; os << L"WebmMfByteStreamHandler::EndCreateObject (begin)" << endl; #endif if (ppObject == 0) return E_POINTER; IUnknown*& pObject = *ppObject; pObject = 0; if (pObjectType == 0) return E_POINTER; MF_OBJECT_TYPE& type = *pObjectType; type = MF_OBJECT_INVALID; if (pResult == 0) return E_INVALIDARG; hr = pResult->GetStatus(); if (FAILED(hr)) //for example, cancelled return hr; IUnknownPtr pUnk; hr = pResult->GetObject(&pUnk); if (FAILED(hr)) //shouldn't happen return hr; assert(pUnk); hr = pUnk->QueryInterface(__uuidof(IMFMediaSource), (void**)&pObject); if (FAILED(hr)) return hr; type = MF_OBJECT_MEDIASOURCE; #ifdef _DEBUG os << L"WebmMfByteStreamHandler::EndCreateObject (end)" << endl; #endif return S_OK; } HRESULT WebmMfByteStreamHandler::CancelObjectCreation(IUnknown*) { #ifdef _DEBUG wodbgstream os; os << L"WebmMfByteStreamHandler::CancelObjectCreation" << endl; #endif Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; if (m_bCancel) return S_OK; if (!m_pByteStream) return S_OK; m_bCancel = TRUE; return m_pByteStream->Close(); } HRESULT WebmMfByteStreamHandler::GetMaxNumberOfBytesRequiredForResolution( QWORD* pcb) { if (pcb == 0) return E_POINTER; *pcb = 1024; //TODO: ask the webm parser for this value return S_OK; } WebmMfByteStreamHandler::CAsyncLoad::CAsyncLoad( WebmMfByteStreamHandler* p) : m_pHandler(p) { } WebmMfByteStreamHandler::CAsyncLoad::~CAsyncLoad() { } HRESULT WebmMfByteStreamHandler::CAsyncLoad::QueryInterface( const IID& iid, void** ppv) { if (ppv == 0) return E_POINTER; IUnknown*& pUnk = reinterpret_cast<IUnknown*&>(*ppv); if (iid == __uuidof(IUnknown)) { pUnk = static_cast<IMFAsyncCallback*>(this); //must be nondelegating } else if (iid == __uuidof(IMFAsyncCallback)) { pUnk = static_cast<IMFAsyncCallback*>(this); } else { pUnk = 0; return E_NOINTERFACE; } pUnk->AddRef(); return S_OK; } ULONG WebmMfByteStreamHandler::CAsyncLoad::AddRef() { return m_pHandler->AddRef(); } ULONG WebmMfByteStreamHandler::CAsyncLoad::Release() { return m_pHandler->Release(); } HRESULT WebmMfByteStreamHandler::CAsyncLoad::GetParameters( DWORD*, DWORD*) { return E_NOTIMPL; //means "assume default behavior" } HRESULT WebmMfByteStreamHandler::CAsyncLoad::Invoke(IMFAsyncResult* pResult) { if (pResult == 0) return E_INVALIDARG; Lock lock; HRESULT hr = lock.Seize(m_pHandler); if (FAILED(hr)) return hr; return m_pHandler->EndLoad(pResult); } HRESULT WebmMfByteStreamHandler::EndLoad(IMFAsyncResult* pLoadResult) { if (!m_pResult) //should never happen return MF_E_UNEXPECTED; HRESULT hrLoad; if (m_bCancel) hrLoad = MF_E_OPERATION_CANCELLED; else hrLoad = pLoadResult->GetStatus(); HRESULT hr = m_pResult->SetStatus(hrLoad); assert(SUCCEEDED(hr)); if (FAILED(hrLoad)) { IUnknownPtr pUnk; hr = m_pResult->GetObject(&pUnk); if (SUCCEEDED(hr)) { const IMFMediaSourcePtr pSource(pUnk); assert(pSource); hr = pSource->Shutdown(); } } hr = MFInvokeCallback(m_pResult); m_pByteStream = 0; m_pResult = 0; return hr; } } //end namespace WebmMfSourceLib <commit_msg>webmmfsource: check byte stream length during creation<commit_after>#include <mfapi.h> //#include <mfobjects.h> #include <mfidl.h> #include <mferror.h> #include "webmmfbytestreamhandler.hpp" #include "webmmfsource.hpp" #include <new> #include <cassert> #ifdef _DEBUG #include "odbgstream.hpp" using std::endl; #endif _COM_SMARTPTR_TYPEDEF(IMFMediaSource, __uuidof(IMFMediaSource)); namespace WebmMfSourceLib { HRESULT CreateHandler( IClassFactory* pClassFactory, IUnknown* pOuter, const IID& iid, void** ppv) { if (ppv == 0) return E_POINTER; *ppv = 0; if (pOuter) return CLASS_E_NOAGGREGATION; typedef WebmMfByteStreamHandler H; H* const p = new (std::nothrow) H(pClassFactory); if (p == 0) return E_OUTOFMEMORY; IUnknown* const pUnk = p; const HRESULT hr = pUnk->QueryInterface(iid, ppv); const ULONG cRef = pUnk->Release(); cRef; return hr; } #pragma warning(disable:4355) //'this' ptr in member init list WebmMfByteStreamHandler::WebmMfByteStreamHandler( IClassFactory* pClassFactory) : m_pClassFactory(pClassFactory), m_cRef(1), m_bCancel(FALSE), m_async_load(this) { #ifdef _DEBUG wodbgstream os; os << L"WebmMfByteStreamHandler: ctor: this=0x" << (const void*)this << endl; #endif HRESULT hr = m_pClassFactory->LockServer(TRUE); assert(SUCCEEDED(hr)); hr = CLockable::Init(); assert(SUCCEEDED(hr)); } #pragma warning(default:4355) WebmMfByteStreamHandler::~WebmMfByteStreamHandler() { #ifdef _DEBUG wodbgstream os; os << L"WebmMfByteStreamHandler: dtor; this=0x" << (const void*)this << endl; #endif const HRESULT hr = m_pClassFactory->LockServer(FALSE); assert(SUCCEEDED(hr)); } HRESULT WebmMfByteStreamHandler::QueryInterface( const IID& iid, void** ppv) { if (ppv == 0) return E_POINTER; IUnknown*& pUnk = reinterpret_cast<IUnknown*&>(*ppv); if (iid == __uuidof(IUnknown)) { pUnk = this; //must be nondelegating } else if (iid == __uuidof(IMFByteStreamHandler)) { pUnk = static_cast<IMFByteStreamHandler*>(this); } else { pUnk = 0; return E_NOINTERFACE; } pUnk->AddRef(); return S_OK; } ULONG WebmMfByteStreamHandler::AddRef() { const ULONG n = InterlockedIncrement(&m_cRef); #if 0 //def _DEBUG odbgstream os; os << "WebmMfByteStreamHandler::AddRef: n=" << n << endl; #endif return n; } ULONG WebmMfByteStreamHandler::Release() { const LONG n = InterlockedDecrement(&m_cRef); #if 0 //def _DEBUG odbgstream os; os << "WebmMfByteStreamHandler::Release: n=" << n << endl; #endif if (n == 0) delete this; return n; } HRESULT WebmMfByteStreamHandler::BeginCreateObject( IMFByteStream* pByteStream, LPCWSTR pURL, DWORD dwFlags, IPropertyStore*, IUnknown** ppCancelCookie, IMFAsyncCallback* pCallback, IUnknown* pState) { pURL; //? #ifdef _DEBUG wodbgstream os; os << L"WebmMfByteStreamHandler::BeginCreateObject: url=" << (pURL ? pURL : L"<NONE>") << endl; #endif Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; if (ppCancelCookie) *ppCancelCookie = 0; if (pByteStream == 0) return E_INVALIDARG; if (pCallback == 0) return E_INVALIDARG; if ((dwFlags & MF_RESOLUTION_MEDIASOURCE) == 0) return E_INVALIDARG; if (m_pResult) //assume one-at-a-time creation return MF_E_UNEXPECTED; DWORD dw; hr = pByteStream->GetCapabilities(&dw); if (SUCCEEDED(hr)) { #ifdef _DEBUG odbgstream os; os << "webmmfsource::BeginCreateObject: caps:"; if (dw & MFBYTESTREAM_IS_READABLE) os << " READABLE"; if (dw & MFBYTESTREAM_IS_WRITABLE) os << " WRITABLE"; if (dw & MFBYTESTREAM_IS_SEEKABLE) os << " SEEKABLE"; if (dw & MFBYTESTREAM_IS_REMOTE) os << " REMOTE"; if (dw & MFBYTESTREAM_IS_DIRECTORY) os << " DIRECTORY"; if (dw & MFBYTESTREAM_HAS_SLOW_SEEK) os << " SLOW_SEEK"; if (dw & MFBYTESTREAM_IS_PARTIALLY_DOWNLOADED) os << " PARTIALLY_DOWNLOADED"; if (dw & MFBYTESTREAM_SHARE_WRITE) os << " SHARE_WRITE"; os << endl; #endif if (!(dw & MFBYTESTREAM_IS_READABLE)) return E_FAIL; if (!(dw & MFBYTESTREAM_IS_SEEKABLE)) return MF_E_BYTESTREAM_NOT_SEEKABLE; } QWORD length; hr = pByteStream->GetLength(&length); if (FAILED(hr)) //MF_E_BYTESTREAM_UNKNOWN_LENGTH return hr; if (length == 0) return MF_E_INVALID_FILE_FORMAT; //TODO: use this elsewhere WebmMfSource* pSource; hr = WebmMfSource::CreateSource(m_pClassFactory, pByteStream, pSource); if (FAILED(hr)) return hr; const IMFMediaSourcePtr pUnk(pSource, false); IMFAsyncResultPtr pResult; hr = MFCreateAsyncResult(pUnk, pCallback, pState, &pResult); if (FAILED(hr)) return hr; hr = pSource->BeginLoad(&m_async_load); if (FAILED(hr)) return hr; m_pResult = pResult; m_bCancel = FALSE; m_pByteStream = pByteStream; return S_OK; } HRESULT WebmMfByteStreamHandler::EndCreateObject( IMFAsyncResult* pResult, MF_OBJECT_TYPE* pObjectType, IUnknown** ppObject) { Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; #ifdef _DEBUG wodbgstream os; os << L"WebmMfByteStreamHandler::EndCreateObject (begin)" << endl; #endif if (ppObject == 0) return E_POINTER; IUnknown*& pObject = *ppObject; pObject = 0; if (pObjectType == 0) return E_POINTER; MF_OBJECT_TYPE& type = *pObjectType; type = MF_OBJECT_INVALID; if (pResult == 0) return E_INVALIDARG; hr = pResult->GetStatus(); if (FAILED(hr)) //for example, cancelled return hr; IUnknownPtr pUnk; hr = pResult->GetObject(&pUnk); if (FAILED(hr)) //shouldn't happen return hr; assert(pUnk); hr = pUnk->QueryInterface(__uuidof(IMFMediaSource), (void**)&pObject); if (FAILED(hr)) return hr; type = MF_OBJECT_MEDIASOURCE; #ifdef _DEBUG os << L"WebmMfByteStreamHandler::EndCreateObject (end)" << endl; #endif return S_OK; } HRESULT WebmMfByteStreamHandler::CancelObjectCreation(IUnknown*) { #ifdef _DEBUG wodbgstream os; os << L"WebmMfByteStreamHandler::CancelObjectCreation" << endl; #endif Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; if (m_bCancel) return S_OK; if (!m_pByteStream) return S_OK; m_bCancel = TRUE; return m_pByteStream->Close(); } HRESULT WebmMfByteStreamHandler::GetMaxNumberOfBytesRequiredForResolution( QWORD* pcb) { if (pcb == 0) return E_POINTER; *pcb = 1024; //TODO: ask the webm parser for this value return S_OK; } WebmMfByteStreamHandler::CAsyncLoad::CAsyncLoad( WebmMfByteStreamHandler* p) : m_pHandler(p) { } WebmMfByteStreamHandler::CAsyncLoad::~CAsyncLoad() { } HRESULT WebmMfByteStreamHandler::CAsyncLoad::QueryInterface( const IID& iid, void** ppv) { if (ppv == 0) return E_POINTER; IUnknown*& pUnk = reinterpret_cast<IUnknown*&>(*ppv); if (iid == __uuidof(IUnknown)) { pUnk = static_cast<IMFAsyncCallback*>(this); //must be nondelegating } else if (iid == __uuidof(IMFAsyncCallback)) { pUnk = static_cast<IMFAsyncCallback*>(this); } else { pUnk = 0; return E_NOINTERFACE; } pUnk->AddRef(); return S_OK; } ULONG WebmMfByteStreamHandler::CAsyncLoad::AddRef() { return m_pHandler->AddRef(); } ULONG WebmMfByteStreamHandler::CAsyncLoad::Release() { return m_pHandler->Release(); } HRESULT WebmMfByteStreamHandler::CAsyncLoad::GetParameters( DWORD*, DWORD*) { return E_NOTIMPL; //means "assume default behavior" } HRESULT WebmMfByteStreamHandler::CAsyncLoad::Invoke(IMFAsyncResult* pResult) { if (pResult == 0) return E_INVALIDARG; Lock lock; HRESULT hr = lock.Seize(m_pHandler); if (FAILED(hr)) return hr; return m_pHandler->EndLoad(pResult); } HRESULT WebmMfByteStreamHandler::EndLoad(IMFAsyncResult* pLoadResult) { if (!m_pResult) //should never happen return MF_E_UNEXPECTED; HRESULT hrLoad; if (m_bCancel) hrLoad = MF_E_OPERATION_CANCELLED; else hrLoad = pLoadResult->GetStatus(); HRESULT hr = m_pResult->SetStatus(hrLoad); assert(SUCCEEDED(hr)); if (FAILED(hrLoad)) { IUnknownPtr pUnk; hr = m_pResult->GetObject(&pUnk); if (SUCCEEDED(hr)) { const IMFMediaSourcePtr pSource(pUnk); assert(pSource); hr = pSource->Shutdown(); } } hr = MFInvokeCallback(m_pResult); m_pByteStream = 0; m_pResult = 0; return hr; } } //end namespace WebmMfSourceLib <|endoftext|>
<commit_before><commit_msg>Pull in r182656 from upstream llvm trunk:<commit_after><|endoftext|>
<commit_before>/* This file implements the classes defined in Match.h: Match, Capability, and Client A Match object contains all of the information a startd needs about a given match, such as the capability, the client of this match, etc. The capability in the match is just a pointer to a Capability object. The client is also just a pointer to a Client object. The startd maintains two Match objects in the "rip", the per-resource information structure. One for the current match, and one for the possibly preempting match that is pending. A Capability object contains the capability string, and some functions to manipulate and compare against this string. The constructor generates a new capability with the following form: <ip:port>#random_integer A Client object contains all the info about a given client of a startd. In particular, the client name (a.k.a. "user"), the address ("<www.xxx.yyy.zzz:pppp>" formed ip/port), and the hostname. Written 9/29/97 by Derek Wright <[email protected]> */ #include "startd.h" static char *_FileName_ = __FILE__; /////////////////////////////////////////////////////////////////////////// // Match /////////////////////////////////////////////////////////////////////////// Match::Match() { m_client = new Client; m_cap = new Capability; m_ad = NULL; m_rank = -1; m_oldrank = -1; m_universe = -1; m_agentstream = NULL; m_match_tid = -1; m_claim_tid = -1; m_aliveint = -1; m_cluster = -1; m_proc = -1; m_job_start = -1; m_last_pckpt = -1; } Match::~Match() { // Cancel any timers associated with this match this->cancel_match_timer(); this->cancel_claim_timer(); // Free up memory that's been allocated if( m_ad ) { delete( m_ad ); } delete( m_cap ); if( m_client ) { delete( m_client ); } if( m_agentstream ) { delete( m_agentstream ); } } void Match::vacate() { assert( m_cap ); // warn the client of this match that it's being vacated if( m_client && m_client->addr() ) { m_client->vacate( m_cap->capab() ); } } int Match::send_accountant( int cmd ) { if( !accountant_host ) { return FALSE; } ReliSock sock; sock.timeout( 30 ); if( ! sock.connect( accountant_host, ACCOUNTANT_PORT ) ) { dprintf(D_ALWAYS, "Couldn't connect to accountant\n"); return FALSE; } if( !sock.put( cmd ) ) { dprintf(D_ALWAYS, "Can't send command (%d) to accountant\n", cmd ); return FALSE; } if( !sock.put( m_cap->capab() ) ) { dprintf(D_ALWAYS, "Can't send capability to accountant\n"); return FALSE; } if( !sock.eom() ) { dprintf(D_ALWAYS, "Can't send EOM to accountant\n"); return FALSE; } sock.close(); return TRUE; } void Match::update( ClassAd* ad ) { char line[256]; char* tmp; sprintf( line, "%s = %f", ATTR_CURRENT_RANK, m_rank ); ad->Insert( line ); if( m_client ) { tmp = m_client->name(); if( tmp ) { sprintf( line, "%s=\"%s\"", ATTR_REMOTE_USER, tmp ); ad->Insert( line ); } tmp = m_client->host(); if( tmp ) { sprintf( line, "%s=\"%s\"", ATTR_CLIENT_MACHINE, tmp ); ad->Insert( line ); } } if( (m_cluster > 0) && (m_proc >= 0) ) { sprintf( line, "%s=\"%d.%d\"", ATTR_JOB_ID, m_cluster, m_proc ); ad->Insert( line ); } if( m_job_start > 0 ) { sprintf(line, "%s=%d", ATTR_JOB_START, m_job_start ); ad->Insert( line ); } if( m_last_pckpt > 0 ) { sprintf(line, "%s=%d", ATTR_LAST_PERIODIC_CHECKPOINT, m_last_pckpt ); ad->Insert( line ); } if( m_universe > 0 ) { sprintf( line, "%s=%d", ATTR_JOB_UNIVERSE, m_universe ); ad->Insert( line ); } } void Match::refuse_agent() { if( !m_agentstream ) return; dprintf( D_ALWAYS, "Refusing request from schedd agent.\n" ); m_agentstream->encode(); m_agentstream->put(NOT_OK); m_agentstream->end_of_message(); } void Match::start_match_timer() { m_match_tid = daemonCore->Register_Timer( match_timeout, 0, (TimerHandlercpp)match_timed_out, "match_timed_out", this ); if( m_match_tid == -1 ) { EXCEPT( "Couldn't register timer (out of memory)." ); } dprintf( D_FULLDEBUG, "Started match timer for %d seconds.\n", match_timeout ); } void Match::cancel_match_timer() { if( m_match_tid != -1 ) { daemonCore->Cancel_Timer( m_match_tid ); m_match_tid = -1; dprintf( D_FULLDEBUG, "Canceled match timer.\n" ); } } int Match::match_timed_out() { Resource* rip = resmgr->get_by_any_cap( capab() ); if( !rip ) { EXCEPT( "Can't find resource of expired match." ); } if( rip->r_cur->cap()->matches( capab() ) ) { if( rip->state() != matched_state ) { EXCEPT( "Match timed out but not in matched state." ); } delete rip->r_cur; rip->r_cur = new Match; rip->change_state( owner_state ); } else { // The match that timed out was the preempting match. assert( rip->r_pre->cap()->matches( capab() ) ); // We need to generate a new preempting match object, // restore our reqexp, and update the CM. delete rip->r_pre; rip->r_pre = new Match; rip->r_reqexp->pub(); rip->update(); } return TRUE; } void Match::start_claim_timer() { if( m_aliveint < 0 ) { dprintf( D_ALWAYS, "Warning: starting claim timer before alive interval set.\n" ); m_aliveint = 300; } m_claim_tid = daemonCore->Register_Timer( (3 * m_aliveint), 0, (TimerHandlercpp)claim_timed_out, "claim_timed_out", this ); if( m_claim_tid == -1 ) { EXCEPT( "Couldn't register timer (out of memory)." ); } dprintf( D_FULLDEBUG, "Started claim timer w/ %d second alive interval.\n", m_aliveint ); } void Match::cancel_claim_timer() { if( m_claim_tid != -1 ) { daemonCore->Cancel_Timer( m_claim_tid ); m_claim_tid = -1; dprintf( D_FULLDEBUG, "Canceled claim timer.\n" ); } } int Match::claim_timed_out() { Resource* rip = resmgr->get_by_cur_cap( capab() ); if( !rip ) { EXCEPT( "Can't find resource of expired claim." ); } // Note that this claim timed out so we don't try to send a // command to our client. if( m_client ) { delete m_client; m_client = NULL; } // Release the claim. rip->release_claim(); return TRUE; } void Match::alive() { // Process a keep alive command daemonCore->Reset_Timer( m_claim_tid, (3 * m_aliveint), 0 ); } // Set our ad to the given pointer void Match::setad(ClassAd *ad) { if( m_ad ) { delete( m_ad ); } m_ad = ad; } void Match::deletead(void) { if( m_ad ) { delete( m_ad ); m_ad = NULL; } } void Match::setagentstream(Stream* stream) { if( m_agentstream ) { delete( m_agentstream ); } m_agentstream = stream; } /////////////////////////////////////////////////////////////////////////// // Client /////////////////////////////////////////////////////////////////////////// Client::Client() { c_name = NULL; c_addr = NULL; c_host = NULL; } Client::~Client() { free( c_name ); free( c_addr ); free( c_host ); } void Client::setname(char* name) { if( c_name ) { free( c_name); } if( name ) { c_name = strdup( name ); } else { c_name = NULL; } } void Client::setaddr(char* addr) { if( c_addr ) { free( c_addr); } if( addr ) { c_addr = strdup( addr ); } else { c_addr = NULL; } } void Client::sethost(char* host) { if( c_host ) { free( c_host); } if( host ) { c_host = strdup( host ); } else { c_host = NULL; } } void Client::vacate(char* cap) { ReliSock sock; sock.timeout( 20 ); if( ! (c_addr || c_host || c_name ) ) { // Client not really set, nothing to do. return; } dprintf(D_FULLDEBUG, "Entered vacate_client %s %s...\n", c_addr, c_host); if( ! sock.connect( c_addr, 0 ) ) { dprintf(D_ALWAYS, "Can't connect to schedd (%s)\n", c_addr); } else { if( !sock.put( RELEASE_CLAIM ) ) { dprintf(D_ALWAYS, "Can't send RELEASE_CLAIM command to client\n"); } else if( !sock.put( cap ) ) { dprintf(D_ALWAYS, "Can't send capability to client\n"); } else if( !sock.eom() ) { dprintf(D_ALWAYS, "Can't send EOM to client\n"); } sock.close(); } } /////////////////////////////////////////////////////////////////////////// // Capability /////////////////////////////////////////////////////////////////////////// char* new_capability_string() { char cap[128]; char tmp[128]; char randbuf[12]; randbuf[0] = '\0'; int i, len; // Create a really mangled 10 digit random number: The first 6 // digits are generated as follows: for the ith digit, pull // the ith digit off a new random int. So our 1st slot comes // from the 1st digit of 1 random int, the 2nd from the 2nd // digit of a 2nd random it, etc... If we're trying to get a // digit from a number that's too small to have that many, we // just use the last digit. The last 4 digits of our number // come from the first 4 digits of the current time multiplied // by a final random int. That should keep 'em guessing. :) // -Derek Wright 1/8/98 for( i=0; i<6; i++ ) { sprintf( tmp, "%d", get_random_int() ); len = strlen(tmp); if( i < len ) { tmp[i+1] = '\0'; strcat( randbuf, tmp+i ); } else { strcat( randbuf, tmp+(len-1) ); } } sprintf( tmp, "%f", (double)((float)time(NULL) * (float)get_random_int()) ); tmp[4]='\0'; strcat( randbuf, tmp ); // Capability string is "<ip:port>#random_number" strcpy( cap, daemonCore->InfoCommandSinfulString() ); strcat( cap, "#" ); strcat( cap, randbuf ); return strdup( cap ); } Capability::Capability() { c_capab = new_capability_string(); } Capability::~Capability() { free( c_capab ); } int Capability::matches(char* capab) { return( strcmp(capab, c_capab) == 0 ); } <commit_msg>Don't put ATTR_JOB_UNIVERSE into the resource classad. We don't use it, and if the users want it in the classad, they can put it into startd_job_exprs.<commit_after>/* This file implements the classes defined in Match.h: Match, Capability, and Client A Match object contains all of the information a startd needs about a given match, such as the capability, the client of this match, etc. The capability in the match is just a pointer to a Capability object. The client is also just a pointer to a Client object. The startd maintains two Match objects in the "rip", the per-resource information structure. One for the current match, and one for the possibly preempting match that is pending. A Capability object contains the capability string, and some functions to manipulate and compare against this string. The constructor generates a new capability with the following form: <ip:port>#random_integer A Client object contains all the info about a given client of a startd. In particular, the client name (a.k.a. "user"), the address ("<www.xxx.yyy.zzz:pppp>" formed ip/port), and the hostname. Written 9/29/97 by Derek Wright <[email protected]> */ #include "startd.h" static char *_FileName_ = __FILE__; /////////////////////////////////////////////////////////////////////////// // Match /////////////////////////////////////////////////////////////////////////// Match::Match() { m_client = new Client; m_cap = new Capability; m_ad = NULL; m_rank = -1; m_oldrank = -1; m_universe = -1; m_agentstream = NULL; m_match_tid = -1; m_claim_tid = -1; m_aliveint = -1; m_cluster = -1; m_proc = -1; m_job_start = -1; m_last_pckpt = -1; } Match::~Match() { // Cancel any timers associated with this match this->cancel_match_timer(); this->cancel_claim_timer(); // Free up memory that's been allocated if( m_ad ) { delete( m_ad ); } delete( m_cap ); if( m_client ) { delete( m_client ); } if( m_agentstream ) { delete( m_agentstream ); } } void Match::vacate() { assert( m_cap ); // warn the client of this match that it's being vacated if( m_client && m_client->addr() ) { m_client->vacate( m_cap->capab() ); } } int Match::send_accountant( int cmd ) { if( !accountant_host ) { return FALSE; } ReliSock sock; sock.timeout( 30 ); if( ! sock.connect( accountant_host, ACCOUNTANT_PORT ) ) { dprintf(D_ALWAYS, "Couldn't connect to accountant\n"); return FALSE; } if( !sock.put( cmd ) ) { dprintf(D_ALWAYS, "Can't send command (%d) to accountant\n", cmd ); return FALSE; } if( !sock.put( m_cap->capab() ) ) { dprintf(D_ALWAYS, "Can't send capability to accountant\n"); return FALSE; } if( !sock.eom() ) { dprintf(D_ALWAYS, "Can't send EOM to accountant\n"); return FALSE; } sock.close(); return TRUE; } void Match::update( ClassAd* ad ) { char line[256]; char* tmp; sprintf( line, "%s = %f", ATTR_CURRENT_RANK, m_rank ); ad->Insert( line ); if( m_client ) { tmp = m_client->name(); if( tmp ) { sprintf( line, "%s=\"%s\"", ATTR_REMOTE_USER, tmp ); ad->Insert( line ); } tmp = m_client->host(); if( tmp ) { sprintf( line, "%s=\"%s\"", ATTR_CLIENT_MACHINE, tmp ); ad->Insert( line ); } } if( (m_cluster > 0) && (m_proc >= 0) ) { sprintf( line, "%s=\"%d.%d\"", ATTR_JOB_ID, m_cluster, m_proc ); ad->Insert( line ); } if( m_job_start > 0 ) { sprintf(line, "%s=%d", ATTR_JOB_START, m_job_start ); ad->Insert( line ); } if( m_last_pckpt > 0 ) { sprintf(line, "%s=%d", ATTR_LAST_PERIODIC_CHECKPOINT, m_last_pckpt ); ad->Insert( line ); } } void Match::refuse_agent() { if( !m_agentstream ) return; dprintf( D_ALWAYS, "Refusing request from schedd agent.\n" ); m_agentstream->encode(); m_agentstream->put(NOT_OK); m_agentstream->end_of_message(); } void Match::start_match_timer() { m_match_tid = daemonCore->Register_Timer( match_timeout, 0, (TimerHandlercpp)match_timed_out, "match_timed_out", this ); if( m_match_tid == -1 ) { EXCEPT( "Couldn't register timer (out of memory)." ); } dprintf( D_FULLDEBUG, "Started match timer for %d seconds.\n", match_timeout ); } void Match::cancel_match_timer() { if( m_match_tid != -1 ) { daemonCore->Cancel_Timer( m_match_tid ); m_match_tid = -1; dprintf( D_FULLDEBUG, "Canceled match timer.\n" ); } } int Match::match_timed_out() { Resource* rip = resmgr->get_by_any_cap( capab() ); if( !rip ) { EXCEPT( "Can't find resource of expired match." ); } if( rip->r_cur->cap()->matches( capab() ) ) { if( rip->state() != matched_state ) { EXCEPT( "Match timed out but not in matched state." ); } delete rip->r_cur; rip->r_cur = new Match; rip->change_state( owner_state ); } else { // The match that timed out was the preempting match. assert( rip->r_pre->cap()->matches( capab() ) ); // We need to generate a new preempting match object, // restore our reqexp, and update the CM. delete rip->r_pre; rip->r_pre = new Match; rip->r_reqexp->pub(); rip->update(); } return TRUE; } void Match::start_claim_timer() { if( m_aliveint < 0 ) { dprintf( D_ALWAYS, "Warning: starting claim timer before alive interval set.\n" ); m_aliveint = 300; } m_claim_tid = daemonCore->Register_Timer( (3 * m_aliveint), 0, (TimerHandlercpp)claim_timed_out, "claim_timed_out", this ); if( m_claim_tid == -1 ) { EXCEPT( "Couldn't register timer (out of memory)." ); } dprintf( D_FULLDEBUG, "Started claim timer w/ %d second alive interval.\n", m_aliveint ); } void Match::cancel_claim_timer() { if( m_claim_tid != -1 ) { daemonCore->Cancel_Timer( m_claim_tid ); m_claim_tid = -1; dprintf( D_FULLDEBUG, "Canceled claim timer.\n" ); } } int Match::claim_timed_out() { Resource* rip = resmgr->get_by_cur_cap( capab() ); if( !rip ) { EXCEPT( "Can't find resource of expired claim." ); } // Note that this claim timed out so we don't try to send a // command to our client. if( m_client ) { delete m_client; m_client = NULL; } // Release the claim. rip->release_claim(); return TRUE; } void Match::alive() { // Process a keep alive command daemonCore->Reset_Timer( m_claim_tid, (3 * m_aliveint), 0 ); } // Set our ad to the given pointer void Match::setad(ClassAd *ad) { if( m_ad ) { delete( m_ad ); } m_ad = ad; } void Match::deletead(void) { if( m_ad ) { delete( m_ad ); m_ad = NULL; } } void Match::setagentstream(Stream* stream) { if( m_agentstream ) { delete( m_agentstream ); } m_agentstream = stream; } /////////////////////////////////////////////////////////////////////////// // Client /////////////////////////////////////////////////////////////////////////// Client::Client() { c_name = NULL; c_addr = NULL; c_host = NULL; } Client::~Client() { free( c_name ); free( c_addr ); free( c_host ); } void Client::setname(char* name) { if( c_name ) { free( c_name); } if( name ) { c_name = strdup( name ); } else { c_name = NULL; } } void Client::setaddr(char* addr) { if( c_addr ) { free( c_addr); } if( addr ) { c_addr = strdup( addr ); } else { c_addr = NULL; } } void Client::sethost(char* host) { if( c_host ) { free( c_host); } if( host ) { c_host = strdup( host ); } else { c_host = NULL; } } void Client::vacate(char* cap) { ReliSock sock; sock.timeout( 20 ); if( ! (c_addr || c_host || c_name ) ) { // Client not really set, nothing to do. return; } dprintf(D_FULLDEBUG, "Entered vacate_client %s %s...\n", c_addr, c_host); if( ! sock.connect( c_addr, 0 ) ) { dprintf(D_ALWAYS, "Can't connect to schedd (%s)\n", c_addr); } else { if( !sock.put( RELEASE_CLAIM ) ) { dprintf(D_ALWAYS, "Can't send RELEASE_CLAIM command to client\n"); } else if( !sock.put( cap ) ) { dprintf(D_ALWAYS, "Can't send capability to client\n"); } else if( !sock.eom() ) { dprintf(D_ALWAYS, "Can't send EOM to client\n"); } sock.close(); } } /////////////////////////////////////////////////////////////////////////// // Capability /////////////////////////////////////////////////////////////////////////// char* new_capability_string() { char cap[128]; char tmp[128]; char randbuf[12]; randbuf[0] = '\0'; int i, len; // Create a really mangled 10 digit random number: The first 6 // digits are generated as follows: for the ith digit, pull // the ith digit off a new random int. So our 1st slot comes // from the 1st digit of 1 random int, the 2nd from the 2nd // digit of a 2nd random it, etc... If we're trying to get a // digit from a number that's too small to have that many, we // just use the last digit. The last 4 digits of our number // come from the first 4 digits of the current time multiplied // by a final random int. That should keep 'em guessing. :) // -Derek Wright 1/8/98 for( i=0; i<6; i++ ) { sprintf( tmp, "%d", get_random_int() ); len = strlen(tmp); if( i < len ) { tmp[i+1] = '\0'; strcat( randbuf, tmp+i ); } else { strcat( randbuf, tmp+(len-1) ); } } sprintf( tmp, "%f", (double)((float)time(NULL) * (float)get_random_int()) ); tmp[4]='\0'; strcat( randbuf, tmp ); // Capability string is "<ip:port>#random_number" strcpy( cap, daemonCore->InfoCommandSinfulString() ); strcat( cap, "#" ); strcat( cap, randbuf ); return strdup( cap ); } Capability::Capability() { c_capab = new_capability_string(); } Capability::~Capability() { free( c_capab ); } int Capability::matches(char* capab) { return( strcmp(capab, c_capab) == 0 ); } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved */ #include "../StroikaPreComp.h" #include <algorithm> #include <cstdlib> #include <fstream> #include <sstream> #if qPlatform_POSIX #include <sys/types.h> #include <unistd.h> #include <signal.h> #endif #include "../../Foundation/Characters/Format.h" #include "../../Foundation/Containers/Common.h" #include "../../Foundation/Debug/Assertions.h" #include "../../Foundation/Debug/Trace.h" #include "../../Foundation/Execution/CommandLine.h" #include "../../Foundation/Execution/Exceptions.h" #include "../../Foundation/Execution/Module.h" #include "../../Foundation/Execution/ThreadAbortException.h" #include "../../Foundation/IO/FileUtils.h" #include "../../Foundation/Memory/SmallStackBuffer.h" #include "Main.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::Service; /* ******************************************************************************** ****************************** Service::Main::IRep ***************************** ******************************************************************************** */ Main::IRep::IRep () : fStopping_ (false) , fMustReReadConfig (false) { } Main::IRep::~IRep () { } void Main::IRep::OnStartRequest () { // This procedure ends when the entire service process ends... Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::IRep::OnStartRequest")); MainLoop (); } void Main::IRep::OnStopRequest () { // default to using thread stuff to send us a signal to abort... fStopping_ = true; } void Main::IRep::OnReReadConfigurationRequest () { } String Main::IRep::GetServiceStatusMessage () const { return String (); } #if qPlatform_POSIX String Main::IRep::GetPIDFileName () const { return L"/tmp/" + GetServiceDescription ().fName + L".pid"; } #endif #if qPlatform_POSIX void Main::IRep::SignalHandler (int signum) { // VERY PRIMITIVE IMPL FOR NOW -- LGP 2011-09-24 switch (signum) { case SIGTERM: fStopping_ = true; break; #if qCompilerAndStdLib_Supports_constexpr case kSIG_ReReadConfiguration: #else case SIGHUP: #endif fMustReReadConfig = true; break; } } #endif /* ******************************************************************************** ************************************ Service::Main ***************************** ******************************************************************************** */ const wchar_t Service::Main::CommandNames::kRunAsService[] = L"Run-As-Service"; const wchar_t Service::Main::CommandNames::kStart[] = L"Start"; const wchar_t Service::Main::CommandNames::kStop[] = L"Stop"; const wchar_t Service::Main::CommandNames::kKill[] = L"Kill"; const wchar_t Service::Main::CommandNames::kRestart[] = L"Restart"; const wchar_t Service::Main::CommandNames::kReloadConfiguration[] = L"Reload-Configuration"; const wchar_t Service::Main::CommandNames::kPause[] = L"Pause"; const wchar_t Service::Main::CommandNames::kContinue[] = L"Continue"; Memory::SharedPtr<Main::IRep> Main::_sRep; Main::Main (Memory::SharedPtr<IRep> rep) { Ensure (_sRep.IsNull ()); _sRep = rep; #if qPlatform_POSIX SetupSignalHanlders_ (); #endif } #if qPlatform_POSIX void Main::SetupSignalHanlders_ () { signal (SIGTERM, SignalHandler); signal (kSIG_ReReadConfiguration, SignalHandler); } #endif Main::State Main::GetState () const { #if qPlatform_POSIX if (GetServicePID () != 0) { return eRunning; } #endif return eStopped; // otherwise (esp on other platforms where not implemtned) must be stopped } #if qPlatform_POSIX pid_t Main::GetServicePID () const { ifstream in (_sRep->GetPIDFileName ().AsTString ().c_str ()); if (in) { pid_t n = 0; in >> n; return n; } return 0; } #endif String Main::GetServiceStatusMessage () const { ServiceDescription svd = GetServiceDescription (); wstringstream tmp; tmp << L"Service '" << svd.fName.As<wstring> () << "'" << endl; switch (this->GetState ()) { case eStopped: tmp << L" State: STOPPED" << endl; break; case eRunning: tmp << L" State: Running" << endl; #if qPlatform_POSIX tmp << L" PID: " << GetServicePID () << endl; #endif break; case ePaused: tmp << L" State: PAUSED" << endl; #if qPlatform_POSIX tmp << L" PID: " << GetServicePID () << endl; #endif break; default: AssertNotReached (); } return tmp.str (); } void Main::RunAsService () { // VERY PRIMITIVE IMPL - WE NEED LOCKING on tmpfile stuff - add good tempfile supprot to fileuitls or use existing... try { #if qPlatform_POSIX ofstream out (_sRep->GetPIDFileName ().AsTString ().c_str ()); out << getpid () << endl; #endif _sRep->OnStartRequest (); } catch (const Execution::ThreadAbortException& /*threadAbort*/) { #if qPlatform_POSIX unlink (_sRep->GetPIDFileName ().AsTString ().c_str ()); #endif // ignore this - just means service ended normally } catch (...) { DbgTrace (TSTR ("Unexpected exception ended running service")); #if qPlatform_POSIX unlink (_sRep->GetPIDFileName ().AsTString ().c_str ()); #endif throw; } } void Main::Start () { // Check not already runnig, (someday) and then for and exec the #if qPlatform_POSIX // REALLY should use GETSTATE - and return state based on if PID file exsits... if (GetServicePID () != 0) { Execution::DoThrow (Execution::StringException (L"Cannot Start service because its already running")); } #endif Characters::TString thisEXEPath = Execution::GetEXEPath (); #if qPlatform_POSIX pid_t pid = fork (); if (pid == 0) { // Child - exec int r = execl (thisEXEPath.c_str (), thisEXEPath.c_str (), String (CommandNames::kRunAsService).AsTString ().c_str (), nullptr); exit (-1); } else if (pid < 0) { // failed to fork - serious error Execution::errno_ErrorException::DoThrow (errno); } else { // parent - in this case - no reason to wait - our work is done... Future versions might wait to // see if the 'pidfile' got created.... // --LGP 2011-09-23 } #endif } void Main::Stop () { // Send signal to server to stop #if qPlatform_POSIX kill (GetServicePID (), SIGTERM); #endif } void Main::Kill () { Stop (); // Send signal to server to stop #if qPlatform_POSIX kill (GetServicePID (), SIGKILL); // REALY should WAIT for server to stop and only do this it fails - unlink (_sRep->GetPIDFileName ().AsTString ().c_str ()); #endif } void Main::Restart () { IgnoreExceptionsForCall (Stop ()); #if qPlatform_POSIX // REALY should WAIT for server to stop and only do this it fails - unlink (_sRep->GetPIDFileName ().AsTString ().c_str ()); #endif Start (); } void Main::ReReadConfiguration () { // SEND APPROPRIATE SIGNAL #if qPlatform_POSIX pid_t pid = GetServicePID (); Assert (pid != 0); // maybe throw if non-zero??? kill (GetServicePID (), kSIG_ReReadConfiguration); #endif } void Main::Pause () { AssertNotImplemented (); } void Main::Continue () { AssertNotImplemented (); } Main::ServiceDescription Main::GetServiceDescription () const { return _sRep->GetServiceDescription (); } #if qPlatform_POSIX void Main::SignalHandler (int signum) { _sRep->SignalHandler (signum); } #endif bool Main::_HandleStandardCommandLineArgument (const String& arg) { if (Execution::MatchesCommandLineArgument (arg, CommandNames::kRunAsService)) { RunAsService (); return true; } else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kStart)) { Start (); return true; } else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kStop)) { Stop (); return true; } else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kKill)) { Kill (); return true; } else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kRestart)) { Restart (); return true; } else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kReloadConfiguration)) { ReReadConfiguration (); return true; } else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kPause)) { Pause (); return true; } else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kContinue)) { Continue (); return true; } /// MANY more neeeded, and fix to use named constants... return false; } <commit_msg>neaten output of Main::GetServiceStatusMessage ()<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved */ #include "../StroikaPreComp.h" #include <algorithm> #include <cstdlib> #include <fstream> #include <sstream> #if qPlatform_POSIX #include <sys/types.h> #include <unistd.h> #include <signal.h> #endif #include "../../Foundation/Characters/Format.h" #include "../../Foundation/Containers/Common.h" #include "../../Foundation/Debug/Assertions.h" #include "../../Foundation/Debug/Trace.h" #include "../../Foundation/Execution/CommandLine.h" #include "../../Foundation/Execution/Exceptions.h" #include "../../Foundation/Execution/Module.h" #include "../../Foundation/Execution/ThreadAbortException.h" #include "../../Foundation/IO/FileUtils.h" #include "../../Foundation/Memory/SmallStackBuffer.h" #include "Main.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::Service; /* ******************************************************************************** ****************************** Service::Main::IRep ***************************** ******************************************************************************** */ Main::IRep::IRep () : fStopping_ (false) , fMustReReadConfig (false) { } Main::IRep::~IRep () { } void Main::IRep::OnStartRequest () { // This procedure ends when the entire service process ends... Debug::TraceContextBumper traceCtx (TSTR ("Stroika::Frameworks::Service::Main::IRep::OnStartRequest")); MainLoop (); } void Main::IRep::OnStopRequest () { // default to using thread stuff to send us a signal to abort... fStopping_ = true; } void Main::IRep::OnReReadConfigurationRequest () { } String Main::IRep::GetServiceStatusMessage () const { return String (); } #if qPlatform_POSIX String Main::IRep::GetPIDFileName () const { return L"/tmp/" + GetServiceDescription ().fName + L".pid"; } #endif #if qPlatform_POSIX void Main::IRep::SignalHandler (int signum) { // VERY PRIMITIVE IMPL FOR NOW -- LGP 2011-09-24 switch (signum) { case SIGTERM: fStopping_ = true; break; #if qCompilerAndStdLib_Supports_constexpr case kSIG_ReReadConfiguration: #else case SIGHUP: #endif fMustReReadConfig = true; break; } } #endif /* ******************************************************************************** ************************************ Service::Main ***************************** ******************************************************************************** */ const wchar_t Service::Main::CommandNames::kRunAsService[] = L"Run-As-Service"; const wchar_t Service::Main::CommandNames::kStart[] = L"Start"; const wchar_t Service::Main::CommandNames::kStop[] = L"Stop"; const wchar_t Service::Main::CommandNames::kKill[] = L"Kill"; const wchar_t Service::Main::CommandNames::kRestart[] = L"Restart"; const wchar_t Service::Main::CommandNames::kReloadConfiguration[] = L"Reload-Configuration"; const wchar_t Service::Main::CommandNames::kPause[] = L"Pause"; const wchar_t Service::Main::CommandNames::kContinue[] = L"Continue"; Memory::SharedPtr<Main::IRep> Main::_sRep; Main::Main (Memory::SharedPtr<IRep> rep) { Ensure (_sRep.IsNull ()); _sRep = rep; #if qPlatform_POSIX SetupSignalHanlders_ (); #endif } #if qPlatform_POSIX void Main::SetupSignalHanlders_ () { signal (SIGTERM, SignalHandler); signal (kSIG_ReReadConfiguration, SignalHandler); } #endif Main::State Main::GetState () const { #if qPlatform_POSIX if (GetServicePID () != 0) { return eRunning; } #endif return eStopped; // otherwise (esp on other platforms where not implemtned) must be stopped } #if qPlatform_POSIX pid_t Main::GetServicePID () const { ifstream in (_sRep->GetPIDFileName ().AsTString ().c_str ()); if (in) { pid_t n = 0; in >> n; return n; } return 0; } #endif String Main::GetServiceStatusMessage () const { const wchar_t kTAB[] = L" "; // use spaces instead of tab so formatting independent of tabstop settings ServiceDescription svd = GetServiceDescription (); wstringstream tmp; tmp << L"Service '" << svd.fName.As<wstring> () << "'" << endl; switch (this->GetState ()) { case eStopped: tmp << kTAB << L"State: " << kTAB << "STOPPED" << endl; break; case eRunning: tmp << kTAB << L"State: " << kTAB << "Running" << endl; #if qPlatform_POSIX tmp << kTAB << L"PID: " << kTAB << GetServicePID () << endl; #endif break; case ePaused: tmp << kTAB << L"State: " << kTAB << "PAUSED" << endl; #if qPlatform_POSIX tmp << kTAB << L"PID: " << kTAB<< GetServicePID () << endl; #endif break; default: AssertNotReached (); } return tmp.str (); } void Main::RunAsService () { // VERY PRIMITIVE IMPL - WE NEED LOCKING on tmpfile stuff - add good tempfile supprot to fileuitls or use existing... try { #if qPlatform_POSIX ofstream out (_sRep->GetPIDFileName ().AsTString ().c_str ()); out << getpid () << endl; #endif _sRep->OnStartRequest (); } catch (const Execution::ThreadAbortException& /*threadAbort*/) { #if qPlatform_POSIX unlink (_sRep->GetPIDFileName ().AsTString ().c_str ()); #endif // ignore this - just means service ended normally } catch (...) { DbgTrace (TSTR ("Unexpected exception ended running service")); #if qPlatform_POSIX unlink (_sRep->GetPIDFileName ().AsTString ().c_str ()); #endif throw; } } void Main::Start () { // Check not already runnig, (someday) and then for and exec the #if qPlatform_POSIX // REALLY should use GETSTATE - and return state based on if PID file exsits... if (GetServicePID () != 0) { Execution::DoThrow (Execution::StringException (L"Cannot Start service because its already running")); } #endif Characters::TString thisEXEPath = Execution::GetEXEPath (); #if qPlatform_POSIX pid_t pid = fork (); if (pid == 0) { // Child - exec int r = execl (thisEXEPath.c_str (), thisEXEPath.c_str (), String (CommandNames::kRunAsService).AsTString ().c_str (), nullptr); exit (-1); } else if (pid < 0) { // failed to fork - serious error Execution::errno_ErrorException::DoThrow (errno); } else { // parent - in this case - no reason to wait - our work is done... Future versions might wait to // see if the 'pidfile' got created.... // --LGP 2011-09-23 } #endif } void Main::Stop () { // Send signal to server to stop #if qPlatform_POSIX kill (GetServicePID (), SIGTERM); #endif } void Main::Kill () { Stop (); // Send signal to server to stop #if qPlatform_POSIX kill (GetServicePID (), SIGKILL); // REALY should WAIT for server to stop and only do this it fails - unlink (_sRep->GetPIDFileName ().AsTString ().c_str ()); #endif } void Main::Restart () { IgnoreExceptionsForCall (Stop ()); #if qPlatform_POSIX // REALY should WAIT for server to stop and only do this it fails - unlink (_sRep->GetPIDFileName ().AsTString ().c_str ()); #endif Start (); } void Main::ReReadConfiguration () { // SEND APPROPRIATE SIGNAL #if qPlatform_POSIX pid_t pid = GetServicePID (); Assert (pid != 0); // maybe throw if non-zero??? kill (GetServicePID (), kSIG_ReReadConfiguration); #endif } void Main::Pause () { AssertNotImplemented (); } void Main::Continue () { AssertNotImplemented (); } Main::ServiceDescription Main::GetServiceDescription () const { return _sRep->GetServiceDescription (); } #if qPlatform_POSIX void Main::SignalHandler (int signum) { _sRep->SignalHandler (signum); } #endif bool Main::_HandleStandardCommandLineArgument (const String& arg) { if (Execution::MatchesCommandLineArgument (arg, CommandNames::kRunAsService)) { RunAsService (); return true; } else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kStart)) { Start (); return true; } else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kStop)) { Stop (); return true; } else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kKill)) { Kill (); return true; } else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kRestart)) { Restart (); return true; } else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kReloadConfiguration)) { ReReadConfiguration (); return true; } else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kPause)) { Pause (); return true; } else if (Execution::MatchesCommandLineArgument (arg, CommandNames::kContinue)) { Continue (); return true; } /// MANY more neeeded, and fix to use named constants... return false; } <|endoftext|>
<commit_before>/* Copyright 2017 The TensorFlow 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 <utility> #include "tensorflow/core/framework/dataset.h" #include "tensorflow/core/framework/partial_tensor_shape.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/kernels/data/experimental/sql/driver_manager.h" #include "tensorflow/core/kernels/data/experimental/sql/query_connection.h" #include "tensorflow/core/lib/io/inputbuffer.h" #include "tensorflow/core/lib/io/record_reader.h" #include "tensorflow/core/lib/strings/stringprintf.h" namespace tensorflow { namespace data { namespace experimental { namespace { class SqlDatasetOp : public DatasetOpKernel { public: explicit SqlDatasetOp(OpKernelConstruction* ctx) : DatasetOpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("output_shapes", &output_shapes_)); for (const DataType& dt : output_types_) { OP_REQUIRES(ctx, dt == DT_STRING || dt == DT_INT8 || dt == DT_INT16 || dt == DT_INT32 || dt == DT_INT64 || dt == DT_UINT8 || dt == DT_UINT16 || dt == DT_BOOL || dt == DT_DOUBLE, errors::InvalidArgument( "Each element of `output_types_` must be one of: " "DT_STRING, DT_INT8, DT_INT16, DT_INT32, DT_INT64, " "DT_UINT8, DT_UINT16, DT_BOOL, DT_DOUBLE ")); } for (const PartialTensorShape& pts : output_shapes_) { OP_REQUIRES(ctx, pts.dims() == 0, errors::InvalidArgument( "Each element of `output_shapes_` must be a scalar.")); } } void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override { tstring driver_name; OP_REQUIRES_OK( ctx, ParseScalarArgument<tstring>(ctx, "driver_name", &driver_name)); tstring data_source_name; OP_REQUIRES_OK(ctx, ParseScalarArgument<tstring>(ctx, "data_source_name", &data_source_name)); tstring query; OP_REQUIRES_OK(ctx, ParseScalarArgument<tstring>(ctx, "query", &query)); // TODO(b/64276826) Change this check when we add support for other // databases. OP_REQUIRES(ctx, driver_name == "sqlite", errors::InvalidArgument(tensorflow::strings::Printf( "The database type, %s, is not supported by SqlDataset. " "The set of supported databases is: {'sqlite'}.", driver_name.c_str()))); *output = new Dataset(ctx, driver_name, data_source_name, query, output_types_, output_shapes_); } private: class Dataset : public DatasetBase { public: Dataset(OpKernelContext* ctx, const string& driver_name, const string& data_source_name, const string& query, const DataTypeVector& output_types, const std::vector<PartialTensorShape>& output_shapes) : DatasetBase(DatasetContext(ctx)), driver_name_(driver_name), data_source_name_(data_source_name), query_(query), output_types_(output_types), output_shapes_(output_shapes) {} std::unique_ptr<IteratorBase> MakeIteratorInternal( const string& prefix) const override { return absl::make_unique<Iterator>( Iterator::Params{this, strings::StrCat(prefix, "::Sql")}); } const DataTypeVector& output_dtypes() const override { return output_types_; } const std::vector<PartialTensorShape>& output_shapes() const override { return output_shapes_; } string DebugString() const override { return "SqlDatasetOp::Dataset"; } Status CheckExternalState() const override { return Status::OK(); } protected: Status AsGraphDefInternal(SerializationContext* ctx, DatasetGraphDefBuilder* b, Node** output) const override { Node* driver_name_node; TF_RETURN_IF_ERROR(b->AddScalar(driver_name_, &driver_name_node)); Node* data_source_name_node; TF_RETURN_IF_ERROR( b->AddScalar(data_source_name_, &data_source_name_node)); Node* query_node; TF_RETURN_IF_ERROR(b->AddScalar(query_, &query_node)); TF_RETURN_IF_ERROR(b->AddDataset( this, {driver_name_node, data_source_name_node, query_node}, output)); return Status::OK(); } private: class Iterator : public DatasetIterator<Dataset> { public: explicit Iterator(const Params& params) : DatasetIterator<Dataset>(params) {} ~Iterator() override { if (query_connection_initialized_) { Status s = query_connection_->Close(); if (!s.ok()) { LOG(WARNING) << "Failed to close query connection: " << s; } } } Status GetNextInternal(IteratorContext* ctx, std::vector<Tensor>* out_tensors, bool* end_of_sequence) override { mutex_lock l(mu_); if (!query_connection_initialized_) { TF_RETURN_IF_ERROR(InitializeQueryConnection()); } next_calls_++; return query_connection_->GetNext(ctx, out_tensors, end_of_sequence); } protected: std::shared_ptr<model::Node> CreateNode( IteratorContext* ctx, model::Node::Args args) const override { return model::MakeSourceNode(std::move(args)); } Status SaveInternal(IteratorStateWriter* writer) override { mutex_lock l(mu_); if (query_connection_initialized_) { TF_RETURN_IF_ERROR( writer->WriteScalar(full_name("next_calls"), next_calls_)); } return Status::OK(); } Status RestoreInternal(IteratorContext* ctx, IteratorStateReader* reader) override { mutex_lock l(mu_); if (reader->Contains(full_name("next_calls"))) { TF_RETURN_IF_ERROR(InitializeQueryConnection()); TF_RETURN_IF_ERROR( reader->ReadScalar(full_name("next_calls"), &next_calls_)); int64 rem_next_calls = next_calls_; std::vector<Tensor> out_tensors; bool end_of_sequence = false; while (rem_next_calls--) { TF_RETURN_IF_ERROR(query_connection_->GetNext(ctx, &out_tensors, &end_of_sequence)); out_tensors.clear(); } } else { query_connection_initialized_ = false; } return Status::OK(); } private: Status InitializeQueryConnection() EXCLUSIVE_LOCKS_REQUIRED(mu_) { query_connection_initialized_ = true; query_connection_ = sql::DriverManager::CreateQueryConnection(dataset()->driver_name_); Status s = query_connection_->Open(dataset()->data_source_name_, dataset()->query_, dataset()->output_types_); next_calls_ = 0; if (!s.ok()) { LOG(WARNING) << "Failed to connect to database: " << s; return s; } return Status::OK(); } mutex mu_; // TODO(b/129062371): explore ways to seek into a SQLite databases. int64 next_calls_ GUARDED_BY(mu_) = 0; std::unique_ptr<sql::QueryConnection> query_connection_ GUARDED_BY(mu_); bool query_connection_initialized_ GUARDED_BY(mu_) = false; }; const tstring driver_name_; const tstring data_source_name_; const tstring query_; const DataTypeVector output_types_; const std::vector<PartialTensorShape> output_shapes_; }; DataTypeVector output_types_; std::vector<PartialTensorShape> output_shapes_; }; REGISTER_KERNEL_BUILDER(Name("SqlDataset").Device(DEVICE_CPU), SqlDatasetOp); REGISTER_KERNEL_BUILDER(Name("ExperimentalSqlDataset").Device(DEVICE_CPU), SqlDatasetOp); } // namespace } // namespace experimental } // namespace data } // namespace tensorflow <commit_msg>Fix SqlDataset fails to raise StopIteration issue when combined with batch<commit_after>/* Copyright 2017 The TensorFlow 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 <utility> #include "tensorflow/core/framework/dataset.h" #include "tensorflow/core/framework/partial_tensor_shape.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/kernels/data/experimental/sql/driver_manager.h" #include "tensorflow/core/kernels/data/experimental/sql/query_connection.h" #include "tensorflow/core/lib/io/inputbuffer.h" #include "tensorflow/core/lib/io/record_reader.h" #include "tensorflow/core/lib/strings/stringprintf.h" namespace tensorflow { namespace data { namespace experimental { namespace { class SqlDatasetOp : public DatasetOpKernel { public: explicit SqlDatasetOp(OpKernelConstruction* ctx) : DatasetOpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("output_shapes", &output_shapes_)); for (const DataType& dt : output_types_) { OP_REQUIRES(ctx, dt == DT_STRING || dt == DT_INT8 || dt == DT_INT16 || dt == DT_INT32 || dt == DT_INT64 || dt == DT_UINT8 || dt == DT_UINT16 || dt == DT_BOOL || dt == DT_DOUBLE, errors::InvalidArgument( "Each element of `output_types_` must be one of: " "DT_STRING, DT_INT8, DT_INT16, DT_INT32, DT_INT64, " "DT_UINT8, DT_UINT16, DT_BOOL, DT_DOUBLE ")); } for (const PartialTensorShape& pts : output_shapes_) { OP_REQUIRES(ctx, pts.dims() == 0, errors::InvalidArgument( "Each element of `output_shapes_` must be a scalar.")); } } void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override { tstring driver_name; OP_REQUIRES_OK( ctx, ParseScalarArgument<tstring>(ctx, "driver_name", &driver_name)); tstring data_source_name; OP_REQUIRES_OK(ctx, ParseScalarArgument<tstring>(ctx, "data_source_name", &data_source_name)); tstring query; OP_REQUIRES_OK(ctx, ParseScalarArgument<tstring>(ctx, "query", &query)); // TODO(b/64276826) Change this check when we add support for other // databases. OP_REQUIRES(ctx, driver_name == "sqlite", errors::InvalidArgument(tensorflow::strings::Printf( "The database type, %s, is not supported by SqlDataset. " "The set of supported databases is: {'sqlite'}.", driver_name.c_str()))); *output = new Dataset(ctx, driver_name, data_source_name, query, output_types_, output_shapes_); } private: class Dataset : public DatasetBase { public: Dataset(OpKernelContext* ctx, const string& driver_name, const string& data_source_name, const string& query, const DataTypeVector& output_types, const std::vector<PartialTensorShape>& output_shapes) : DatasetBase(DatasetContext(ctx)), driver_name_(driver_name), data_source_name_(data_source_name), query_(query), output_types_(output_types), output_shapes_(output_shapes) {} std::unique_ptr<IteratorBase> MakeIteratorInternal( const string& prefix) const override { return absl::make_unique<Iterator>( Iterator::Params{this, strings::StrCat(prefix, "::Sql")}); } const DataTypeVector& output_dtypes() const override { return output_types_; } const std::vector<PartialTensorShape>& output_shapes() const override { return output_shapes_; } string DebugString() const override { return "SqlDatasetOp::Dataset"; } Status CheckExternalState() const override { return Status::OK(); } protected: Status AsGraphDefInternal(SerializationContext* ctx, DatasetGraphDefBuilder* b, Node** output) const override { Node* driver_name_node; TF_RETURN_IF_ERROR(b->AddScalar(driver_name_, &driver_name_node)); Node* data_source_name_node; TF_RETURN_IF_ERROR( b->AddScalar(data_source_name_, &data_source_name_node)); Node* query_node; TF_RETURN_IF_ERROR(b->AddScalar(query_, &query_node)); TF_RETURN_IF_ERROR(b->AddDataset( this, {driver_name_node, data_source_name_node, query_node}, output)); return Status::OK(); } private: class Iterator : public DatasetIterator<Dataset> { public: explicit Iterator(const Params& params) : DatasetIterator<Dataset>(params) {} ~Iterator() override { if (query_connection_initialized_) { Status s = query_connection_->Close(); if (!s.ok()) { LOG(WARNING) << "Failed to close query connection: " << s; } } } Status GetNextInternal(IteratorContext* ctx, std::vector<Tensor>* out_tensors, bool* end_of_sequence) override { mutex_lock l(mu_); if (!query_connection_initialized_) { TF_RETURN_IF_ERROR(InitializeQueryConnection()); } Status status = Status::OK(); if (!end_of_sequence_) { next_calls_++; status = query_connection_->GetNext(ctx, out_tensors, &end_of_sequence_); } *end_of_sequence = end_of_sequence_; return status; } protected: std::shared_ptr<model::Node> CreateNode( IteratorContext* ctx, model::Node::Args args) const override { return model::MakeSourceNode(std::move(args)); } Status SaveInternal(IteratorStateWriter* writer) override { mutex_lock l(mu_); if (query_connection_initialized_) { TF_RETURN_IF_ERROR( writer->WriteScalar(full_name("next_calls"), next_calls_)); } return Status::OK(); } Status RestoreInternal(IteratorContext* ctx, IteratorStateReader* reader) override { mutex_lock l(mu_); if (reader->Contains(full_name("next_calls"))) { TF_RETURN_IF_ERROR(InitializeQueryConnection()); TF_RETURN_IF_ERROR( reader->ReadScalar(full_name("next_calls"), &next_calls_)); int64 rem_next_calls = next_calls_; std::vector<Tensor> out_tensors; end_of_sequence_ = false; while (rem_next_calls--) { TF_RETURN_IF_ERROR(query_connection_->GetNext(ctx, &out_tensors, &end_of_sequence_)); out_tensors.clear(); } } else { query_connection_initialized_ = false; end_of_sequence_ = false; } return Status::OK(); } private: Status InitializeQueryConnection() EXCLUSIVE_LOCKS_REQUIRED(mu_) { query_connection_initialized_ = true; end_of_sequence_ = false; query_connection_ = sql::DriverManager::CreateQueryConnection(dataset()->driver_name_); Status s = query_connection_->Open(dataset()->data_source_name_, dataset()->query_, dataset()->output_types_); next_calls_ = 0; if (!s.ok()) { LOG(WARNING) << "Failed to connect to database: " << s; return s; } return Status::OK(); } mutex mu_; // TODO(b/129062371): explore ways to seek into a SQLite databases. int64 next_calls_ GUARDED_BY(mu_) = 0; std::unique_ptr<sql::QueryConnection> query_connection_ GUARDED_BY(mu_); bool query_connection_initialized_ GUARDED_BY(mu_) = false; bool end_of_sequence_ GUARDED_BY(mu_) = false; }; const tstring driver_name_; const tstring data_source_name_; const tstring query_; const DataTypeVector output_types_; const std::vector<PartialTensorShape> output_shapes_; }; DataTypeVector output_types_; std::vector<PartialTensorShape> output_shapes_; }; REGISTER_KERNEL_BUILDER(Name("SqlDataset").Device(DEVICE_CPU), SqlDatasetOp); REGISTER_KERNEL_BUILDER(Name("ExperimentalSqlDataset").Device(DEVICE_CPU), SqlDatasetOp); } // namespace } // namespace experimental } // namespace data } // namespace tensorflow <|endoftext|>
<commit_before>#include "palabos3D.h" #include "palabos3D.hh" #include <vector> #include <cmath> using namespace plb; using namespace plb::descriptors; using namespace std; typedef double T; typedef Array<T,3> Velocity; //#define DESCRIPTOR descriptors::D3Q27Descriptor #define DESCRIPTOR MRTD3Q19Descriptor typedef MRTdynamics<T,DESCRIPTOR> BackgroundDynamics; typedef AnechoicMRTdynamics<T,DESCRIPTOR> AnechoicBackgroundDynamics; // --------------------------------------------- // Includes of acoustics resources #include "acoustics/acoustics3D.h" using namespace plb_acoustics_3D; // --------------------------------------------- const T rho0 = 1; const T drho = rho0/10; void writeGifs(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){ const plint nx = lattice.getNx(); const plint ny = lattice.getNy(); const plint nz = lattice.getNz(); const plint imSize = 600; ImageWriter<T> imageWriter("leeloo"); Box3D slice(0, nx-1, 0, ny-1, nz/2, nz/2); //imageWriter.writeGif(createFileName("u", iT, 6), //*computeDensity(lattice), ); imageWriter.writeGif( createFileName("rho", iter, 6), *computeDensity(lattice, slice), (T) rho0 - drho/1000000, (T) rho0 + drho/1000000, imSize, imSize); } void writeVTK(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){ VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), 1.); vtkOut.writeData<float>(*computeDensity(lattice), "density", 1.); vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", 1.); } int main(int argc, char **argv){ plbInit(&argc, &argv); std::string fNameOut = "tmp"; const plint nx = 100; const plint ny = 100; const plint nz = 100; const T lattice_speed_sound = 1/sqrt(3); const T omega = 1.9; const plint maxT = 4000; const T lx = 2.3; const T dx =lx/nx; Array<T,3> u0(0, 0, 0); plint cx = util::roundToInt(nx/2); plint cy = util::roundToInt(ny/2); plint cz = util::roundToInt(nz/2); Array<T,3> centerLB(cx , cy, cz); global::directories().setOutputDir(fNameOut+"/"); T rhoBar_target = 0; Array<T,3> j_target(0, 0, 0); T delta = 30; AnechoicBackgroundDynamics *anechoicDynamics = new AnechoicBackgroundDynamics(omega); anechoicDynamics->setDelta((T) delta); anechoicDynamics->setRhoBar_target(rhoBar_target); //j_target[0] = -j_target[0]; anechoicDynamics->setJ_target(j_target); MultiBlockLattice3D<T, DESCRIPTOR> lattice(nx,ny,nz, anechoicDynamics); pcout << "Creation of the lattice." << endl; // Switch off periodicity. lattice.periodicity().toggleAll(false); pcout << "Initilization of rho and u." << endl; initializeAtEquilibrium( lattice, lattice.getBoundingBox(), rho0 , u0 ); plint size_square = 80; Box3D square( nx/2 - size_square/2, nx/2 + size_square/2, ny/2 - size_square/2, ny/2 + size_square/2, nz/2 - size_square/2, nz/2 + size_square/2); defineDynamics(lattice, square, new BackgroundDynamics(omega)); // Anechoic Condition /*T rhoBar_target = 0; Array<T,3> j_target(0, 0, 0); T size_anechoic_buffer = 30; // Define Anechoic Boards defineAnechoicBoards(nx, ny, nz, lattice, size_anechoic_buffer, omega, j_target, j_target, j_target, j_target, j_target, j_target, rhoBar_target);*/ lattice.initialize(); pcout << std::endl << "Voxelizing the domain." << std::endl; pcout << std::endl << "dx:" << dx << std::endl; pcout << "Simulation begins" << endl; plb_ofstream history_pressures("history_pressures.dat"); for (plint iT=0; iT<maxT; ++iT){ if (iT != 0){ T lattice_speed_sound = 1/sqrt(3); T rho_changing = 1. + drho*sin(2*M_PI*(lattice_speed_sound/20)*iT); Box3D impulse(nx/2 + 20, nx/2 + 20, ny/2 + 20, ny/2 + 20, nz/2 + 20, nz/2 + 20); initializeAtEquilibrium( lattice, impulse, rho_changing, u0 ); } if (iT % 100 == 0 && iT>0) { pcout << "Iteration " << iT << endl; //writeGifs(lattice,iT); //writeVTK(lattice, iT); } history_pressures << setprecision(10) << lattice.get(nx/2+30, ny/2+30, nz/2+30).computeDensity() - rho0 << endl; lattice.collideAndStream(); } pcout << "End of simulation at iteration " << endl; } <commit_msg>Its more interesting to avoid bug of dynamics<commit_after>#include "palabos3D.h" #include "palabos3D.hh" #include <vector> #include <cmath> using namespace plb; using namespace plb::descriptors; using namespace std; typedef double T; typedef Array<T,3> Velocity; //#define DESCRIPTOR descriptors::D3Q27Descriptor #define DESCRIPTOR MRTD3Q19Descriptor typedef MRTdynamics<T,DESCRIPTOR> BackgroundDynamics; typedef AnechoicMRTdynamics<T,DESCRIPTOR> AnechoicBackgroundDynamics; // --------------------------------------------- // Includes of acoustics resources #include "acoustics/acoustics3D.h" using namespace plb_acoustics_3D; // --------------------------------------------- const T rho0 = 1; const T drho = rho0/10; void writeGifs(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){ const plint nx = lattice.getNx(); const plint ny = lattice.getNy(); const plint nz = lattice.getNz(); const plint imSize = 600; ImageWriter<T> imageWriter("leeloo"); Box3D slice(0, nx-1, 0, ny-1, nz/2, nz/2); //imageWriter.writeGif(createFileName("u", iT, 6), //*computeDensity(lattice), ); imageWriter.writeGif( createFileName("rho", iter, 6), *computeDensity(lattice, slice), (T) rho0 - drho/1000000, (T) rho0 + drho/1000000, imSize, imSize); } void writeVTK(MultiBlockLattice3D<T,DESCRIPTOR>& lattice, plint iter){ VtkImageOutput3D<T> vtkOut(createFileName("vtk", iter, 6), 1.); vtkOut.writeData<float>(*computeDensity(lattice), "density", 1.); vtkOut.writeData<3,float>(*computeVelocity(lattice), "velocity", 1.); } int main(int argc, char **argv){ plbInit(&argc, &argv); std::string fNameOut = "tmp"; const plint nx = 100; const plint ny = 100; const plint nz = 100; const T lattice_speed_sound = 1/sqrt(3); const T omega = 1.9; const plint maxT = 4000; const T lx = 2.3; const T dx =lx/nx; Array<T,3> u0(0, 0, 0); plint cx = util::roundToInt(nx/2); plint cy = util::roundToInt(ny/2); plint cz = util::roundToInt(nz/2); Array<T,3> centerLB(cx , cy, cz); global::directories().setOutputDir(fNameOut+"/"); T rhoBar_target = 0; Array<T,3> j_target(0, 0, 0); T delta = 30; AnechoicBackgroundDynamics *anechoicDynamics = new AnechoicBackgroundDynamics(omega); anechoicDynamics->setDelta((T) delta); anechoicDynamics->setRhoBar_target(rhoBar_target); //j_target[0] = -j_target[0]; anechoicDynamics->setJ_target(j_target); MultiBlockLattice3D<T, DESCRIPTOR> lattice(nx, ny, nz, anechoicDynamics); defineDynamics(lattice, lattice.getBoundingBox(), new BackgroundDynamics(omega)); pcout << "Creation of the lattice." << endl; // Switch off periodicity. lattice.periodicity().toggleAll(false); pcout << "Initilization of rho and u." << endl; initializeAtEquilibrium( lattice, lattice.getBoundingBox(), rho0 , u0 ); plint size_square = 40; Box3D square( nx/2 - size_square/2, nx/2 + size_square/2, ny/2 - size_square/2, ny/2 + size_square/2, nz/2 - size_square/2, nz/2 + size_square/2); defineDynamics(lattice, square, anechoicDynamics); // Anechoic Condition /*T rhoBar_target = 0; Array<T,3> j_target(0, 0, 0); T size_anechoic_buffer = 30; // Define Anechoic Boards defineAnechoicBoards(nx, ny, nz, lattice, size_anechoic_buffer, omega, j_target, j_target, j_target, j_target, j_target, j_target, rhoBar_target);*/ lattice.initialize(); pcout << std::endl << "Voxelizing the domain." << std::endl; pcout << std::endl << "dx:" << dx << std::endl; pcout << "Simulation begins" << endl; plb_ofstream history_pressures("history_pressures.dat"); for (plint iT=0; iT<maxT; ++iT){ if (iT != 0){ T lattice_speed_sound = 1/sqrt(3); T rho_changing = 1. + drho*sin(2*M_PI*(lattice_speed_sound/20)*iT); Box3D impulse(nx/2 + 20, nx/2 + 20, ny/2 + 20, ny/2 + 20, nz/2 + 20, nz/2 + 20); initializeAtEquilibrium( lattice, impulse, rho_changing, u0 ); } if (iT % 100 == 0 && iT>0) { pcout << "Iteration " << iT << endl; //writeGifs(lattice,iT); //writeVTK(lattice, iT); } history_pressures << setprecision(10) << lattice.get(nx/2+30, ny/2+30, nz/2+30).computeDensity() - rho0 << endl; lattice.collideAndStream(); } pcout << "End of simulation at iteration " << endl; } <|endoftext|>
<commit_before>/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <chrono> #include <condition_variable> #include <deque> #include <memory> #include <mutex> #include <random> #include <thread> #include <folly/Synchronized.h> #include <folly/portability/GMock.h> #include <folly/portability/GTest.h> #include <folly/synchronization/Baton.h> #include <thrift/lib/cpp/concurrency/FunctionRunner.h> #include <thrift/lib/cpp/concurrency/SFQThreadManager.h> using namespace apache::thrift::concurrency; using testing::_; using testing::AnyNumber; using testing::AtLeast; class SFQThreadManagerTest : public testing::Test { public: MOCK_METHOD1(bogusTask, void(int)); protected: std::shared_ptr<ThreadManager> newSFQTM( std::chrono::seconds perturb, size_t numQueues) { SFQThreadManagerConfig config; config.setPerturbInterval(perturb) .setNumFairQueuesForUpstream(numQueues) .setExecutors( {ThreadManager::newSimpleThreadManager(1), ThreadManager::newSimpleThreadManager(1), ThreadManager::newSimpleThreadManager(1), ThreadManager::newSimpleThreadManager(1), ThreadManager::newSimpleThreadManager(1)}); return std::make_shared<SFQThreadManager>(std::move(config)); } }; // Verify tasks are executed at all. TEST_F(SFQThreadManagerTest, SmokeTest) { auto tm = newSFQTM(std::chrono::seconds(1), 1); tm->start(); ThreadManager::ExecutionScope es(PRIORITY::NORMAL); es.setTenantId(123); auto ka = tm->getKeepAlive(std::move(es), ThreadManager::Source::UPSTREAM); EXPECT_CALL(*this, bogusTask(0)).Times(1); ka->add([this]() { this->bogusTask(0); }); } // Ensure the queuing is fair and that higher priority tasks pre-empt low pri. TEST_F(SFQThreadManagerTest, FairnessPreemptTest) { // Disabling perturbation so we can actually test this. auto tm = newSFQTM(std::chrono::seconds(0), 10000); const auto source = ThreadManager::Source::UPSTREAM; tm->start(); // This will dictate the expected order of placing the tasks. std::vector<folly::Baton<>> addOrderBaton(4); std::vector<folly::Baton<>> c0Baton(2), c1Baton(2); size_t c0{0}, c1{0}; ThreadManager::ExecutionScope es(PRIORITY::NORMAL); es.setTenantId(0); tm->getKeepAlive(es, source)->add([&]() { addOrderBaton[0].wait(); ++c0; c0Baton[0].post(); }); es.setTenantId(0); tm->getKeepAlive(es, source)->add([&]() { addOrderBaton[1].wait(); ++c0; c0Baton[1].post(); }); es.setTenantId(1); tm->getKeepAlive(es, source)->add([&]() { addOrderBaton[2].wait(); ++c1; c1Baton[0].post(); }); es.setTenantId(1); tm->getKeepAlive(es, source)->add([&]() { addOrderBaton[3].wait(); ++c1; c1Baton[1].post(); }); // No tasks have run at this point. EXPECT_EQ(0, c0); EXPECT_EQ(0, c1); // Tenant 0 was added first, so we expect this to execute. addOrderBaton[0].post(); c0Baton[0].wait(); EXPECT_EQ(1, c0); EXPECT_EQ(0, c1); // Tenant 1 should be next even though it was added 3rd. Posting the 3rd // add-order baton would lock up here if it were unfair. addOrderBaton[2].post(); c1Baton[0].wait(); EXPECT_EQ(1, c0); EXPECT_EQ(1, c1); // Tenant 0 will then be up next. It was the task added 2nd. addOrderBaton[1].post(); c0Baton[1].wait(); EXPECT_EQ(2, c0); EXPECT_EQ(1, c1); // Tenant 1 would be up next, but let's preempt all this with a higher // priority source. folly::Baton<> hpribaton, hpribatonOuter; es = ThreadManager::ExecutionScope(PRIORITY::HIGH); es.setTenantId(123); tm->getKeepAlive(es, ThreadManager::Source::INTERNAL)->add([&]() { hpribaton.wait(); hpribatonOuter.post(); }); hpribaton.post(); hpribatonOuter.wait(); // Now we should be able to execute the tenant 1 task after the // source-preempted task. addOrderBaton[3].post(); c1Baton[1].wait(); EXPECT_EQ(2, c0); EXPECT_EQ(2, c1); addOrderBaton.clear(); c0Baton.clear(); c1Baton.clear(); } <commit_msg>Instrument SFQThreadManagerTest<commit_after>/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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 <chrono> #include <condition_variable> #include <deque> #include <memory> #include <mutex> #include <random> #include <thread> #include <folly/Synchronized.h> #include <folly/portability/GMock.h> #include <folly/portability/GTest.h> #include <folly/synchronization/Baton.h> #include <thrift/lib/cpp/concurrency/FunctionRunner.h> #include <thrift/lib/cpp/concurrency/SFQThreadManager.h> using namespace apache::thrift::concurrency; using namespace std::literals::chrono_literals; using testing::_; using testing::AnyNumber; using testing::AtLeast; class SFQThreadManagerTest : public testing::Test { public: MOCK_METHOD1(bogusTask, void(int)); protected: std::shared_ptr<ThreadManager> newSFQTM( std::chrono::seconds perturb, size_t numQueues) { SFQThreadManagerConfig config; config.setPerturbInterval(perturb) .setNumFairQueuesForUpstream(numQueues) .setExecutors( {ThreadManager::newSimpleThreadManager(1), ThreadManager::newSimpleThreadManager(1), ThreadManager::newSimpleThreadManager(1), ThreadManager::newSimpleThreadManager(1), ThreadManager::newSimpleThreadManager(1)}); return std::make_shared<SFQThreadManager>(std::move(config)); } }; // Verify tasks are executed at all. TEST_F(SFQThreadManagerTest, SmokeTest) { auto tm = newSFQTM(std::chrono::seconds(1), 1); tm->start(); ThreadManager::ExecutionScope es(PRIORITY::NORMAL); es.setTenantId(123); auto ka = tm->getKeepAlive(std::move(es), ThreadManager::Source::UPSTREAM); EXPECT_CALL(*this, bogusTask(0)).Times(1); ka->add([this]() { this->bogusTask(0); }); } // Ensure the queuing is fair and that higher priority tasks pre-empt low pri. TEST_F(SFQThreadManagerTest, FairnessPreemptTest) { // Disabling perturbation so we can actually test this. auto tm = newSFQTM(std::chrono::seconds(0), 10000); const auto source = ThreadManager::Source::UPSTREAM; tm->start(); // This will dictate the expected order of placing the tasks. std::vector<folly::Baton<>> addOrderBaton(4); std::vector<folly::Baton<>> c0Baton(2), c1Baton(2); size_t c0{0}, c1{0}; ThreadManager::ExecutionScope es(PRIORITY::NORMAL); es.setTenantId(0); tm->getKeepAlive(es, source)->add([&]() { ASSERT_TRUE(addOrderBaton[0].try_wait_for(3s)); ++c0; c0Baton[0].post(); }); es.setTenantId(0); tm->getKeepAlive(es, source)->add([&]() { ASSERT_TRUE(addOrderBaton[1].try_wait_for(3s)); ++c0; c0Baton[1].post(); }); es.setTenantId(1); tm->getKeepAlive(es, source)->add([&]() { ASSERT_TRUE(addOrderBaton[2].try_wait_for(3s)); ++c1; c1Baton[0].post(); }); es.setTenantId(1); tm->getKeepAlive(es, source)->add([&]() { ASSERT_TRUE(addOrderBaton[3].try_wait_for(3s)); ++c1; c1Baton[1].post(); }); // No tasks have run at this point. EXPECT_EQ(0, c0); EXPECT_EQ(0, c1); // Tenant 0 was added first, so we expect this to execute. addOrderBaton[0].post(); ASSERT_TRUE(c0Baton[0].try_wait_for(3s)); EXPECT_EQ(1, c0); EXPECT_EQ(0, c1); // Tenant 1 should be next even though it was added 3rd. Posting the 3rd // add-order baton would lock up here if it were unfair. addOrderBaton[2].post(); ASSERT_TRUE(c1Baton[0].try_wait_for(3s)); EXPECT_EQ(1, c0); EXPECT_EQ(1, c1); // Tenant 0 will then be up next. It was the task added 2nd. addOrderBaton[1].post(); ASSERT_TRUE(c0Baton[1].try_wait_for(3s)); EXPECT_EQ(2, c0); EXPECT_EQ(1, c1); // Tenant 1 would be up next, but let's preempt all this with a higher // priority source. folly::Baton<> hpribaton, hpribatonOuter; es = ThreadManager::ExecutionScope(PRIORITY::HIGH); es.setTenantId(123); tm->getKeepAlive(es, ThreadManager::Source::INTERNAL)->add([&]() { ASSERT_TRUE(hpribaton.try_wait_for(3s)); hpribatonOuter.post(); }); hpribaton.post(); ASSERT_TRUE(hpribatonOuter.try_wait_for(3s)); // Now we should be able to execute the tenant 1 task after the // source-preempted task. addOrderBaton[3].post(); ASSERT_TRUE(c1Baton[1].try_wait_for(3s)); EXPECT_EQ(2, c0); EXPECT_EQ(2, c1); addOrderBaton.clear(); c0Baton.clear(); c1Baton.clear(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved. */ #include <map> #include "db/util/Math.h" #include "db/util/Date.h" #include "db/logging/Logger.h" using namespace std; using namespace db::io; using namespace db::util; using namespace db::logging; std::multimap<const char*, Logger*, Logger::NameComparator> Logger::sLoggers; const char* Logger::defaultCategory = "__DEFAULT__"; const char* Logger::levelToString(Level level) { // FIXME: return an std::string, pass in a buffer that // has to get filled, or heap-allocate and require the user // to delete the return value from this method -- as it stands // this stuff will get stack allocated and then wiped out when // the function returns, resulting in the return value of this // method pointing somewhere unsafe const char* rval; switch(level) { case None: rval = ""; break; case Error: rval = "ERROR"; break; case Warning: rval = "WARNING"; break; case Info: rval = "INFO"; break; case Debug: rval = "DEBUG"; break; case DebugData: rval = "DEBUG-DATA"; break; case DebugDetail: rval = "DEBUG-DETAIL"; break; default: rval = "OTHER"; } return rval; } void Logger::addLogger(Logger* logger, const char* category) { sLoggers.insert(pair<const char*, Logger*>(category, logger)); } void Logger::removeLogger(Logger* logger, const char* category) { // FIXME assert(false); } Logger::Logger(const char* name, Level level) { mName = new char[strlen(name) + 1]; strcpy(mName, name); setLevel(level); mDateFormat = NULL; setDateFormat("%Y-%m-%d %H:%M:%S"); } Logger::~Logger() { delete [] mName; if(mDateFormat != NULL) { delete [] mDateFormat; } } const char* Logger::getName() { return mName; } void Logger::setLevel(Level level) { mLevel = level; } Logger::Level Logger::getLevel() { return mLevel; } void Logger::getDate(string& date) { date.erase(); if(strcmp(mDateFormat, "") == 0) { // shortcut - do nothing } else { // handle other date formats here Date now; date = now.format(date, mDateFormat, "c"); } } bool Logger::setDateFormat(const char* dateFormat) { lock(); { if(mDateFormat != NULL) { delete [] mDateFormat; } mDateFormat = new char[strlen(dateFormat) + 1]; strcpy(mDateFormat, dateFormat); } unlock(); return true; } bool Logger::log( const char* cat, Level level, const char* file, const char* function, int line, const void* object, const char* message) { bool rval = false; if(mLevel >= level) { lock(); // Output as: // [date: ][level: ][cat: ][file:][function:][line: ][object: ]message string logText; string date; getDate(date); if(strcmp(date.c_str(), "") != 0) { logText.append(date); logText.append(": "); } logText.append(levelToString(level)); logText.append(": "); if(cat != NULL && strcmp(cat, defaultCategory) != 0) { logText.append(cat); logText.append(": "); } if(file) { logText.append(file); logText.append(1, ':'); } if(function) { logText.append(function); logText.append(1, ':'); } if(line != -1) { char tmp[21]; snprintf(tmp, 21, "%d", line); logText.append(tmp); logText.append(1, ':'); } if(file || function || line) { logText.append(1, ' '); } if(object) { char tmp[23]; snprintf(tmp, 21, "<%p>", object); logText.append(tmp); logText.append(": "); } logText.append(message); logText.append(1, '\n'); log(logText.c_str()); rval = true; unlock(); } return rval; } void Logger::catLevelLog( const char* cat, Level level, const char* file, const char* function, int line, const void* object, const char* message) { multimap<const char*, Logger*, NameComparator>::iterator i = sLoggers.find(cat); while(i != sLoggers.end()) { Logger* lg = i->second; lg->log(cat, level, file, function, line, object, message); i++; } } #if 0 const char* Logger::getStackTrace(Throwable t) { String rval = "null"; if(t != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.close(); rval = sw.toString(); } return rval; } #endif <commit_msg>Changed loop in catLevelLog() to go to sLoggers.upper_bound() instead of sLoggers.end() for iterating over search results in multimap.<commit_after>/* * Copyright (c) 2007 Digital Bazaar, Inc. All rights reserved. */ #include <map> #include "db/util/Math.h" #include "db/util/Date.h" #include "db/logging/Logger.h" using namespace std; using namespace db::io; using namespace db::util; using namespace db::logging; std::multimap<const char*, Logger*, Logger::NameComparator> Logger::sLoggers; const char* Logger::defaultCategory = "__DEFAULT__"; const char* Logger::levelToString(Level level) { // FIXME: return an std::string, pass in a buffer that // has to get filled, or heap-allocate and require the user // to delete the return value from this method -- as it stands // this stuff will get stack allocated and then wiped out when // the function returns, resulting in the return value of this // method pointing somewhere unsafe const char* rval; switch(level) { case None: rval = ""; break; case Error: rval = "ERROR"; break; case Warning: rval = "WARNING"; break; case Info: rval = "INFO"; break; case Debug: rval = "DEBUG"; break; case DebugData: rval = "DEBUG-DATA"; break; case DebugDetail: rval = "DEBUG-DETAIL"; break; default: rval = "OTHER"; } return rval; } void Logger::addLogger(Logger* logger, const char* category) { sLoggers.insert(pair<const char*, Logger*>(category, logger)); } void Logger::removeLogger(Logger* logger, const char* category) { // FIXME assert(false); } Logger::Logger(const char* name, Level level) { mName = new char[strlen(name) + 1]; strcpy(mName, name); setLevel(level); mDateFormat = NULL; setDateFormat("%Y-%m-%d %H:%M:%S"); } Logger::~Logger() { delete [] mName; if(mDateFormat != NULL) { delete [] mDateFormat; } } const char* Logger::getName() { return mName; } void Logger::setLevel(Level level) { mLevel = level; } Logger::Level Logger::getLevel() { return mLevel; } void Logger::getDate(string& date) { date.erase(); if(strcmp(mDateFormat, "") == 0) { // shortcut - do nothing } else { // handle other date formats here Date now; date = now.format(date, mDateFormat, "c"); } } bool Logger::setDateFormat(const char* dateFormat) { lock(); { if(mDateFormat != NULL) { delete [] mDateFormat; } mDateFormat = new char[strlen(dateFormat) + 1]; strcpy(mDateFormat, dateFormat); } unlock(); return true; } bool Logger::log( const char* cat, Level level, const char* file, const char* function, int line, const void* object, const char* message) { bool rval = false; if(mLevel >= level) { lock(); // Output as: // [date: ][level: ][cat: ][file:][function:][line: ][object: ]message string logText; string date; getDate(date); if(strcmp(date.c_str(), "") != 0) { logText.append(date); logText.append(": "); } logText.append(levelToString(level)); logText.append(": "); if(cat != NULL && strcmp(cat, defaultCategory) != 0) { logText.append(cat); logText.append(": "); } if(file) { logText.append(file); logText.append(1, ':'); } if(function) { logText.append(function); logText.append(1, ':'); } if(line != -1) { char tmp[21]; snprintf(tmp, 21, "%d", line); logText.append(tmp); logText.append(1, ':'); } if(file || function || line) { logText.append(1, ' '); } if(object) { char tmp[23]; snprintf(tmp, 21, "<%p>", object); logText.append(tmp); logText.append(": "); } logText.append(message); logText.append(1, '\n'); log(logText.c_str()); rval = true; unlock(); } return rval; } void Logger::catLevelLog( const char* cat, Level level, const char* file, const char* function, int line, const void* object, const char* message) { multimap<const char*, Logger*, NameComparator>::iterator i = sLoggers.find(cat); if(i != sLoggers.end()) { multimap<const char*, Logger*, NameComparator>::iterator end = sLoggers.upper_bound(cat); for(; i != end; i++) { Logger* lg = i->second; lg->log(cat, level, file, function, line, object, message); } } } #if 0 const char* Logger::getStackTrace(Throwable t) { String rval = "null"; if(t != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); t.printStackTrace(pw); pw.close(); rval = sw.toString(); } return rval; } #endif <|endoftext|>
<commit_before>/* * STDPConn.hpp * * Created on: Jan 28, 2011 * Author: sorenrasmussen */ #ifndef STDPCONN_HPP_ #define STDPCONN_HPP_ #include "HyPerConn.hpp" namespace PV { class STDPConn : HyPerConn { public: STDPConn(); STDPConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, ChannelType channel); virtual ~STDPConn(); virtual int initializeThreadBuffers(); virtual int initializeThreadKernels(); virtual PVPatch * getPlasticityIncrement(int k, int arbor); inline PVLayerCube * getPlasticityDecrement() {return pDecr;} protected: int initialize(); PVLayerCube * pDecr; // plasticity decrement variable (Mi) for post-synaptic layer PVPatch ** pIncr; // list of stdp patches Psij variable bool localWmaxFlag; // presence of rate dependent wMax; pvdata_t * Wmax; // adaptive upper STDP weight boundary // STDP parameters for modifying weights float ampLTP; // long term potentiation amplitude float ampLTD; // long term depression amplitude float tauLTP; float tauLTD; float dWMax; }; } #endif /* STDPCONN_HPP_ */ <commit_msg>Modifications needed to implement STDPConn.<commit_after>/* * STDPConn.hpp * * Created on: Jan 28, 2011 * Author: sorenrasmussen */ #ifndef STDPCONN_HPP_ #define STDPCONN_HPP_ #include "HyPerConn.hpp" #include <stdio.h> namespace PV { class STDPConn : HyPerConn { public: STDPConn(); STDPConn(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, ChannelType channel, const char * filename=NULL); virtual ~STDPConn(); int setParams(PVParams * params); virtual int initializeThreadBuffers(); virtual int initializeThreadKernels(); virtual int deleteWeights(); virtual float maxWeight(); virtual int updateState(float time, float dt); virtual int updateWeights(int axonId); virtual int outputState(float time, bool last=false); virtual int writeTextWeightsExtra(FILE * fd, int k); virtual PVPatch * getPlasticityIncrement(int k, int arbor); virtual PVLayerCube * getPlasticityDecrement(); protected: int initialize(const char * name, HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, ChannelType channel, const char * filename); virtual int adjustAxonalPatches(PVAxonalArbor * arbor, int nxPatch, int nyPatch, int dx, int dy); PVLayerCube * pDecr; // plasticity decrement variable (Mi) for post-synaptic layer PVPatch ** pIncr; // list of stdp patches Psij variable bool stdpFlag; // presence of spike timing dependent plasticity bool localWmaxFlag; // presence of rate dependent wMax; pvdata_t * Wmax; // adaptive upper STDP weight boundary // STDP parameters for modifying weights float ampLTP; // long term potentiation amplitude float ampLTD; // long term depression amplitude float tauLTP; float tauLTD; float dWMax; }; } #endif /* STDPCONN_HPP_ */ <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbStandardShader.h" #include "otbFragmentShaderRegistry.h" #include "otbGlVersionChecker.h" #include <GL/glew.h> namespace otb { StandardShader::StandardShader() : m_LocalContrastRange( 50 ), m_SpectralAngleRange( 10 ), m_Center(), m_Radius( 200 ), m_ChessboardSize( 256 ), m_SliderPosition( 500 ), m_VerticalSlider( false ), m_ShaderType( SHADER_STANDARD ) { m_Center.Fill( 0 ); BuildShader(); } StandardShader::~StandardShader() {} std::string StandardShader::GetSource() const { const char * glVersion = NULL; const char * glslVersion = NULL; if(!otb::GlVersionChecker::CheckGLCapabilities( glVersion, glslVersion)) { itkExceptionMacro(<<" Required GL and GLSL versions were not found (GL version is "<<glVersion<<", should be at least "<<otb::GlVersionChecker::REQUIRED_GL_VERSION<<", GLSL version is "<<glslVersion<<", should be at least "<<otb::GlVersionChecker::REQUIRED_GLSL_VERSION<<")"); } bool isGLSLS140Available = otb::GlVersionChecker::VerCmp(glslVersion,"1.40")>=0; std::string shader_source = ""; if(isGLSLS140Available) { shader_source+="#version 140 \n"; } else { shader_source+="#version 130 \n"; } shader_source = "uniform sampler2D src;\n" \ "uniform vec4 shader_a;\n" \ "uniform vec4 shader_b;\n" \ "uniform int shader_use_no_data;\n" \ "uniform float shader_no_data;\n" \ "uniform vec3 shader_current;\n" \ "uniform vec4 shader_gamma;\n" \ "uniform float shader_alpha;\n" \ "uniform vec2 shader_center;\n" \ "uniform int shader_type;\n" \ "uniform float shader_radius;\n" \ "uniform float shader_localc_range;\n" \ "uniform float shader_spectral_angle_range;\n" \ "uniform float shader_chessboard_size;\n" \ "uniform float shader_slider_pos;\n" \ "uniform int shader_vertical_slider_flag;\n" \ "void main (void) {\n" \ "vec4 p = texture2D(src, gl_TexCoord[0].xy);\n" \ "gl_FragColor = clamp(pow((p+shader_b)*shader_a,shader_gamma), 0.0, 1.0);\n" \ "gl_FragColor[3] = clamp(shader_alpha,0.0,1.0);\n" \ "if(shader_use_no_data > 0 && vec3(p) == vec3(shader_no_data)){\n" \ "gl_FragColor[3] = 0.;\n" \ "}\n" \ "float alpha = gl_FragColor[3];\n" \ "float dist = distance(gl_FragCoord.xy,shader_center);\n" \ "if(shader_type == 1)\n" \ "{\n" \ "if(dist < shader_radius)\n" \ "{\n" \ "vec3 tmp = clamp((vec3(p)-vec3(shader_current)+vec3(shader_localc_range))/(2.*vec3(shader_localc_range)),0.0,1.0);\n" \ "gl_FragColor[0] = tmp[0];\n" \ "gl_FragColor[1] = tmp[1];\n" \ "gl_FragColor[2] = tmp[2];\n" \ "gl_FragColor[3] = alpha;\n" \ "}\n" \ "}\n" \ "else if(shader_type == 2)" \ "{\n" \ "gl_FragColor[3] = dist > shader_radius ? 1.0 : 0.0; \n" \ "}\n" \ "else if(shader_type == 3)\n" \ "{\n" \ "float alpha = (mod(floor(gl_FragCoord.x / shader_chessboard_size), 2.0) == 0.) != (mod(floor(gl_FragCoord.y / shader_chessboard_size), 2.0) == 1.) ? shader_alpha : 0.0;\n" \ "gl_FragColor[3] = clamp(alpha,0.0,1.0);\n" \ "}\n" \ "else if(shader_type == 4)\n" \ "{\n" \ "float alpha = (shader_vertical_slider_flag == 0 && gl_FragCoord.x > shader_slider_pos) || (shader_vertical_slider_flag == 1 && gl_FragCoord.y > shader_slider_pos) ? 1.0 : 0.0;\n" \ "gl_FragColor[3] = clamp(alpha,0.0,1.0);\n" \ "}\n" \ "else if(shader_type == 5)\n" \ "{\n" \ "if(dist < shader_radius)\n" \ "{\n" \ "float angle = acos(clamp(dot(vec3(p),shader_current)/(length(vec3(p))*length(shader_current)),-1.0,1.0));\n" \ "vec3 tmp = clamp(vec3(1.-shader_spectral_angle_range*abs(angle)/3.142),0.0,1.0);\n" \ "gl_FragColor[0] = tmp[0];\n" \ "gl_FragColor[1] = tmp[1];\n" \ "gl_FragColor[2] = tmp[2];\n" \ "gl_FragColor[3] = alpha;\n" \ "}\n" \ "}\n"; if(isGLSLS140Available) { shader_source+= "else if(shader_type == 6)\n" \ "{\n" \ "if(dist < shader_radius)\n" \ "{\n" \ "vec2 size = vec2(textureSize(src,0));\n" \ "vec2 dx = vec2(gl_TexCoord[0].xy);\n" \ "dx[0]+=1.0/size[0];\n" \ "vec2 dy = vec2(gl_TexCoord[0].xy);\n" \ "dy[1]+=1.0/size[1];\n" \ "vec4 pdx = texture2D(src, dx);\n" \ "vec4 pdy = texture2D(src, dy);\n" \ "gl_FragColor = clamp(pow(5*shader_a*(0.5*abs((pdx-p))+ 0.5*abs((pdy-p))),shader_gamma),0.0,1.0);\n" \ "gl_FragColor[3] = alpha;\n" \ "}\n" \ "}\n"; } shader_source+="}"; return shader_source; } std::string StandardShader::GetName() const { return "StandardShader"; } void StandardShader::SetupShader() { assert( !m_ImageSettings.IsNull() ); // // Compute shifts. double shr = -m_ImageSettings->GetMinRed(); double shg = -m_ImageSettings->GetMinGreen(); double shb = -m_ImageSettings->GetMinBlue(); // // Compute scales. double scr = 1.0 / ( m_ImageSettings->GetMaxRed()+shr ); double scg = 1.0 / ( m_ImageSettings->GetMaxGreen()+shg ); double scb = 1.0 / ( m_ImageSettings->GetMaxBlue()+shb ); double gamma = m_ImageSettings->GetGamma(); GLint shader_a = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_a"); glUniform4f(shader_a,scr,scg,scb,1.); GLint shader_b = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_b"); glUniform4f(shader_b,shr,shg,shb,0); GLint shader_use_no_data = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_use_no_data"); glUniform1i(shader_use_no_data, m_ImageSettings->GetUseNoData() ); GLint shader_no_data = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_no_data"); glUniform1f( shader_no_data, m_ImageSettings->GetNoData() ); GLint shader_gamma = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_gamma"); glUniform4f( shader_gamma, gamma, gamma, gamma, gamma ); GLint shader_alpha = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_alpha"); glUniform1f( shader_alpha, m_ImageSettings->GetAlpha() ); GLint shader_radius = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_radius"); glUniform1f(shader_radius,m_Radius); GLint shader_center = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_center"); glUniform2f(shader_center,m_Center[0],m_Center[1]); GLint shader_type = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_type"); glUniform1i(shader_type,m_ShaderType); // std::cout // << "r: " << m_ImageSettings->GetCurrentRed() // << " g: " << m_ImageSettings->GetCurrentGreen() // << " b: " << m_ImageSettings->GetCurrentBlue() // << std::endl; GLint shader_current = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_current"); glUniform3f( shader_current, m_ImageSettings->GetCurrentRed(), m_ImageSettings->GetCurrentGreen(), m_ImageSettings->GetCurrentBlue() ); GLint shader_localc_range = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_localc_range"); glUniform1f(shader_localc_range,m_LocalContrastRange); GLint shader_spectral_angle_range = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_spectral_angle_range"); glUniform1f(shader_spectral_angle_range,m_SpectralAngleRange); GLint shader_chessboard_size = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_chessboard_size"); glUniform1f(shader_chessboard_size,m_ChessboardSize); GLint shader_slider_pos = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_slider_pos"); glUniform1f(shader_slider_pos,m_SliderPosition); GLint shader_vertical_slider_flag = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_vertical_slider_flag"); glUniform1i(shader_vertical_slider_flag,m_VerticalSlider); } } // End namespace otb <commit_msg>COMP: Added missing include header-file.<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbStandardShader.h" #include <cassert> #include <GL/glew.h> #include "otbFragmentShaderRegistry.h" #include "otbGlVersionChecker.h" namespace otb { StandardShader::StandardShader() : m_LocalContrastRange( 50 ), m_SpectralAngleRange( 10 ), m_Center(), m_Radius( 200 ), m_ChessboardSize( 256 ), m_SliderPosition( 500 ), m_VerticalSlider( false ), m_ShaderType( SHADER_STANDARD ) { m_Center.Fill( 0 ); BuildShader(); } StandardShader::~StandardShader() {} std::string StandardShader::GetSource() const { const char * glVersion = NULL; const char * glslVersion = NULL; if(!otb::GlVersionChecker::CheckGLCapabilities( glVersion, glslVersion)) { itkExceptionMacro(<<" Required GL and GLSL versions were not found (GL version is "<<glVersion<<", should be at least "<<otb::GlVersionChecker::REQUIRED_GL_VERSION<<", GLSL version is "<<glslVersion<<", should be at least "<<otb::GlVersionChecker::REQUIRED_GLSL_VERSION<<")"); } bool isGLSLS140Available = otb::GlVersionChecker::VerCmp(glslVersion,"1.40")>=0; std::string shader_source = ""; if(isGLSLS140Available) { shader_source+="#version 140 \n"; } else { shader_source+="#version 130 \n"; } shader_source = "uniform sampler2D src;\n" \ "uniform vec4 shader_a;\n" \ "uniform vec4 shader_b;\n" \ "uniform int shader_use_no_data;\n" \ "uniform float shader_no_data;\n" \ "uniform vec3 shader_current;\n" \ "uniform vec4 shader_gamma;\n" \ "uniform float shader_alpha;\n" \ "uniform vec2 shader_center;\n" \ "uniform int shader_type;\n" \ "uniform float shader_radius;\n" \ "uniform float shader_localc_range;\n" \ "uniform float shader_spectral_angle_range;\n" \ "uniform float shader_chessboard_size;\n" \ "uniform float shader_slider_pos;\n" \ "uniform int shader_vertical_slider_flag;\n" \ "void main (void) {\n" \ "vec4 p = texture2D(src, gl_TexCoord[0].xy);\n" \ "gl_FragColor = clamp(pow((p+shader_b)*shader_a,shader_gamma), 0.0, 1.0);\n" \ "gl_FragColor[3] = clamp(shader_alpha,0.0,1.0);\n" \ "if(shader_use_no_data > 0 && vec3(p) == vec3(shader_no_data)){\n" \ "gl_FragColor[3] = 0.;\n" \ "}\n" \ "float alpha = gl_FragColor[3];\n" \ "float dist = distance(gl_FragCoord.xy,shader_center);\n" \ "if(shader_type == 1)\n" \ "{\n" \ "if(dist < shader_radius)\n" \ "{\n" \ "vec3 tmp = clamp((vec3(p)-vec3(shader_current)+vec3(shader_localc_range))/(2.*vec3(shader_localc_range)),0.0,1.0);\n" \ "gl_FragColor[0] = tmp[0];\n" \ "gl_FragColor[1] = tmp[1];\n" \ "gl_FragColor[2] = tmp[2];\n" \ "gl_FragColor[3] = alpha;\n" \ "}\n" \ "}\n" \ "else if(shader_type == 2)" \ "{\n" \ "gl_FragColor[3] = dist > shader_radius ? 1.0 : 0.0; \n" \ "}\n" \ "else if(shader_type == 3)\n" \ "{\n" \ "float alpha = (mod(floor(gl_FragCoord.x / shader_chessboard_size), 2.0) == 0.) != (mod(floor(gl_FragCoord.y / shader_chessboard_size), 2.0) == 1.) ? shader_alpha : 0.0;\n" \ "gl_FragColor[3] = clamp(alpha,0.0,1.0);\n" \ "}\n" \ "else if(shader_type == 4)\n" \ "{\n" \ "float alpha = (shader_vertical_slider_flag == 0 && gl_FragCoord.x > shader_slider_pos) || (shader_vertical_slider_flag == 1 && gl_FragCoord.y > shader_slider_pos) ? 1.0 : 0.0;\n" \ "gl_FragColor[3] = clamp(alpha,0.0,1.0);\n" \ "}\n" \ "else if(shader_type == 5)\n" \ "{\n" \ "if(dist < shader_radius)\n" \ "{\n" \ "float angle = acos(clamp(dot(vec3(p),shader_current)/(length(vec3(p))*length(shader_current)),-1.0,1.0));\n" \ "vec3 tmp = clamp(vec3(1.-shader_spectral_angle_range*abs(angle)/3.142),0.0,1.0);\n" \ "gl_FragColor[0] = tmp[0];\n" \ "gl_FragColor[1] = tmp[1];\n" \ "gl_FragColor[2] = tmp[2];\n" \ "gl_FragColor[3] = alpha;\n" \ "}\n" \ "}\n"; if(isGLSLS140Available) { shader_source+= "else if(shader_type == 6)\n" \ "{\n" \ "if(dist < shader_radius)\n" \ "{\n" \ "vec2 size = vec2(textureSize(src,0));\n" \ "vec2 dx = vec2(gl_TexCoord[0].xy);\n" \ "dx[0]+=1.0/size[0];\n" \ "vec2 dy = vec2(gl_TexCoord[0].xy);\n" \ "dy[1]+=1.0/size[1];\n" \ "vec4 pdx = texture2D(src, dx);\n" \ "vec4 pdy = texture2D(src, dy);\n" \ "gl_FragColor = clamp(pow(5*shader_a*(0.5*abs((pdx-p))+ 0.5*abs((pdy-p))),shader_gamma),0.0,1.0);\n" \ "gl_FragColor[3] = alpha;\n" \ "}\n" \ "}\n"; } shader_source+="}"; return shader_source; } std::string StandardShader::GetName() const { return "StandardShader"; } void StandardShader::SetupShader() { assert( !m_ImageSettings.IsNull() ); // // Compute shifts. double shr = -m_ImageSettings->GetMinRed(); double shg = -m_ImageSettings->GetMinGreen(); double shb = -m_ImageSettings->GetMinBlue(); // // Compute scales. double scr = 1.0 / ( m_ImageSettings->GetMaxRed()+shr ); double scg = 1.0 / ( m_ImageSettings->GetMaxGreen()+shg ); double scb = 1.0 / ( m_ImageSettings->GetMaxBlue()+shb ); double gamma = m_ImageSettings->GetGamma(); GLint shader_a = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_a"); glUniform4f(shader_a,scr,scg,scb,1.); GLint shader_b = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_b"); glUniform4f(shader_b,shr,shg,shb,0); GLint shader_use_no_data = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_use_no_data"); glUniform1i(shader_use_no_data, m_ImageSettings->GetUseNoData() ); GLint shader_no_data = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_no_data"); glUniform1f( shader_no_data, m_ImageSettings->GetNoData() ); GLint shader_gamma = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_gamma"); glUniform4f( shader_gamma, gamma, gamma, gamma, gamma ); GLint shader_alpha = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_alpha"); glUniform1f( shader_alpha, m_ImageSettings->GetAlpha() ); GLint shader_radius = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_radius"); glUniform1f(shader_radius,m_Radius); GLint shader_center = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_center"); glUniform2f(shader_center,m_Center[0],m_Center[1]); GLint shader_type = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_type"); glUniform1i(shader_type,m_ShaderType); // std::cout // << "r: " << m_ImageSettings->GetCurrentRed() // << " g: " << m_ImageSettings->GetCurrentGreen() // << " b: " << m_ImageSettings->GetCurrentBlue() // << std::endl; GLint shader_current = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_current"); glUniform3f( shader_current, m_ImageSettings->GetCurrentRed(), m_ImageSettings->GetCurrentGreen(), m_ImageSettings->GetCurrentBlue() ); GLint shader_localc_range = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_localc_range"); glUniform1f(shader_localc_range,m_LocalContrastRange); GLint shader_spectral_angle_range = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_spectral_angle_range"); glUniform1f(shader_spectral_angle_range,m_SpectralAngleRange); GLint shader_chessboard_size = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_chessboard_size"); glUniform1f(shader_chessboard_size,m_ChessboardSize); GLint shader_slider_pos = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_slider_pos"); glUniform1f(shader_slider_pos,m_SliderPosition); GLint shader_vertical_slider_flag = glGetUniformLocation(otb::FragmentShaderRegistry::Instance()->GetShaderProgram("StandardShader"), "shader_vertical_slider_flag"); glUniform1i(shader_vertical_slider_flag,m_VerticalSlider); } } // End namespace otb <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2012. All rights reserved */ #include "../StroikaPreComp.h" #include "Event.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; /* * Design notes: * * o The use of condition variables is non-obvious. I haven't found good documentation, but * the best I've found would be * https://computing.llnl.gov/tutorials/pthreads/#ConVarOverview * * In particular, on the surface, it looks like the mutex locks in Wait() and signal should prevent things * form working (deadlock). But they apparently do not cause a deadlock because * "pthread_cond_wait() blocks the calling thread until the specified condition is signalled. * This routine should be called while mutex is locked, and it will automatically release the * mutex while it waits. After signal is received and thread is awakened, mutex will be * automatically locked for use by the thread. The programmer is then responsible for * unlocking mutex when the thread is finished with it." * */ /* * TODO: * o POSIX/C++ code below on wait is a bit of a KLUGE. Unclear if it was a red-herring or * osmething like that needed. Review once threading stuff stable. * -- LGP 2011-10-27 * NB: its been working and stable for quite a while. It could use cleanup/docs (working on that). * and the timeout part maybe wrong (esp with signals). But it appears to mostly be * correct. */ /* ******************************************************************************** ************************************** Event *********************************** ******************************************************************************** */ #if qTrack_ThreadUtils_HandleCounts uint32_t Event::sCurAllocatedHandleCount = 0; #endif void Event::Wait (Time::DurationSecondsType timeout) { //Debug::TraceContextBumper ctx (TSTR ("Event::Wait")); //DbgTrace ("(timeout = %.2f)", timeout); CheckForThreadAborting (); #if qPlatform_Windows AssertNotNull (fEventHandle); // must be careful about rounding errors in int->DurationSecondsType->int Again: DWORD result = ::WaitForSingleObjectEx (fEventHandle, Platform::Windows::Duration2Milliseconds (timeout), true); switch (result) { case WAIT_TIMEOUT: DoThrow (WaitTimedOutException ()); case WAIT_ABANDONED: DoThrow (WaitAbandonedException ()); case WAIT_IO_COMPLETION: CheckForThreadAborting (); goto Again; // roughly right to goto again - should decrement timeout- APC other than for abort - we should just keep waiting } Verify (result == WAIT_OBJECT_0); #elif qUseThreads_StdCPlusPlus std::unique_lock<std::mutex> lock (fMutex_); Time::DurationSecondsType until = Time::GetTickCount () + timeout; Assert (until >= timeout); // so no funny overflow issues... /* * The reason for the loop is that fConditionVariable_.wait_for() can return for things like errno==EINTR, * but must keep waiting. wait_for () returns no_timeout if for a real reason (notify called) OR spurrious. */ while (not fTriggered_) { CheckForThreadAborting (); Time::DurationSecondsType remaining = until - Time::GetTickCount (); if (remaining < 0) { DoThrow (WaitTimedOutException ()); } if (fConditionVariable_.wait_for (lock, std::chrono::duration<double> (remaining)) == std::cv_status::timeout) { DoThrow (WaitTimedOutException ()); } } fTriggered_ = false ; // autoreset #else AssertNotImplemented (); #endif } <commit_msg>Slight cleanup of UNIX/std:c++ cond-variable Wait code - including BWA (hopefully temporary) for interupt issue with thread/abort in threadpool code<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2012. All rights reserved */ #include "../StroikaPreComp.h" #include "../Time/Duration.h" #include "Event.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; using Stroika::Foundation::Time::Duration; /* * Design notes: * * o The use of condition variables is non-obvious. I haven't found good documentation, but * the best I've found would be * https://computing.llnl.gov/tutorials/pthreads/#ConVarOverview * * In particular, on the surface, it looks like the mutex locks in Wait() and signal should prevent things * form working (deadlock). But they apparently do not cause a deadlock because * "pthread_cond_wait() blocks the calling thread until the specified condition is signalled. * This routine should be called while mutex is locked, and it will automatically release the * mutex while it waits. After signal is received and thread is awakened, mutex will be * automatically locked for use by the thread. The programmer is then responsible for * unlocking mutex when the thread is finished with it." * */ /* * TODO: * o POSIX/C++ code below on wait is a bit of a KLUGE. Unclear if it was a red-herring or * osmething like that needed. Review once threading stuff stable. * -- LGP 2011-10-27 * NB: its been working and stable for quite a while. It could use cleanup/docs (working on that). * and the timeout part maybe wrong (esp with signals). But it appears to mostly be * correct. */ /* ******************************************************************************** ************************************** Event *********************************** ******************************************************************************** */ #if qTrack_ThreadUtils_HandleCounts uint32_t Event::sCurAllocatedHandleCount = 0; #endif void Event::Wait (Time::DurationSecondsType timeout) { //Debug::TraceContextBumper ctx (TSTR ("Event::Wait")); //DbgTrace ("(timeout = %.2f)", timeout); CheckForThreadAborting (); #if qPlatform_Windows AssertNotNull (fEventHandle); // must be careful about rounding errors in int->DurationSecondsType->int Again: DWORD result = ::WaitForSingleObjectEx (fEventHandle, Platform::Windows::Duration2Milliseconds (timeout), true); switch (result) { case WAIT_TIMEOUT: DoThrow (WaitTimedOutException ()); case WAIT_ABANDONED: DoThrow (WaitAbandonedException ()); case WAIT_IO_COMPLETION: CheckForThreadAborting (); goto Again; // roughly right to goto again - should decrement timeout- APC other than for abort - we should just keep waiting } Verify (result == WAIT_OBJECT_0); #elif qUseThreads_StdCPlusPlus std::unique_lock<std::mutex> lock (fMutex_); Time::DurationSecondsType until = Time::GetTickCount () + timeout; Assert (until >= timeout); // so no funny overflow issues... /* * The reason for the loop is that fConditionVariable_.wait_for() can return for things like errno==EINTR, * but must keep waiting. wait_for () returns no_timeout if for a real reason (notify called) OR spurrious. */ while (not fTriggered_) { CheckForThreadAborting (); Time::DurationSecondsType remaining = until - Time::GetTickCount (); if (remaining < 0) { DoThrow (WaitTimedOutException ()); } // avoid roundoff issues - and not a big deal to wakeup and wait again once a day ;-) const Time::DurationSecondsType k1Day = Time::DurationSecondsType (60 * 60 * 24); if (remaining >= k1Day) { remaining = k1Day; } // hack needed for theadpool test??? Because Abort_ isn't interupting its WAIT // -- LGP 2012-05-26 #if 1 if (remaining > 5) { remaining = 5; } #endif if (fConditionVariable_.wait_for (lock, Time::Duration (remaining).As<std::chrono::duration<double>> ()) == std::cv_status::timeout) { // No need for this, since could be caught next time through the loop... // And it interferes with the bounding of the 'remaining' count used to avoid overflows // DoThrow (WaitTimedOutException ()); } } fTriggered_ = false ; // autoreset #else AssertNotImplemented (); #endif } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSortByImagePositionPatient.h" #include "mitkDICOMTag.h" mitk::SortByImagePositionPatient ::SortByImagePositionPatient(DICOMSortCriterion::Pointer secondaryCriterion) :DICOMSortCriterion(secondaryCriterion) { } mitk::SortByImagePositionPatient ::~SortByImagePositionPatient() { } mitk::SortByImagePositionPatient ::SortByImagePositionPatient(const SortByImagePositionPatient& other ) :DICOMSortCriterion(other) { } mitk::SortByImagePositionPatient& mitk::SortByImagePositionPatient ::operator=(const SortByImagePositionPatient& other) { if (this != &other) { DICOMSortCriterion::operator=(other); } return *this; } mitk::DICOMTagList mitk::SortByImagePositionPatient ::GetTagsOfInterest() const { DICOMTagList tags; tags.push_back( DICOMTag(0x0020, 0x0032) ); // ImagePositionPatient tags.push_back( DICOMTag(0x0020, 0x0037) ); // ImageOrientationPatient return tags; } bool mitk::SortByImagePositionPatient ::IsLeftBeforeRight(const mitk::DICOMDatasetAccess* left, const mitk::DICOMDatasetAccess* right) const { // sort by distance to world origin, assuming (almost) equal orientation static const DICOMTag tagImagePositionPatient = DICOMTag(0x0020,0x0032); // Image Position (Patient) static const DICOMTag tagImageOrientation = DICOMTag(0x0020, 0x0037); // Image Orientation static Vector3D leftRight; leftRight.Fill(0.0); static Vector3D leftUp; leftUp.Fill(0.0); static bool leftHasOrientation(false); DICOMStringToOrientationVectors( left->GetTagValueAsString( tagImageOrientation ), leftRight, leftUp, leftHasOrientation ); static Vector3D rightRight; rightRight.Fill(0.0); static Vector3D rightUp; rightUp.Fill(0.0); static bool rightHasOrientation(false); DICOMStringToOrientationVectors( right->GetTagValueAsString( tagImageOrientation ), rightRight, rightUp, rightHasOrientation ); static Point3D leftOrigin; leftOrigin.Fill(0.0f); static bool leftHasOrigin(false); leftOrigin = DICOMStringToPoint3D( left->GetTagValueAsString( tagImagePositionPatient ), leftHasOrigin ); static Point3D rightOrigin; rightOrigin.Fill(0.0f); static bool rightHasOrigin(false); rightOrigin = DICOMStringToPoint3D( right->GetTagValueAsString( tagImagePositionPatient ), rightHasOrigin ); // we tolerate very small differences in image orientation, since we got to know about // acquisitions where these values change across a single series (7th decimal digit) // (http://bugs.mitk.org/show_bug.cgi?id=12263) // still, we want to check if our assumption of 'almost equal' orientations is valid for (unsigned int dim = 0; dim < 3; ++dim) { if ( fabs(leftRight[dim] - rightRight[dim]) > 0.0001 || fabs(leftUp[dim] - rightUp[dim]) > 0.0001) { MITK_ERROR << "Dicom images have different orientations."; throw std::logic_error("Dicom images have different orientations. Call GetSeries() first to separate images."); } } static Vector3D normal; normal[0] = leftRight[1] * leftUp[5] - leftRight[2] * leftUp[4]; normal[1] = leftRight[2] * leftUp[3] - leftRight[0] * leftUp[5]; normal[2] = leftRight[0] * leftUp[4] - leftRight[1] * leftUp[3]; static double leftDistance = 0.0; static double rightDistance = 0.0; leftDistance = 0.0; rightDistance = 0.0; // this computes the distance from world origin (0,0,0) ALONG THE NORMAL of the image planes for (unsigned int dim = 0; dim < 3; ++dim) { leftDistance += normal[dim] * leftOrigin[dim]; rightDistance += normal[dim] * rightOrigin[dim]; } // if we can sort by just comparing the distance, we do exactly that if ( fabs(leftDistance - rightDistance) >= mitk::eps) { // default: compare position return leftDistance < rightDistance; } else { return this->NextLevelIsLeftBeforeRight(left, right); } } <commit_msg>Fix image position sorting (formerly: wrong indices used)<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSortByImagePositionPatient.h" #include "mitkDICOMTag.h" mitk::SortByImagePositionPatient ::SortByImagePositionPatient(DICOMSortCriterion::Pointer secondaryCriterion) :DICOMSortCriterion(secondaryCriterion) { } mitk::SortByImagePositionPatient ::~SortByImagePositionPatient() { } mitk::SortByImagePositionPatient ::SortByImagePositionPatient(const SortByImagePositionPatient& other ) :DICOMSortCriterion(other) { } mitk::SortByImagePositionPatient& mitk::SortByImagePositionPatient ::operator=(const SortByImagePositionPatient& other) { if (this != &other) { DICOMSortCriterion::operator=(other); } return *this; } mitk::DICOMTagList mitk::SortByImagePositionPatient ::GetTagsOfInterest() const { DICOMTagList tags; tags.push_back( DICOMTag(0x0020, 0x0032) ); // ImagePositionPatient tags.push_back( DICOMTag(0x0020, 0x0037) ); // ImageOrientationPatient return tags; } bool mitk::SortByImagePositionPatient ::IsLeftBeforeRight(const mitk::DICOMDatasetAccess* left, const mitk::DICOMDatasetAccess* right) const { // sort by distance to world origin, assuming (almost) equal orientation static const DICOMTag tagImagePositionPatient = DICOMTag(0x0020,0x0032); // Image Position (Patient) static const DICOMTag tagImageOrientation = DICOMTag(0x0020, 0x0037); // Image Orientation static Vector3D leftRight; leftRight.Fill(0.0); static Vector3D leftUp; leftUp.Fill(0.0); static bool leftHasOrientation(false); DICOMStringToOrientationVectors( left->GetTagValueAsString( tagImageOrientation ), leftRight, leftUp, leftHasOrientation ); static Vector3D rightRight; rightRight.Fill(0.0); static Vector3D rightUp; rightUp.Fill(0.0); static bool rightHasOrientation(false); DICOMStringToOrientationVectors( right->GetTagValueAsString( tagImageOrientation ), rightRight, rightUp, rightHasOrientation ); static Point3D leftOrigin; leftOrigin.Fill(0.0f); static bool leftHasOrigin(false); leftOrigin = DICOMStringToPoint3D( left->GetTagValueAsString( tagImagePositionPatient ), leftHasOrigin ); static Point3D rightOrigin; rightOrigin.Fill(0.0f); static bool rightHasOrigin(false); rightOrigin = DICOMStringToPoint3D( right->GetTagValueAsString( tagImagePositionPatient ), rightHasOrigin ); // we tolerate very small differences in image orientation, since we got to know about // acquisitions where these values change across a single series (7th decimal digit) // (http://bugs.mitk.org/show_bug.cgi?id=12263) // still, we want to check if our assumption of 'almost equal' orientations is valid for (unsigned int dim = 0; dim < 3; ++dim) { if ( fabs(leftRight[dim] - rightRight[dim]) > 0.0001 || fabs(leftUp[dim] - rightUp[dim]) > 0.0001) { MITK_ERROR << "Dicom images have different orientations."; throw std::logic_error("Dicom images have different orientations. Call GetSeries() first to separate images."); } } static Vector3D normal; normal[0] = leftRight[1] * leftUp[2] - leftRight[2] * leftUp[1]; normal[1] = leftRight[2] * leftUp[0] - leftRight[0] * leftUp[2]; normal[2] = leftRight[0] * leftUp[1] - leftRight[1] * leftUp[0]; static double leftDistance = 0.0; static double rightDistance = 0.0; leftDistance = 0.0; rightDistance = 0.0; // this computes the distance from world origin (0,0,0) ALONG THE NORMAL of the image planes for (unsigned int dim = 0; dim < 3; ++dim) { leftDistance += normal[dim] * leftOrigin[dim]; rightDistance += normal[dim] * rightOrigin[dim]; } // if we can sort by just comparing the distance, we do exactly that if ( fabs(leftDistance - rightDistance) >= mitk::eps) { // default: compare position return leftDistance < rightDistance; } else { return this->NextLevelIsLeftBeforeRight(left, right); } } <|endoftext|>
<commit_before>/* * Copyright 2002-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. */ /* * XSEC * * XSECCryptoUtils:= Helper crypo utilities that make life easier * * Author(s): Berin Lautenbach * * $Id$ * */ #include <xsec/framework/XSECDefs.hpp> #include <xsec/framework/XSECError.hpp> #include <xsec/enc/XSECCryptoUtils.hpp> #include <xsec/enc/XSECCryptoKeyHMAC.hpp> #include <xsec/utils/XSECPlatformUtils.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/XMLString.hpp> XERCES_CPP_NAMESPACE_USE // -------------------------------------------------------------------------------- // XKMS Limited-Use Shared Secret handling // -------------------------------------------------------------------------------- int CleanXKMSPassPhrase(unsigned char * input, int inputLen, safeBuffer &output) { int j = 0; unsigned char c; for (int i = 0; i < inputLen; ++i) { c = input[i]; if (c >= 'A' && c <= 'Z') { output[j++] = c - 'A' + 'a'; } else if (c != '\n' && c != '\r' && c != '\t' && c != ' ') { output[j++] = c; } } return j; } int DSIG_EXPORT CalculateXKMSAuthenticationKey(unsigned char * input, int inputLen, unsigned char * output, int maxOutputLen) { unsigned char keyVal[] = {XKMSAuthenticationValue}; XSECCryptoKeyHMAC * k = XSECPlatformUtils::g_cryptoProvider->keyHMAC(); Janitor<XSECCryptoKeyHMAC> j_k(k); k->setKey(keyVal, 1); XSECCryptoHash *h = XSECPlatformUtils::g_cryptoProvider->hashHMACSHA1(); Janitor<XSECCryptoHash> j_h(h); h->setKey(k); // Clean the input safeBuffer sb; int l = CleanXKMSPassPhrase(input, inputLen, sb); h->hash((unsigned char *) sb.rawBuffer(), l); return h->finish(output, maxOutputLen); } int DSIG_EXPORT CalculateXKMSRevocationCodeIdentifierEncoding1(unsigned char * input, int inputLen, unsigned char * output, int maxOutputLen) { unsigned char keyVal[] = {XKMSRevocationCodeIdenfitierEncoding1}; XSECCryptoKeyHMAC * k = XSECPlatformUtils::g_cryptoProvider->keyHMAC(); Janitor<XSECCryptoKeyHMAC> j_k(k); k->setKey(keyVal, 1); XSECCryptoHash *h = XSECPlatformUtils::g_cryptoProvider->hashHMACSHA1(); Janitor<XSECCryptoHash> j_h(h); h->setKey(k); // Clean the input safeBuffer sb; int l = CleanXKMSPassPhrase(input, inputLen, sb); h->hash((unsigned char *) sb.rawBuffer(), l); return h->finish(output, maxOutputLen); } int DSIG_EXPORT CalculateXKMSRevocationCodeIdentifierEncoding2(unsigned char * input, int inputLen, unsigned char * output, int maxOutputLen) { unsigned char tmpBuf[XSEC_MAX_HASH_SIZE]; int tmpLen = CalculateXKMSRevocationCodeIdentifierEncoding1(input, inputLen, tmpBuf, XSEC_MAX_HASH_SIZE); return CalculateXKMSRevocationCodeIdentifierEncoding2From1(tmpBuf, tmpLen, output, maxOutputLen); } int DSIG_EXPORT CalculateXKMSRevocationCodeIdentifierEncoding2From1(unsigned char * input, int inputLen, unsigned char * output, int maxOutputLen) { unsigned char keyVal[] = {XKMSRevocationCodeIdenfitierEncoding2}; XSECCryptoKeyHMAC * k = XSECPlatformUtils::g_cryptoProvider->keyHMAC(); Janitor<XSECCryptoKeyHMAC> j_k(k); k->setKey(keyVal, 1); XSECCryptoHash *h = XSECPlatformUtils::g_cryptoProvider->hashHMACSHA1(); Janitor<XSECCryptoHash> j_h(h); h->setKey(k); h->hash(input, inputLen); return h->finish(output, maxOutputLen); } int DSIG_EXPORT CalculateXKMSKEK(unsigned char * input, int inputLen, unsigned char * output, int maxOutputLen) { unsigned char keyVal[] = {XKMSKeyEncryption}; XSECCryptoKeyHMAC * k = XSECPlatformUtils::g_cryptoProvider->keyHMAC(); k->setKey(keyVal, 1); XSECCryptoHash *h = XSECPlatformUtils::g_cryptoProvider->hashHMACSHA1(); Janitor<XSECCryptoHash> j_h(h); h->setKey(k); // Clean the input safeBuffer sb; int l = CleanXKMSPassPhrase(input, inputLen, sb); h->hash((unsigned char *) sb.rawBuffer(), l); return h->finish(output, maxOutputLen); } // -------------------------------------------------------------------------------- // Some Base64 helpers // -------------------------------------------------------------------------------- XMLCh DSIG_EXPORT * EncodeToBase64XMLCh(unsigned char * input, int inputLen) { XSECCryptoBase64 * b64 = XSECPlatformUtils::g_cryptoProvider->base64(); Janitor<XSECCryptoBase64> j_b64(b64); unsigned char * output; int outputLen = ((4 * inputLen) / 3) + 5; XSECnew(output, unsigned char[outputLen]); ArrayJanitor<unsigned char> j_output(output); b64->encodeInit(); int j = b64->encode(input, inputLen, output, outputLen - 1); j += b64->encodeFinish(&output[j], outputLen - j - 1); // Strip any trailing \n\r while (j > 0 && (output[j-1] == '\n' || output[j-1] == '\r')) j--; // Now transcode and get out of here output[j] = '\0'; return XMLString::transcode((char *) output); } unsigned int DSIG_EXPORT DecodeFromBase64XMLCh(const XMLCh * input, unsigned char * output, int maxOutputLen) { XSECCryptoBase64 * b64 = XSECPlatformUtils::g_cryptoProvider->base64(); Janitor<XSECCryptoBase64> j_b64(b64); char * tinput = XMLString::transcode(input); ArrayJanitor<char> j_tinput(tinput); b64->decodeInit(); unsigned int j = b64->decode((unsigned char *) tinput, strlen(tinput), output, maxOutputLen - 1); j += b64->encodeFinish(&output[j], maxOutputLen - j - 1); return j; } unsigned int DSIG_EXPORT DecodeFromBase64(const char * input, unsigned char * output, int maxOutputLen) { XSECCryptoBase64 * b64 = XSECPlatformUtils::g_cryptoProvider->base64(); Janitor<XSECCryptoBase64> j_b64(b64); b64->decodeInit(); unsigned int j = b64->decode((unsigned char *) input, strlen(input), output, maxOutputLen - 1); j += b64->encodeFinish(&output[j], maxOutputLen - j - 1); return j; } // -------------------------------------------------------------------------------- // Some stuff to help with wierd signatures // -------------------------------------------------------------------------------- const unsigned char ASNDSAProlog[] = {0x30, 0x2c, 0x02, 0x14}; const unsigned char ASNDSAMiddle[] = {0x02, 0x14}; bool ASN2DSASig(const unsigned char * input, unsigned char * r, unsigned char * s) { if (memcmp(ASNDSAProlog, input, 4) != 0 || memcmp(ASNDSAMiddle, &input[24], 2) != 0) return false; memcpy(r, &input[4], 20); memcpy(s, &input[26], 20); return true; } <commit_msg>Helps if you don't use encode calls when doing base64 decoding...<commit_after>/* * Copyright 2002-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. */ /* * XSEC * * XSECCryptoUtils:= Helper crypo utilities that make life easier * * Author(s): Berin Lautenbach * * $Id$ * */ #include <xsec/framework/XSECDefs.hpp> #include <xsec/framework/XSECError.hpp> #include <xsec/enc/XSECCryptoUtils.hpp> #include <xsec/enc/XSECCryptoKeyHMAC.hpp> #include <xsec/utils/XSECPlatformUtils.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/XMLString.hpp> XERCES_CPP_NAMESPACE_USE // -------------------------------------------------------------------------------- // XKMS Limited-Use Shared Secret handling // -------------------------------------------------------------------------------- int CleanXKMSPassPhrase(unsigned char * input, int inputLen, safeBuffer &output) { int j = 0; unsigned char c; for (int i = 0; i < inputLen; ++i) { c = input[i]; if (c >= 'A' && c <= 'Z') { output[j++] = c - 'A' + 'a'; } else if (c != '\n' && c != '\r' && c != '\t' && c != ' ') { output[j++] = c; } } return j; } int DSIG_EXPORT CalculateXKMSAuthenticationKey(unsigned char * input, int inputLen, unsigned char * output, int maxOutputLen) { unsigned char keyVal[] = {XKMSAuthenticationValue}; XSECCryptoKeyHMAC * k = XSECPlatformUtils::g_cryptoProvider->keyHMAC(); Janitor<XSECCryptoKeyHMAC> j_k(k); k->setKey(keyVal, 1); XSECCryptoHash *h = XSECPlatformUtils::g_cryptoProvider->hashHMACSHA1(); Janitor<XSECCryptoHash> j_h(h); h->setKey(k); // Clean the input safeBuffer sb; int l = CleanXKMSPassPhrase(input, inputLen, sb); h->hash((unsigned char *) sb.rawBuffer(), l); return h->finish(output, maxOutputLen); } int DSIG_EXPORT CalculateXKMSRevocationCodeIdentifierEncoding1(unsigned char * input, int inputLen, unsigned char * output, int maxOutputLen) { unsigned char keyVal[] = {XKMSRevocationCodeIdenfitierEncoding1}; XSECCryptoKeyHMAC * k = XSECPlatformUtils::g_cryptoProvider->keyHMAC(); Janitor<XSECCryptoKeyHMAC> j_k(k); k->setKey(keyVal, 1); XSECCryptoHash *h = XSECPlatformUtils::g_cryptoProvider->hashHMACSHA1(); Janitor<XSECCryptoHash> j_h(h); h->setKey(k); // Clean the input safeBuffer sb; int l = CleanXKMSPassPhrase(input, inputLen, sb); h->hash((unsigned char *) sb.rawBuffer(), l); return h->finish(output, maxOutputLen); } int DSIG_EXPORT CalculateXKMSRevocationCodeIdentifierEncoding2(unsigned char * input, int inputLen, unsigned char * output, int maxOutputLen) { unsigned char tmpBuf[XSEC_MAX_HASH_SIZE]; int tmpLen = CalculateXKMSRevocationCodeIdentifierEncoding1(input, inputLen, tmpBuf, XSEC_MAX_HASH_SIZE); return CalculateXKMSRevocationCodeIdentifierEncoding2From1(tmpBuf, tmpLen, output, maxOutputLen); } int DSIG_EXPORT CalculateXKMSRevocationCodeIdentifierEncoding2From1(unsigned char * input, int inputLen, unsigned char * output, int maxOutputLen) { unsigned char keyVal[] = {XKMSRevocationCodeIdenfitierEncoding2}; XSECCryptoKeyHMAC * k = XSECPlatformUtils::g_cryptoProvider->keyHMAC(); Janitor<XSECCryptoKeyHMAC> j_k(k); k->setKey(keyVal, 1); XSECCryptoHash *h = XSECPlatformUtils::g_cryptoProvider->hashHMACSHA1(); Janitor<XSECCryptoHash> j_h(h); h->setKey(k); h->hash(input, inputLen); return h->finish(output, maxOutputLen); } int DSIG_EXPORT CalculateXKMSKEK(unsigned char * input, int inputLen, unsigned char * output, int maxOutputLen) { unsigned char keyVal[] = {XKMSKeyEncryption}; XSECCryptoKeyHMAC * k = XSECPlatformUtils::g_cryptoProvider->keyHMAC(); k->setKey(keyVal, 1); XSECCryptoHash *h = XSECPlatformUtils::g_cryptoProvider->hashHMACSHA1(); Janitor<XSECCryptoHash> j_h(h); h->setKey(k); // Clean the input safeBuffer sb; int l = CleanXKMSPassPhrase(input, inputLen, sb); h->hash((unsigned char *) sb.rawBuffer(), l); return h->finish(output, maxOutputLen); } // -------------------------------------------------------------------------------- // Some Base64 helpers // -------------------------------------------------------------------------------- XMLCh DSIG_EXPORT * EncodeToBase64XMLCh(unsigned char * input, int inputLen) { XSECCryptoBase64 * b64 = XSECPlatformUtils::g_cryptoProvider->base64(); Janitor<XSECCryptoBase64> j_b64(b64); unsigned char * output; int outputLen = ((4 * inputLen) / 3) + 5; XSECnew(output, unsigned char[outputLen]); ArrayJanitor<unsigned char> j_output(output); b64->encodeInit(); int j = b64->encode(input, inputLen, output, outputLen - 1); j += b64->encodeFinish(&output[j], outputLen - j - 1); // Strip any trailing \n\r while (j > 0 && (output[j-1] == '\n' || output[j-1] == '\r')) j--; // Now transcode and get out of here output[j] = '\0'; return XMLString::transcode((char *) output); } unsigned int DSIG_EXPORT DecodeFromBase64XMLCh(const XMLCh * input, unsigned char * output, int maxOutputLen) { XSECCryptoBase64 * b64 = XSECPlatformUtils::g_cryptoProvider->base64(); Janitor<XSECCryptoBase64> j_b64(b64); char * tinput = XMLString::transcode(input); ArrayJanitor<char> j_tinput(tinput); b64->decodeInit(); unsigned int j = b64->decode((unsigned char *) tinput, strlen(tinput), output, maxOutputLen - 1); j += b64->decodeFinish(&output[j], maxOutputLen - j - 1); return j; } unsigned int DSIG_EXPORT DecodeFromBase64(const char * input, unsigned char * output, int maxOutputLen) { XSECCryptoBase64 * b64 = XSECPlatformUtils::g_cryptoProvider->base64(); Janitor<XSECCryptoBase64> j_b64(b64); b64->decodeInit(); unsigned int j = b64->decode((unsigned char *) input, strlen(input), output, maxOutputLen - 1); j += b64->decodeFinish(&output[j], maxOutputLen - j - 1); return j; } // -------------------------------------------------------------------------------- // Some stuff to help with wierd signatures // -------------------------------------------------------------------------------- const unsigned char ASNDSAProlog[] = {0x30, 0x2c, 0x02, 0x14}; const unsigned char ASNDSAMiddle[] = {0x02, 0x14}; bool ASN2DSASig(const unsigned char * input, unsigned char * r, unsigned char * s) { if (memcmp(ASNDSAProlog, input, 4) != 0 || memcmp(ASNDSAMiddle, &input[24], 2) != 0) return false; memcpy(r, &input[4], 20); memcpy(s, &input[26], 20); return true; } <|endoftext|>
<commit_before>/* * (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others. * * 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. * * Contributors: * Markus Pilman <[email protected]> * Simon Loesing <[email protected]> * Thomas Etter <[email protected]> * Kevin Bocksrocker <[email protected]> * Lucas Braun <[email protected]> */ #include "GcScanProcessor.hpp" #include "ChainedVersionRecord.hpp" #include "LogstructuredMemoryStore.hpp" #include "Table.hpp" #include "VersionRecordIterator.hpp" #include <crossbow/logger.hpp> #include <boost/config.hpp> namespace tell { namespace store { namespace logstructured { namespace { /** * @brief Utilization threshold when to recycle a page in percent */ constexpr size_t gGcThreshold = 50; } // anonymous namespace std::vector<GcScanProcessor> GcScanProcessor::startScan(Table& table, size_t numThreads, const char* queryBuffer, const std::vector<ScanQuery*>& queries) { if (numThreads == 0) { return {}; } std::vector<GcScanProcessor> result; result.reserve(numThreads); auto version = table.minVersion(); auto& log = table.mLog; auto numPages = log.pages(); auto begin = log.pageBegin(); auto end = log.pageEnd(); auto mod = numPages % numThreads; auto iter = begin; for (decltype(numThreads) i = 1; i < numThreads; ++i) { auto step = numPages / numThreads + (i < mod ? 1 : 0); // Increment the page iterator by step pages (but not beyond the end page) for (decltype(step) j = 0; j < step && iter != end; ++j, ++iter) { } result.emplace_back(table, begin, iter, queryBuffer, queries, version); begin = iter; } // The last scan takes the remaining pages result.emplace_back(table, begin, end, queryBuffer, queries, version); return result; } GcScanProcessor::GcScanProcessor(Table& table, const LogImpl::PageIterator& begin, const LogImpl::PageIterator& end, const char* queryBuffer, const std::vector<ScanQuery*>& queryData, uint64_t minVersion) : mTable(table), mQueries(queryBuffer, queryData), mMinVersion(minVersion), mPagePrev(begin), mPageIt(begin), mPageEnd(end), mEntryIt(mPageIt == mPageEnd ? LogPage::EntryIterator() : mPageIt->begin()), mEntryEnd(mPageIt == mPageEnd ? LogPage::EntryIterator() : mPageIt->end()), mRecyclingHead(nullptr), mRecyclingTail(nullptr), mGarbage(0x0u), mSealed(false), mRecycle(false) { } GcScanProcessor::GcScanProcessor(GcScanProcessor&& other) : mTable(other.mTable), mQueries(std::move(other.mQueries)), mMinVersion(other.mMinVersion), mPagePrev(std::move(other.mPagePrev)), mPageIt(std::move(other.mPageIt)), mPageEnd(std::move(other.mPageEnd)), mEntryIt(std::move(other.mEntryIt)), mEntryEnd(std::move(other.mEntryEnd)), mRecyclingHead(other.mRecyclingHead), mRecyclingTail(other.mRecyclingTail), mGarbage(other.mGarbage), mSealed(other.mSealed), mRecycle(other.mRecycle) { other.mRecyclingHead = nullptr; other.mRecyclingTail = nullptr; other.mGarbage = 0x0u; other.mSealed = false; other.mRecycle = false; } void GcScanProcessor::process() { // Abort if the processor already is at the end if (mPageIt == mPageEnd) { return; } // Advance to the next page if the first page contains no entries if (mEntryIt == mEntryEnd && !advancePage()) { return; } do { if (BOOST_UNLIKELY(!mEntryIt->sealed())) { LOG_ASSERT(!mRecycle, "Recycling page even though not all entries are sealed"); mSealed = false; continue; } LOG_ASSERT(mEntryIt->size() >= sizeof(ChainedVersionRecord), "Log record is smaller than record header"); auto record = reinterpret_cast<ChainedVersionRecord*>(mEntryIt->data()); auto context = record->mutableData(); if (context.isInvalid()) { // The element is already marked as invalid - Increase the garbage counter mGarbage += mEntryIt->entrySize(); continue; } auto type = crossbow::from_underlying<VersionRecordType>(mEntryIt->type()); if (context.validTo() <= mMinVersion) { // No version can read the current element - Mark it as invalid and increase the garbage counter #ifdef NDEBUG record->invalidate(); #else auto res = record->tryInvalidate(context, nullptr); LOG_ASSERT(res, "Invalidating expired element failed"); #endif mGarbage += mEntryIt->entrySize(); continue; } else if ((type == VersionRecordType::DELETION) && (record->validFrom() <= mMinVersion)) { // Try to mark the deletion as invalid and set the next pointer to null // This basically truncates the version list and marks the deletion entry as deleted in the version history // Because the entry is still alive (i.e. can be accessed by other transactions) we have to use a CAS to // invalidate the entry if (!record->tryInvalidate(context, nullptr)) { continue; } mGarbage += mEntryIt->entrySize(); // Iterate over the whole version list for this key, this ensures the removal of the invalid deletion entry for (VersionRecordIterator recIter(mTable, record->key()); !recIter.done(); recIter.next()) { } continue; } if (mRecycle) { recycleEntry(record, mEntryIt->size(), mEntryIt->type()); } // Skip the element if it is not a data entry (i.e. deletion) if (type != VersionRecordType::DATA) { continue; } // Process the element auto recordLength = mEntryIt->size() - sizeof(ChainedVersionRecord); mQueries.processRecord(mTable.record(), record->key(), record->data(), recordLength, record->validFrom(), context.validTo()); } while (advanceEntry()); // Append recycled entries to the log if (mRecyclingHead != nullptr) { LOG_ASSERT(mRecyclingTail, "Recycling tail is null despite head being non null"); mTable.mLog.appendPage(mRecyclingHead, mRecyclingTail); } } bool GcScanProcessor::advanceEntry() { // Advance the iterator to the next entry if (++mEntryIt != mEntryEnd) { return true; } // Advance to next page return advancePage(); } bool GcScanProcessor::advancePage() { do { // Advance to next page if (mRecycle) { ++mPageIt; mTable.mLog.erase(mPagePrev.operator->(), mPageIt.operator->()); } else { // Only store the garbage statistic when every entry in the page was sealed if (mSealed) { mPageIt->context().store(mGarbage); } mPagePrev = mPageIt++; } if (mPageIt == mPageEnd) { return false; } mEntryIt = mPageIt->begin(); mEntryEnd = mPageIt->end(); // Retrieve usage statistics of the current page mGarbage = 0x0u; uint32_t offset; std::tie(offset, mSealed) = mPageIt->offsetAndSealed(); auto currentGarbage = mPageIt->context().load(); auto size = (currentGarbage >= offset ? 0u : offset - currentGarbage); mRecycle = (mSealed && ((size * 100) / LogPage::MAX_DATA_SIZE < gGcThreshold)); } while (mEntryIt == mEntryEnd); return true; } void GcScanProcessor::recycleEntry(ChainedVersionRecord* oldElement, uint32_t size, uint32_t type) { if (mRecyclingHead == nullptr) { mRecyclingHead = mTable.mLog.acquirePage(); if (mRecyclingHead == nullptr) { LOG_ERROR("PageManager ran out of space"); mRecycle = false; return; } mRecyclingTail = mRecyclingHead; } auto newEntry = mRecyclingHead->append(size, type); if (newEntry == nullptr) { auto newHead = mTable.mLog.acquirePage(); if (newHead == nullptr) { LOG_ERROR("PageManager ran out of space"); mRecycle = false; return; } newHead->next().store(mRecyclingHead); mRecyclingHead->seal(); mRecyclingHead = newHead; newEntry = mRecyclingHead->append(size, type); LOG_ASSERT(newEntry, "Unable to allocate entry on fresh page"); } auto newElement = new (newEntry->data()) ChainedVersionRecord(oldElement->key(), oldElement->validFrom()); memcpy(newElement->data(), oldElement->data(), size - sizeof(ChainedVersionRecord)); if (!replaceElement(oldElement, newElement)) { newElement->invalidate(); } newEntry->seal(); } bool GcScanProcessor::replaceElement(ChainedVersionRecord* oldElement, ChainedVersionRecord* newElement) { LOG_ASSERT(oldElement->key() == newElement->key(), "Keys do not match"); // Search for the old element in the version list - if it was not found it has to be invalidated by somebody else VersionRecordIterator recIter(mTable, oldElement->key()); if (!recIter.find(oldElement)) { LOG_ASSERT(oldElement->mutableData().isInvalid(), "Old element not in version list but not invalid"); return false; } // Replace can fail because the next pointer or validTo version of the current element has changed or it was // invalidated by someone else - if it was invalidated then the iterator will point to a different element while (!recIter.replace(newElement)) { if (recIter.value() != oldElement) { LOG_ASSERT(oldElement->mutableData().isInvalid(), "Old element not in version list but not invalid"); return false; } } // A successful replace only guarantees that the old element was invalidated (and replaced with the new element) but // the old element could still be in the version list - Traverse the iterator until the new element is reached (this // ensures all previous elements were valid at some time and we can safely reuse the memory of the old element) if (!recIter.find(newElement)) { LOG_ASSERT(newElement->mutableData().isInvalid(), "New element not in version list but not invalid"); } return true; } void GcScanGarbageCollector::run(const std::vector<Table*>& tables, uint64_t /* minVersion */) { for (auto i : tables) { LOG_TRACE("Starting garbage collection on table %1%", i->id()); if (!mStorage.scan(i->id(), nullptr)) { LOG_ERROR("Unable to start Garbage Collection scan"); return; } } } } // namespace logstructured } // namespace store } // namespace tell <commit_msg>Fix false error message<commit_after>/* * (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others. * * 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. * * Contributors: * Markus Pilman <[email protected]> * Simon Loesing <[email protected]> * Thomas Etter <[email protected]> * Kevin Bocksrocker <[email protected]> * Lucas Braun <[email protected]> */ #include "GcScanProcessor.hpp" #include "ChainedVersionRecord.hpp" #include "LogstructuredMemoryStore.hpp" #include "Table.hpp" #include "VersionRecordIterator.hpp" #include <crossbow/logger.hpp> #include <boost/config.hpp> namespace tell { namespace store { namespace logstructured { namespace { /** * @brief Utilization threshold when to recycle a page in percent */ constexpr size_t gGcThreshold = 50; } // anonymous namespace std::vector<GcScanProcessor> GcScanProcessor::startScan(Table& table, size_t numThreads, const char* queryBuffer, const std::vector<ScanQuery*>& queries) { if (numThreads == 0) { return {}; } std::vector<GcScanProcessor> result; result.reserve(numThreads); auto version = table.minVersion(); auto& log = table.mLog; auto numPages = log.pages(); auto begin = log.pageBegin(); auto end = log.pageEnd(); auto mod = numPages % numThreads; auto iter = begin; for (decltype(numThreads) i = 1; i < numThreads; ++i) { auto step = numPages / numThreads + (i < mod ? 1 : 0); // Increment the page iterator by step pages (but not beyond the end page) for (decltype(step) j = 0; j < step && iter != end; ++j, ++iter) { } result.emplace_back(table, begin, iter, queryBuffer, queries, version); begin = iter; } // The last scan takes the remaining pages result.emplace_back(table, begin, end, queryBuffer, queries, version); return result; } GcScanProcessor::GcScanProcessor(Table& table, const LogImpl::PageIterator& begin, const LogImpl::PageIterator& end, const char* queryBuffer, const std::vector<ScanQuery*>& queryData, uint64_t minVersion) : mTable(table), mQueries(queryBuffer, queryData), mMinVersion(minVersion), mPagePrev(begin), mPageIt(begin), mPageEnd(end), mEntryIt(mPageIt == mPageEnd ? LogPage::EntryIterator() : mPageIt->begin()), mEntryEnd(mPageIt == mPageEnd ? LogPage::EntryIterator() : mPageIt->end()), mRecyclingHead(nullptr), mRecyclingTail(nullptr), mGarbage(0x0u), mSealed(false), mRecycle(false) { } GcScanProcessor::GcScanProcessor(GcScanProcessor&& other) : mTable(other.mTable), mQueries(std::move(other.mQueries)), mMinVersion(other.mMinVersion), mPagePrev(std::move(other.mPagePrev)), mPageIt(std::move(other.mPageIt)), mPageEnd(std::move(other.mPageEnd)), mEntryIt(std::move(other.mEntryIt)), mEntryEnd(std::move(other.mEntryEnd)), mRecyclingHead(other.mRecyclingHead), mRecyclingTail(other.mRecyclingTail), mGarbage(other.mGarbage), mSealed(other.mSealed), mRecycle(other.mRecycle) { other.mRecyclingHead = nullptr; other.mRecyclingTail = nullptr; other.mGarbage = 0x0u; other.mSealed = false; other.mRecycle = false; } void GcScanProcessor::process() { // Abort if the processor already is at the end if (mPageIt == mPageEnd) { return; } // Advance to the next page if the first page contains no entries if (mEntryIt == mEntryEnd && !advancePage()) { return; } do { if (BOOST_UNLIKELY(!mEntryIt->sealed())) { LOG_ASSERT(!mRecycle, "Recycling page even though not all entries are sealed"); mSealed = false; continue; } LOG_ASSERT(mEntryIt->size() >= sizeof(ChainedVersionRecord), "Log record is smaller than record header"); auto record = reinterpret_cast<ChainedVersionRecord*>(mEntryIt->data()); auto context = record->mutableData(); if (context.isInvalid()) { // The element is already marked as invalid - Increase the garbage counter mGarbage += mEntryIt->entrySize(); continue; } auto type = crossbow::from_underlying<VersionRecordType>(mEntryIt->type()); if (context.validTo() <= mMinVersion) { // No version can read the current element - Mark it as invalid and increase the garbage counter #ifdef NDEBUG record->invalidate(); #else auto res = record->tryInvalidate(context, nullptr); LOG_ASSERT(res, "Invalidating expired element failed"); #endif mGarbage += mEntryIt->entrySize(); continue; } else if ((type == VersionRecordType::DELETION) && (record->validFrom() <= mMinVersion)) { // Try to mark the deletion as invalid and set the next pointer to null // This basically truncates the version list and marks the deletion entry as deleted in the version history // Because the entry is still alive (i.e. can be accessed by other transactions) we have to use a CAS to // invalidate the entry if (!record->tryInvalidate(context, nullptr)) { continue; } mGarbage += mEntryIt->entrySize(); // Iterate over the whole version list for this key, this ensures the removal of the invalid deletion entry for (VersionRecordIterator recIter(mTable, record->key()); !recIter.done(); recIter.next()) { } continue; } if (mRecycle) { recycleEntry(record, mEntryIt->size(), mEntryIt->type()); } // Skip the element if it is not a data entry (i.e. deletion) if (type != VersionRecordType::DATA) { continue; } // Process the element auto recordLength = mEntryIt->size() - sizeof(ChainedVersionRecord); mQueries.processRecord(mTable.record(), record->key(), record->data(), recordLength, record->validFrom(), context.validTo()); } while (advanceEntry()); // Append recycled entries to the log if (mRecyclingHead != nullptr) { LOG_ASSERT(mRecyclingTail, "Recycling tail is null despite head being non null"); mTable.mLog.appendPage(mRecyclingHead, mRecyclingTail); } } bool GcScanProcessor::advanceEntry() { // Advance the iterator to the next entry if (++mEntryIt != mEntryEnd) { return true; } // Advance to next page return advancePage(); } bool GcScanProcessor::advancePage() { do { // Advance to next page if (mRecycle) { ++mPageIt; mTable.mLog.erase(mPagePrev.operator->(), mPageIt.operator->()); } else { // Only store the garbage statistic when every entry in the page was sealed if (mSealed) { mPageIt->context().store(mGarbage); } mPagePrev = mPageIt++; } if (mPageIt == mPageEnd) { return false; } mEntryIt = mPageIt->begin(); mEntryEnd = mPageIt->end(); // Retrieve usage statistics of the current page mGarbage = 0x0u; uint32_t offset; std::tie(offset, mSealed) = mPageIt->offsetAndSealed(); auto currentGarbage = mPageIt->context().load(); auto size = (currentGarbage >= offset ? 0u : offset - currentGarbage); mRecycle = (mSealed && ((size * 100) / LogPage::MAX_DATA_SIZE < gGcThreshold)); } while (mEntryIt == mEntryEnd); return true; } void GcScanProcessor::recycleEntry(ChainedVersionRecord* oldElement, uint32_t size, uint32_t type) { if (mRecyclingHead == nullptr) { mRecyclingHead = mTable.mLog.acquirePage(); if (mRecyclingHead == nullptr) { LOG_ERROR("PageManager ran out of space"); mRecycle = false; return; } mRecyclingTail = mRecyclingHead; } auto newEntry = mRecyclingHead->append(size, type); if (newEntry == nullptr) { auto newHead = mTable.mLog.acquirePage(); if (newHead == nullptr) { LOG_ERROR("PageManager ran out of space"); mRecycle = false; return; } newHead->next().store(mRecyclingHead); mRecyclingHead->seal(); mRecyclingHead = newHead; newEntry = mRecyclingHead->append(size, type); LOG_ASSERT(newEntry, "Unable to allocate entry on fresh page"); } auto newElement = new (newEntry->data()) ChainedVersionRecord(oldElement->key(), oldElement->validFrom()); memcpy(newElement->data(), oldElement->data(), size - sizeof(ChainedVersionRecord)); if (!replaceElement(oldElement, newElement)) { newElement->invalidate(); } newEntry->seal(); } bool GcScanProcessor::replaceElement(ChainedVersionRecord* oldElement, ChainedVersionRecord* newElement) { LOG_ASSERT(oldElement->key() == newElement->key(), "Keys do not match"); // Search for the old element in the version list - if it was not found it has to be invalidated by somebody else VersionRecordIterator recIter(mTable, oldElement->key()); if (!recIter.find(oldElement)) { LOG_ASSERT(oldElement->mutableData().isInvalid(), "Old element not in version list but not invalid"); return false; } // Replace can fail because the next pointer or validTo version of the current element has changed or it was // invalidated by someone else - if it was invalidated then the iterator will point to a different element while (!recIter.replace(newElement)) { if (recIter.value() != oldElement) { LOG_ASSERT(oldElement->mutableData().isInvalid(), "Old element not in version list but not invalid"); return false; } } // A successful replace only guarantees that the old element was invalidated (and replaced with the new element) but // the old element could still be in the version list - Traverse the iterator until the new element is reached (this // ensures all previous elements were valid at some time and we can safely reuse the memory of the old element) if (!recIter.find(newElement)) { LOG_ASSERT(newElement->mutableData().isInvalid(), "New element not in version list but not invalid"); } return true; } void GcScanGarbageCollector::run(const std::vector<Table*>& tables, uint64_t /* minVersion */) { for (auto i : tables) { LOG_TRACE("Starting garbage collection on table %1%", i->id()); if (mStorage.scan(i->id(), nullptr)) { LOG_ERROR("Unable to start Garbage Collection scan"); return; } } } } // namespace logstructured } // namespace store } // namespace tell <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #ifndef INCLUDED_VCL_INC_HEADLESS_SVPGDI_HXX #define INCLUDED_VCL_INC_HEADLESS_SVPGDI_HXX #include <basebmp/bitmapdevice.hxx> #include <basebmp/color.hxx> #include <vcl/sysdata.hxx> #include "salgdi.hxx" #include "sallayout.hxx" #ifdef IOS #include "quartz/salgdi.h" #include <premac.h> #include <CoreGraphics/CoreGraphics.h> #include <postmac.h> #endif class ServerFont; #ifdef IOS // To keep changes to the CoreText code shared with AOO to a minimum, // let's continue calling the SalGraphics subclass "AquaSalGraphics" even if it // is used by us also on iOS, where of course the term "Aqua" has no meaning at all. // (Note that even on OS X, using the term "Aqua" is a misunderstanding or obsolete.) #define SvpSalGraphics AquaSalGraphics #endif class SvpSalGraphics : public SalGraphics { basebmp::BitmapDeviceSharedPtr m_aDevice; basebmp::BitmapDeviceSharedPtr m_aOrigDevice; #ifndef IOS bool m_bUseLineColor; basebmp::Color m_aLineColor; bool m_bUseFillColor; basebmp::Color m_aFillColor; basebmp::DrawMode m_aDrawMode; // These fields are used only when we use FreeType to draw into a // headless backend, i.e. not on iOS. basebmp::Color m_aTextColor; ServerFont* m_pServerFont[ MAX_FALLBACK ]; basebmp::Format m_eTextFmt; #else friend class CTLayout; CGLayerRef mxLayer; // mirror AquaSalVirtualDevice::mbForeignContext for SvpSalGraphics objects related to such bool mbForeignContext; CGContextRef mrContext; class XorEmulation* mpXorEmulation; int mnXorMode; // 0: off 1: on 2: invert only int mnWidth; int mnHeight; int mnBitmapDepth; // zero unless bitmap /// path representing current clip region CGMutablePathRef mxClipPath; /// Drawing colors /// pen color RGBA RGBAColor maLineColor; /// brush color RGBA RGBAColor maFillColor; // Device Font settings const CoreTextFontData* mpFontData; CoreTextStyle* mpTextStyle; RGBAColor maTextColor; /// allows text to be rendered without antialiasing bool mbNonAntialiasedText; /// is this a printer graphics bool mbPrinter; /// is this a virtual device graphics bool mbVirDev; #endif basebmp::BitmapDeviceSharedPtr m_aClipMap; protected: Region m_aClipRegion; basegfx::B2IVector GetSize() { return m_aOrigDevice->getSize(); } private: bool m_bClipSetup; struct ClipUndoHandle { SvpSalGraphics &m_rGfx; basebmp::BitmapDeviceSharedPtr m_aDevice; ClipUndoHandle( SvpSalGraphics *pGfx ) : m_rGfx( *pGfx ) {} ~ClipUndoHandle(); }; bool isClippedSetup( const basegfx::B2IBox &aRange, ClipUndoHandle &rUndo ); void ensureClip(); protected: virtual bool drawAlphaBitmap( const SalTwoRect&, const SalBitmap& rSourceBitmap, const SalBitmap& rAlphaBitmap ); virtual bool drawTransformedBitmap( const basegfx::B2DPoint& rNull, const basegfx::B2DPoint& rX, const basegfx::B2DPoint& rY, const SalBitmap& rSourceBitmap, const SalBitmap* pAlphaBitmap); virtual bool drawAlphaRect( long nX, long nY, long nWidth, long nHeight, sal_uInt8 nTransparency ); public: SvpSalGraphics(); virtual ~SvpSalGraphics(); void setDevice( basebmp::BitmapDeviceSharedPtr& rDevice ); virtual void GetResolution( sal_Int32& rDPIX, sal_Int32& rDPIY ); virtual sal_uInt16 GetBitCount() const; virtual long GetGraphicsWidth() const; virtual void ResetClipRegion(); virtual bool setClipRegion( const Region& ); virtual void SetLineColor(); virtual void SetLineColor( SalColor nSalColor ); virtual void SetFillColor(); virtual void SetFillColor( SalColor nSalColor ); virtual void SetXORMode( bool bSet, bool ); virtual void SetROPLineColor( SalROPColor nROPColor ); virtual void SetROPFillColor( SalROPColor nROPColor ); virtual void SetTextColor( SalColor nSalColor ); virtual sal_uInt16 SetFont( FontSelectPattern*, int nFallbackLevel ); virtual void GetFontMetric( ImplFontMetricData*, int nFallbackLevel ); virtual const ImplFontCharMap* GetImplFontCharMap() const; virtual bool GetImplFontCapabilities(vcl::FontCapabilities &rFontCapabilities) const; virtual void GetDevFontList( ImplDevFontList* ); virtual void ClearDevFontCache(); virtual bool AddTempDevFont( ImplDevFontList*, const OUString& rFileURL, const OUString& rFontName ); virtual sal_Bool CreateFontSubset( const OUString& rToFile, const PhysicalFontFace*, sal_GlyphId* pGlyphIds, sal_uInt8* pEncoding, sal_Int32* pWidths, int nGlyphs, FontSubsetInfo& rInfo ); virtual const Ucs2SIntMap* GetFontEncodingVector( const PhysicalFontFace*, const Ucs2OStrMap** ppNonEncoded ); virtual const void* GetEmbedFontData( const PhysicalFontFace*, const sal_Ucs* pUnicodes, sal_Int32* pWidths, FontSubsetInfo& rInfo, long* pDataLen ); virtual void FreeEmbedFontData( const void* pData, long nDataLen ); virtual void GetGlyphWidths( const PhysicalFontFace*, bool bVertical, Int32Vector& rWidths, Ucs2UIntMap& rUnicodeEnc ); virtual bool GetGlyphBoundRect( sal_GlyphId nIndex, Rectangle& ); virtual bool GetGlyphOutline( sal_GlyphId nIndex, ::basegfx::B2DPolyPolygon& ); virtual SalLayout* GetTextLayout( ImplLayoutArgs&, int nFallbackLevel ); virtual void DrawServerFontLayout( const ServerFontLayout& ); virtual bool supportsOperation( OutDevSupportType ) const; virtual void drawPixel( long nX, long nY ); virtual void drawPixel( long nX, long nY, SalColor nSalColor ); virtual void drawLine( long nX1, long nY1, long nX2, long nY2 ); virtual void drawRect( long nX, long nY, long nWidth, long nHeight ); virtual bool drawPolyPolygon( const ::basegfx::B2DPolyPolygon&, double fTransparency ); virtual bool drawPolyLine( const ::basegfx::B2DPolygon&, double fTransparency, const ::basegfx::B2DVector& rLineWidths, basegfx::B2DLineJoin, com::sun::star::drawing::LineCap); virtual void drawPolyLine( sal_uInt32 nPoints, const SalPoint* pPtAry ); virtual void drawPolygon( sal_uInt32 nPoints, const SalPoint* pPtAry ); virtual void drawPolyPolygon( sal_uInt32 nPoly, const sal_uInt32* pPoints, PCONSTSALPOINT* pPtAry ); virtual sal_Bool drawPolyLineBezier( sal_uInt32 nPoints, const SalPoint* pPtAry, const sal_uInt8* pFlgAry ); virtual sal_Bool drawPolygonBezier( sal_uInt32 nPoints, const SalPoint* pPtAry, const sal_uInt8* pFlgAry ); virtual sal_Bool drawPolyPolygonBezier( sal_uInt32 nPoly, const sal_uInt32* pPoints, const SalPoint* const* pPtAry, const sal_uInt8* const* pFlgAry ); virtual void copyArea( long nDestX, long nDestY, long nSrcX, long nSrcY, long nSrcWidth, long nSrcHeight, sal_uInt16 nFlags ); virtual void copyBits( const SalTwoRect& rPosAry, SalGraphics* pSrcGraphics ); virtual void drawBitmap( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap ); virtual void drawBitmap( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap, SalColor nTransparentColor ); virtual void drawBitmap( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap, const SalBitmap& rTransparentBitmap ); virtual void drawMask( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap, SalColor nMaskColor ); virtual SalBitmap* getBitmap( long nX, long nY, long nWidth, long nHeight ); virtual SalColor getPixel( long nX, long nY ); virtual void invert( long nX, long nY, long nWidth, long nHeight, SalInvert nFlags ); virtual void invert( sal_uInt32 nPoints, const SalPoint* pPtAry, SalInvert nFlags ); virtual sal_Bool drawEPS( long nX, long nY, long nWidth, long nHeight, void* pPtr, sal_uLong nSize ); virtual SystemGraphicsData GetGraphicsData() const; virtual SystemFontData GetSysFontData( int nFallbacklevel ) const; #ifdef IOS void SetVirDevGraphics( CGLayerRef xLayer, CGContextRef xContext, int = 0 ); bool CheckContext(); CGContextRef GetContext(); bool GetRawFontData( const PhysicalFontFace* pFontData, std::vector<unsigned char>& rBuffer, bool* pJustCFF ); void RefreshRect( const CGRect& ) { }; void RefreshRect(float /* lX */, float /* lY */, float /* lWidth */, float /* lHeight */) { }; void SetState(); void UnsetState(); void InvalidateContext(); bool IsPenVisible() const { return maLineColor.IsVisible(); } bool IsBrushVisible() const { return maFillColor.IsVisible(); } void ImplDrawPixel( long nX, long nY, const RGBAColor& ); // helper to draw single pixels CGPoint* makeCGptArray(sal_uLong nPoints, const SalPoint* pPtAry); bool IsFlipped() const { return false; } void ApplyXorContext(); void Pattern50Fill(); #endif }; #endif // INCLUDED_VCL_INC_HEADLESS_SVPGDI_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Fix fallout from 772c3a202481506b92c496948cfdc0f23ab94b2c<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #ifndef INCLUDED_VCL_INC_HEADLESS_SVPGDI_HXX #define INCLUDED_VCL_INC_HEADLESS_SVPGDI_HXX #include <basebmp/bitmapdevice.hxx> #include <basebmp/color.hxx> #include <vcl/sysdata.hxx> #include "salgdi.hxx" #include "sallayout.hxx" #ifdef IOS #include "quartz/salgdi.h" #include <premac.h> #include <CoreGraphics/CoreGraphics.h> #include <postmac.h> #endif class ServerFont; #ifdef IOS // To keep changes to the CoreText code shared with AOO to a minimum, // let's continue calling the SalGraphics subclass "AquaSalGraphics" even if it // is used by us also on iOS, where of course the term "Aqua" has no meaning at all. // (Note that even on OS X, using the term "Aqua" is a misunderstanding or obsolete.) #define SvpSalGraphics AquaSalGraphics #endif class SvpSalGraphics : public SalGraphics { basebmp::BitmapDeviceSharedPtr m_aDevice; basebmp::BitmapDeviceSharedPtr m_aOrigDevice; #ifndef IOS bool m_bUseLineColor; basebmp::Color m_aLineColor; bool m_bUseFillColor; basebmp::Color m_aFillColor; basebmp::DrawMode m_aDrawMode; // These fields are used only when we use FreeType to draw into a // headless backend, i.e. not on iOS. basebmp::Color m_aTextColor; ServerFont* m_pServerFont[ MAX_FALLBACK ]; basebmp::Format m_eTextFmt; #else friend class CTLayout; CGLayerRef mxLayer; // mirror AquaSalVirtualDevice::mbForeignContext for SvpSalGraphics objects related to such bool mbForeignContext; CGContextRef mrContext; class XorEmulation* mpXorEmulation; int mnXorMode; // 0: off 1: on 2: invert only int mnWidth; int mnHeight; int mnBitmapDepth; // zero unless bitmap /// path representing current clip region CGMutablePathRef mxClipPath; /// Drawing colors /// pen color RGBA RGBAColor maLineColor; /// brush color RGBA RGBAColor maFillColor; // Device Font settings const CoreTextFontData* mpFontData; CoreTextStyle* mpTextStyle; RGBAColor maTextColor; /// allows text to be rendered without antialiasing bool mbNonAntialiasedText; /// is this a printer graphics bool mbPrinter; /// is this a virtual device graphics bool mbVirDev; #endif basebmp::BitmapDeviceSharedPtr m_aClipMap; protected: Region m_aClipRegion; basegfx::B2IVector GetSize() { return m_aOrigDevice->getSize(); } private: bool m_bClipSetup; struct ClipUndoHandle { SvpSalGraphics &m_rGfx; basebmp::BitmapDeviceSharedPtr m_aDevice; ClipUndoHandle( SvpSalGraphics *pGfx ) : m_rGfx( *pGfx ) {} ~ClipUndoHandle(); }; bool isClippedSetup( const basegfx::B2IBox &aRange, ClipUndoHandle &rUndo ); void ensureClip(); protected: virtual bool drawAlphaBitmap( const SalTwoRect&, const SalBitmap& rSourceBitmap, const SalBitmap& rAlphaBitmap ); virtual bool drawTransformedBitmap( const basegfx::B2DPoint& rNull, const basegfx::B2DPoint& rX, const basegfx::B2DPoint& rY, const SalBitmap& rSourceBitmap, const SalBitmap* pAlphaBitmap); virtual bool drawAlphaRect( long nX, long nY, long nWidth, long nHeight, sal_uInt8 nTransparency ); public: SvpSalGraphics(); virtual ~SvpSalGraphics(); void setDevice( basebmp::BitmapDeviceSharedPtr& rDevice ); virtual void GetResolution( sal_Int32& rDPIX, sal_Int32& rDPIY ); virtual sal_uInt16 GetBitCount() const; virtual long GetGraphicsWidth() const; virtual void ResetClipRegion(); virtual bool setClipRegion( const Region& ); virtual void SetLineColor(); virtual void SetLineColor( SalColor nSalColor ); virtual void SetFillColor(); virtual void SetFillColor( SalColor nSalColor ); virtual void SetXORMode( bool bSet, bool ); virtual void SetROPLineColor( SalROPColor nROPColor ); virtual void SetROPFillColor( SalROPColor nROPColor ); virtual void SetTextColor( SalColor nSalColor ); virtual sal_uInt16 SetFont( FontSelectPattern*, int nFallbackLevel ); virtual void GetFontMetric( ImplFontMetricData*, int nFallbackLevel ); virtual const ImplFontCharMap* GetImplFontCharMap() const; virtual bool GetImplFontCapabilities(vcl::FontCapabilities &rFontCapabilities) const; virtual void GetDevFontList( ImplDevFontList* ); virtual void ClearDevFontCache(); virtual bool AddTempDevFont( ImplDevFontList*, const OUString& rFileURL, const OUString& rFontName ); virtual sal_Bool CreateFontSubset( const OUString& rToFile, const PhysicalFontFace*, sal_GlyphId* pGlyphIds, sal_uInt8* pEncoding, sal_Int32* pWidths, int nGlyphs, FontSubsetInfo& rInfo ); virtual const Ucs2SIntMap* GetFontEncodingVector( const PhysicalFontFace*, const Ucs2OStrMap** ppNonEncoded ); virtual const void* GetEmbedFontData( const PhysicalFontFace*, const sal_Ucs* pUnicodes, sal_Int32* pWidths, FontSubsetInfo& rInfo, long* pDataLen ); virtual void FreeEmbedFontData( const void* pData, long nDataLen ); virtual void GetGlyphWidths( const PhysicalFontFace*, bool bVertical, Int32Vector& rWidths, Ucs2UIntMap& rUnicodeEnc ); virtual bool GetGlyphBoundRect( sal_GlyphId nIndex, Rectangle& ); virtual bool GetGlyphOutline( sal_GlyphId nIndex, ::basegfx::B2DPolyPolygon& ); virtual SalLayout* GetTextLayout( ImplLayoutArgs&, int nFallbackLevel ); virtual void DrawServerFontLayout( const ServerFontLayout& ); virtual bool supportsOperation( OutDevSupportType ) const; virtual void drawPixel( long nX, long nY ); virtual void drawPixel( long nX, long nY, SalColor nSalColor ); virtual void drawLine( long nX1, long nY1, long nX2, long nY2 ); virtual void drawRect( long nX, long nY, long nWidth, long nHeight ); virtual bool drawPolyPolygon( const ::basegfx::B2DPolyPolygon&, double fTransparency ); virtual bool drawPolyLine( const ::basegfx::B2DPolygon&, double fTransparency, const ::basegfx::B2DVector& rLineWidths, basegfx::B2DLineJoin, com::sun::star::drawing::LineCap); virtual void drawPolyLine( sal_uInt32 nPoints, const SalPoint* pPtAry ); virtual void drawPolygon( sal_uInt32 nPoints, const SalPoint* pPtAry ); virtual void drawPolyPolygon( sal_uInt32 nPoly, const sal_uInt32* pPoints, PCONSTSALPOINT* pPtAry ); virtual sal_Bool drawPolyLineBezier( sal_uInt32 nPoints, const SalPoint* pPtAry, const sal_uInt8* pFlgAry ); virtual sal_Bool drawPolygonBezier( sal_uInt32 nPoints, const SalPoint* pPtAry, const sal_uInt8* pFlgAry ); virtual sal_Bool drawPolyPolygonBezier( sal_uInt32 nPoly, const sal_uInt32* pPoints, const SalPoint* const* pPtAry, const sal_uInt8* const* pFlgAry ); virtual void copyArea( long nDestX, long nDestY, long nSrcX, long nSrcY, long nSrcWidth, long nSrcHeight, sal_uInt16 nFlags ); virtual void copyBits( const SalTwoRect& rPosAry, SalGraphics* pSrcGraphics ); virtual void drawBitmap( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap ); virtual void drawBitmap( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap, SalColor nTransparentColor ); virtual void drawBitmap( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap, const SalBitmap& rTransparentBitmap ); virtual void drawMask( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap, SalColor nMaskColor ); virtual SalBitmap* getBitmap( long nX, long nY, long nWidth, long nHeight ); virtual SalColor getPixel( long nX, long nY ); virtual void invert( long nX, long nY, long nWidth, long nHeight, SalInvert nFlags ); virtual void invert( sal_uInt32 nPoints, const SalPoint* pPtAry, SalInvert nFlags ); virtual sal_Bool drawEPS( long nX, long nY, long nWidth, long nHeight, void* pPtr, sal_uLong nSize ); virtual SystemGraphicsData GetGraphicsData() const; virtual SystemFontData GetSysFontData( int nFallbacklevel ) const; #ifdef IOS void SetVirDevGraphics( CGLayerRef xLayer, CGContextRef xContext, int = 0 ); bool CheckContext(); CGContextRef GetContext(); bool GetRawFontData( const PhysicalFontFace* pFontData, std::vector<unsigned char>& rBuffer, bool* pJustCFF ); void RefreshRect( const CGRect& ) { }; void RefreshRect(float lX, float lY, float lWidth, float lHeight); void SetState(); void UnsetState(); void InvalidateContext(); bool IsPenVisible() const { return maLineColor.IsVisible(); } bool IsBrushVisible() const { return maFillColor.IsVisible(); } void ImplDrawPixel( long nX, long nY, const RGBAColor& ); // helper to draw single pixels CGPoint* makeCGptArray(sal_uLong nPoints, const SalPoint* pPtAry); bool IsFlipped() const { return false; } void ApplyXorContext(); void Pattern50Fill(); #endif }; #endif // INCLUDED_VCL_INC_HEADLESS_SVPGDI_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#ifndef ENTT_CORE_TYPE_INFO_HPP #define ENTT_CORE_TYPE_INFO_HPP #include "../config/config.h" #include "../core/attribute.h" #include "hashed_string.hpp" #ifndef ENTT_PRETTY_FUNCTION # define ENTT_TYPE_ID_API ENTT_API #else # define ENTT_TYPE_ID_API #endif #ifndef ENTT_PRETTY_FUNCTION /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace entt::internal { struct ENTT_API type_id_generator { static ENTT_ID_TYPE next() ENTT_NOEXCEPT { static ENTT_ID_TYPE value{}; return value++; } }; } /** * Internal details not to be documented. * @endcond TURN_OFF_DOXYGEN */ #endif namespace entt { /** * @brief Types identifiers. * @tparam Type Type for which to generate an identifier. */ template<typename Type, typename = void> struct ENTT_TYPE_ID_API type_info { /** * @brief Returns the numeric representation of a given type. * @return The numeric representation of the given type. */ #if defined ENTT_PRETTY_FUNCTION_CONSTEXPR static constexpr ENTT_ID_TYPE id() ENTT_NOEXCEPT { constexpr auto value = entt::hashed_string::value(ENTT_PRETTY_FUNCTION_CONSTEXPR); return value; } #elif defined ENTT_PRETTY_FUNCTION static ENTT_ID_TYPE id() ENTT_NOEXCEPT { static const auto value = entt::hashed_string::value(ENTT_PRETTY_FUNCTION); return value; } #else static ENTT_ID_TYPE id() ENTT_NOEXCEPT { static const ENTT_ID_TYPE value = internal::type_id_generator::next(); return value; } #endif }; } #endif <commit_msg>type_info: minor changes<commit_after>#ifndef ENTT_CORE_TYPE_INFO_HPP #define ENTT_CORE_TYPE_INFO_HPP #include "../config/config.h" #include "../core/attribute.h" #include "hashed_string.hpp" #ifndef ENTT_PRETTY_FUNCTION # define ENTT_TYPE_ID_API ENTT_API #else # define ENTT_TYPE_ID_API #endif namespace entt { #ifndef ENTT_PRETTY_FUNCTION /** * @cond TURN_OFF_DOXYGEN * Internal details not to be documented. */ namespace internal { struct ENTT_API type_id_generator { static ENTT_ID_TYPE next() ENTT_NOEXCEPT { static ENTT_ID_TYPE value{}; return value++; } }; } /** * Internal details not to be documented. * @endcond TURN_OFF_DOXYGEN */ #endif /** * @brief Types identifiers. * @tparam Type Type for which to generate an identifier. */ template<typename Type, typename = void> struct ENTT_TYPE_ID_API type_info { /** * @brief Returns the numeric representation of a given type. * @return The numeric representation of the given type. */ #if defined ENTT_PRETTY_FUNCTION_CONSTEXPR static constexpr ENTT_ID_TYPE id() ENTT_NOEXCEPT { constexpr auto value = entt::hashed_string::value(ENTT_PRETTY_FUNCTION_CONSTEXPR); return value; } #elif defined ENTT_PRETTY_FUNCTION static ENTT_ID_TYPE id() ENTT_NOEXCEPT { static const auto value = entt::hashed_string::value(ENTT_PRETTY_FUNCTION); return value; } #else static ENTT_ID_TYPE id() ENTT_NOEXCEPT { static const ENTT_ID_TYPE value = internal::type_id_generator::next(); return value; } #endif }; } #endif <|endoftext|>
<commit_before> AliAnalysisTaskElectronEfficiencyV2* AddTask_jjung_efficiency(TString name = "name", Bool_t isAOD, Bool_t getFromAlien = kFALSE, TString configFile="Config_jjung_lowmass.C", Bool_t DoCentralityCorrection = kFALSE) { std::cout << "########################################\nADDTASK of ANALYSIS started\n########################################" << std::endl; // ######################################################### // ######################################################### // Configuring Analysis Manager AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager(); TString fileName = AliAnalysisManager::GetCommonFileName(); fileName = "AnalysisResults.root"; // create a subfolder in the file // ######################################################### // ######################################################### // Loading individual config file either local or from Alien // TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/"; TString configBasePath= "/data4/jung/localLegotrainNewEfficiency/"; //Load updated macros from private ALIEN path if (getFromAlien //&& && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/j/jjung/%s .",configFile.Data()))) ) { configBasePath=Form("%s/",gSystem->pwd()); } TString configFilePath(configBasePath+configFile); // Loading config and cutlib Bool_t err=kFALSE; err |= gROOT->LoadMacro(configFilePath.Data()); if (err) { Error("AddTask_jjung_ElectronEfficiency_v2","Config(s) could not be loaded!"); return 0x0; } // Download resolution file (configured in your config.C) // if (GetResolutionFromAlien == kTRUE) // std::cout << "Trying to download resolution file" << std::endl; // gSystem->Exec(Form("alien_cp alien://%s .",resoFilenameFromAlien.c_str())); // std::cout << "Load resolution file from AliEn" << std::endl; // } // // // Download centrality file (configured in your config.C) // if (GetCentralityFromAlien == kTRUE && !gSystem->Exec(Form("alien_cp alien://%s .",CentralityFilenameFromAlien.c_str()))){ // std::cout << "Load centrality file from AliEn" << std::endl; // } // ######################################################### // ######################################################### // Creating an instance of the task AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(name.Data()); // ######################################################### // ######################################################### // Event selection. Is the same for all the different cutsettings task->SetEnablePhysicsSelection(kTRUE); task->SetTriggerMask(triggerNames); task->SetEventFilter(SetupEventCuts()); //returns eventCuts from Config. task->SetCentrality(centMin, centMax); // ######################################################### // ######################################################### // Set minimum and maximum values of generated tracks. Only used to save computing power. // Do not set here your analysis pt-cuts task->SetMinPtGen(minGenPt); task->SetMaxPtGen(maxGenPt); task->SetMinEtaGen(minGenEta); task->SetMaxEtaGen(maxGenEta); // ######################################################### // ######################################################### // Set minimum and maximum values of generated tracks. Only used to save computing power. task->SetKinematicCuts(minPtCut, maxPtCut, minEtaCut, maxEtaCut); // ######################################################### // ######################################################### // Set Binning task->SetPtBinsLinear (minPtBin, maxPtBin, stepsPtBin); task->SetEtaBinsLinear (minEtaBin, maxEtaBin, stepsEtaBin); task->SetPhiBinsLinear (minPhiBin, maxPhiBin, stepsPhiBin); task->SetThetaBinsLinear(minThetaBin, maxThetaBin, stepsThetaBin); task->SetMassBinsLinear (minMassBin, maxMassBin, stepsMassBin); task->SetPairPtBinsLinear(minPairPtBin, maxPairPtBin, stepsPairPtBin); // ######################################################### // ######################################################### // Resolution File, If resoFilename = "" no correction is applied task->SetResolutionFile(resoFilename); task->SetResolutionFileFromAlien(resoFilenameFromAlien); task->SetResolutionDeltaPtBinsLinear (DeltaMomMin, DeltaMomMax, NbinsDeltaMom); task->SetResolutionRelPtBinsLinear (RelMomMin, RelMomMax, NbinsRelMom); task->SetResolutionEtaBinsLinear (DeltaEtaMin, DeltaEtaMax, NbinsDeltaEta); task->SetResolutionPhiBinsLinear (DeltaPhiMin, DeltaPhiMax, NbinsDeltaPhi); task->SetResolutionThetaBinsLinear(DeltaThetaMin, DeltaThetaMax, NbinsDeltaTheta); // ######################################################### // ######################################################### // Set centrality correction. If resoFilename = "" no correction is applied task->SetCentralityFile(centralityFilename); // ######################################################### // ######################################################### // Pairing related config task->SetDoPairing(DoPairing); task->SetULSandLS(DoULSLS); // ######################################################### // ######################################################### // Add MCSignals. Can be set to see differences of: // e.g. secondaries and primaries. or primaries from charm and resonances AddSingleLegMCSignal(task); AddPairMCSignal(task); // ######################################################### // ######################################################### // Adding cutsettings //TObjArray* arrNames=names.Tokenize(";"); const Int_t nDie=arrNames->GetEntriesFast(); for (int iCut = 0; iCut < nDie; ++iCut){ //TString cutDefinition(arrNames->At(iCut)->GetName()); AliAnalysisFilter* filter = SetupTrackCutsAndSettings(iCut); task->AddTrackCuts(filter); } mgr->AddTask(task); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, mgr->CreateContainer("efficiency", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data())); return task; } <commit_msg>LMEE: personal Addtask: allow different binning of single efficiency<commit_after> AliAnalysisTaskElectronEfficiencyV2* AddTask_jjung_efficiency(TString name = "name", Bool_t isAOD, Bool_t getFromAlien = kFALSE, TString configFile="Config_jjung_lowmass.C", Bool_t DoCentralityCorrection = kFALSE, Int_t wagonnr = 0) { std::cout << "########################################\nADDTASK of ANALYSIS started\n########################################" << std::endl; // ######################################################### // ######################################################### // Configuring Analysis Manager AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager(); TString fileName = AliAnalysisManager::GetCommonFileName(); fileName = "AnalysisResults.root"; // create a subfolder in the file // ######################################################### // ######################################################### // Loading individual config file either local or from Alien // TString configBasePath= "$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/"; TString configBasePath= "/data4/jung/localLegotrainNewEfficiency/"; //Load updated macros from private ALIEN path if (getFromAlien //&& && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/j/jjung/%s .",configFile.Data()))) ) { configBasePath=Form("%s/",gSystem->pwd()); } TString configFilePath(configBasePath+configFile); // Loading config and cutlib Bool_t err=kFALSE; err |= gROOT->LoadMacro(configFilePath.Data()); if (err) { Error("AddTask_jjung_ElectronEfficiency_v2","Config(s) could not be loaded!"); return 0x0; } // Download resolution file (configured in your config.C) // if (GetResolutionFromAlien == kTRUE) // std::cout << "Trying to download resolution file" << std::endl; // gSystem->Exec(Form("alien_cp alien://%s .",resoFilenameFromAlien.c_str())); // std::cout << "Load resolution file from AliEn" << std::endl; // } // // // Download centrality file (configured in your config.C) // if (GetCentralityFromAlien == kTRUE && !gSystem->Exec(Form("alien_cp alien://%s .",CentralityFilenameFromAlien.c_str()))){ // std::cout << "Load centrality file from AliEn" << std::endl; // } // ######################################################### // ######################################################### // Creating an instance of the task AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(name.Data()); // ######################################################### // ######################################################### // Event selection. Is the same for all the different cutsettings task->SetEnablePhysicsSelection(kTRUE); task->SetTriggerMask(triggerNames); task->SetEventFilter(SetupEventCuts(wagonnr)); //returns eventCuts from Config. task->SetCentrality(centMin, centMax); // ######################################################### // ######################################################### // Set minimum and maximum values of generated tracks. Only used to save computing power. // Do not set here your analysis pt-cuts task->SetMinPtGen(minGenPt); task->SetMaxPtGen(maxGenPt); task->SetMinEtaGen(minGenEta); task->SetMaxEtaGen(maxGenEta); // ######################################################### // ######################################################### // Set minimum and maximum values of generated tracks. Only used to save computing power. task->SetKinematicCuts(minPtCut, maxPtCut, minEtaCut, maxEtaCut); // ######################################################### // ######################################################### // Set Binning if (usePtVector == true) { std::vector<double> ptBinsVec; for (unsigned int i = 0; i < nBinsPt+1; ++i){ ptBinsVec.push_back(PtBins[i]); } task->SetPtBins(ptBinsVec); } else task->SetPtBinsLinear (minPtBin, maxPtBin, stepsPtBin); task->SetEtaBinsLinear (minEtaBin, maxEtaBin, stepsEtaBin); task->SetPhiBinsLinear (minPhiBin, maxPhiBin, stepsPhiBin); task->SetThetaBinsLinear(minThetaBin, maxThetaBin, stepsThetaBin); task->SetMassBinsLinear (minMassBin, maxMassBin, stepsMassBin); task->SetPairPtBinsLinear(minPairPtBin, maxPairPtBin, stepsPairPtBin); // ######################################################### // ######################################################### // Resolution File, If resoFilename = "" no correction is applied task->SetResolutionFile(resoFilename); task->SetResolutionFileFromAlien(resoFilenameFromAlien); task->SetResolutionDeltaPtBinsLinear (DeltaMomMin, DeltaMomMax, NbinsDeltaMom); task->SetResolutionRelPtBinsLinear (RelMomMin, RelMomMax, NbinsRelMom); task->SetResolutionEtaBinsLinear (DeltaEtaMin, DeltaEtaMax, NbinsDeltaEta); task->SetResolutionPhiBinsLinear (DeltaPhiMin, DeltaPhiMax, NbinsDeltaPhi); task->SetResolutionThetaBinsLinear(DeltaThetaMin, DeltaThetaMax, NbinsDeltaTheta); // ######################################################### // ######################################################### // Set centrality correction. If resoFilename = "" no correction is applied task->SetCentralityFile(centralityFilename); // ######################################################### // ######################################################### // Pairing related config task->SetDoPairing(DoPairing); task->SetULSandLS(DoULSLS); // ######################################################### // ######################################################### // Add MCSignals. Can be set to see differences of: // e.g. secondaries and primaries. or primaries from charm and resonances AddSingleLegMCSignal(task); AddPairMCSignal(task); // ######################################################### // ######################################################### // Adding cutsettings //TObjArray* arrNames=names.Tokenize(";"); const Int_t nDie=arrNames->GetEntriesFast(); for (int iCut = 0; iCut < nDie; ++iCut){ //TString cutDefinition(arrNames->At(iCut)->GetName()); AliAnalysisFilter* filter = SetupTrackCutsAndSettings(iCut); task->AddTrackCuts(filter); } mgr->AddTask(task); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, mgr->CreateContainer("efficiency", TList::Class(), AliAnalysisManager::kOutputContainer, fileName.Data())); return task; } <|endoftext|>
<commit_before>// Copyright 2013 Alessio Sclocco <[email protected]> // // 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 <string> using std::getline; #include <fstream> using std::ifstream; #include <map> using std::make_pair; #include <vector> using std::vector; #include <cctype> using std::isalpha; #include <readConfiguration.hpp> #include <utils.hpp> using isa::utils::castToType; void readPadding(map< string, unsigned int > & padding, const string paddingFilename) { string temp; ifstream paddingFile(paddingFilename); while ( ! paddingFile.eof() ) { unsigned int middle = 0; getline(paddingFile, temp); if ( ! isalpha(temp[0]) ) { continue; } middle = temp.find(" "); padding.insert(make_pair(temp.substr(0, middle), castToType< string, unsigned int >(temp.substr(middle + 1)))); } } void readVectorWidth(map< string, unsigned int > & vectorWidth, const string vectorFilename) { string temp; ifstream vectorFile(vectorFilename); while ( ! vectorFile.eof() ) { unsigned int middle = 0; getline(vectorFile, temp); if ( ! isalpha(temp[0]) ) { continue; } middle = temp.find(" "); vectorWidth.insert(make_pair(temp.substr(0, middle), castToType< string, unsigned int >(temp.substr(middle + 1)))); } } void readDedispersion(map< string, map< unsigned int, vector< unsigned int > > > & dedispersionParameters, const string dedispersionFilename) { string temp; ifstream dedispersionFile(dedispersionFilename); while ( ! dedispersionFile.eof() ) { unsigned int splitPoint = 0; getline(dedispersionFile, temp); if ( ! isalpha(temp[0]) ) { continue; } string deviceName; unsigned int nrDMs = 0; vector< unsigned int > parameters(4); splitPoint = temp.find(" "); deviceName = temp.substr(0, splitPoint); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); nrDMs = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[0] = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[1] = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[2] = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); parameters[3] = castToType< string, unsigned int >(temp); if ( dedispersionParameters.count(deviceName) == 0 ) { map< unsigned int, vector< unsigned int > > container; container.insert(make_pair(nrDMs, parameters)); dedispersionParameters.insert(make_pair(deviceName, container)); } else { dedispersionParameters[deviceName].insert(make_pair(nrDMs, parameters)); } } } void readTranspose(map< string, map< unsigned int, unsigned int > > & transposeParameters, const string transposeFilename) { string temp; ifstream transposeFile(transposeFilename); while ( ! transposeFile.eof() ) { unsigned int splitPoint = 0; getline(transposeFile, temp); if ( ! isalpha(temp[0]) ) { continue; } string deviceName; unsigned int nrDMs = 0; unsigned int parameter = 0; splitPoint = temp.find(" "); deviceName = temp.substr(0, splitPoint); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); nrDMs = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); parameter = castToType< string, unsigned int >(temp); if ( transposeParameters.count(deviceName) == 0 ) { map< unsigned int, unsigned int > container; container.insert(make_pair(nrDMs, parameter)); transposeParameters.insert(make_pair(deviceName, container)); } else { transposeParameters[deviceName].insert(make_pair(nrDMs, parameter)); } } } void readFolding(map< string, map< unsigned int, map< unsigned int, vector< unsigned int > > > > & foldingParameters, const string foldingFilename) { string temp; ifstream foldingFile(foldingFilename); while ( ! foldingFile.eof() ) { unsigned int splitPoint = 0; getline(foldingFile, temp); if ( ! isalpha(temp[0]) ) { continue; } string deviceName; unsigned int nrDMs = 0; unsigned int nrPeriods = 0; vector< unsigned int > parameters(6); splitPoint = temp.find(" "); deviceName = temp.substr(0, splitPoint); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); nrDMs = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); nrPeriods = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[0] = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[1] = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[2] = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[3] = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[4] = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); parameters[5] = castToType< string, unsigned int >(temp); if ( foldingParameters.count(deviceName) == 0 ) { map< unsigned int, map< unsigned int, vector< unsigned int > > > externalContainer; map< unsigned int, vector< unsigned int > > internalContainer; internalContainer.insert(make_pair(nrPeriods, parameters)); externalContainer.insert(make_pair(nrDMs, internalContainer)); foldingParameters.insert(make_pair(deviceName, externalContainer)); } else if ( foldingParameters[deviceName].count(nrDMs) == 0 ) { map< unsigned int, vector< unsigned int > > internalContainer; internalContainer.insert(make_pair(nrPeriods, parameters)); foldingParameters[deviceName].insert(make_pair(nrDMs, internalContainer)); } else { foldingParameters[deviceName][nrDMs].insert(make_pair(nrPeriods, parameters)); } } } void readSNR(map< string, map< unsigned int, map< unsigned int, vector< unsigned int > > > > & snrParameters, const string snrFilename) { string temp; ifstream snrFile(snrFilename); while ( ! snrFile.eof() ) { unsigned int splitPoint = 0; getline(snrFile, temp); if ( ! isalpha(temp[0]) ) { continue; } string deviceName; unsigned int nrDMs = 0; unsigned int nrPeriods = 0; vector< unsigned int > parameters(2); splitPoint = temp.find(" "); deviceName = temp.substr(0, splitPoint); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); nrDMs = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); nrPeriods = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[0] = castToType< string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); parameters[1] = castToType< string, unsigned int >(temp); if ( snrParameters.count(deviceName) == 0 ) { map< unsigned int, map< unsigned int, vector< unsigned int > > > externalContainer; map< unsigned int, vector< unsigned int > > internalContainer; internalContainer.insert(make_pair(nrPeriods, parameters)); externalContainer.insert(make_pair(nrDMs, internalContainer)); snrParameters.insert(make_pair(deviceName, externalContainer)); } else if ( snrParameters[deviceName].count(nrDMs) == 0 ) { map< unsigned int, vector< unsigned int > > internalContainer; internalContainer.insert(make_pair(nrPeriods, parameters)); snrParameters[deviceName].insert(make_pair(nrDMs, internalContainer)); } else { snrParameters[deviceName][nrDMs].insert(make_pair(nrPeriods, parameters)); } } } <commit_msg>Style.<commit_after>// Copyright 2013 Alessio Sclocco <[email protected]> // // 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 <string> #include <fstream> #include <map> #include <vector> #include <cctype> #include <readConfiguration.hpp> #include <utils.hpp> void readPadding(map< std::string, unsigned int > & padding, const std::string & paddingFilename) { std::string temp; std::ifstream paddingFile(paddingFilename); while ( ! paddingFile.eof() ) { unsigned int middle = 0; std::getline(paddingFile, temp); if ( ! std::isalpha(temp[0]) ) { continue; } middle = temp.find(" "); padding.insert(std::make_pair(temp.substr(0, middle), isa::utils::castToType< std::string, unsigned int >(temp.substr(middle + 1)))); } } void readVectorWidth(map< std::string, unsigned int > & vectorWidth, const std::string & vectorFilename) { std::string temp; std::ifstream vectorFile(vectorFilename); while ( ! vectorFile.eof() ) { unsigned int middle = 0; std::getline(vectorFile, temp); if ( ! std::isalpha(temp[0]) ) { continue; } middle = temp.find(" "); vectorWidth.insert(std::make_pair(temp.substr(0, middle), isa::utils::castToType< std::string, unsigned int >(temp.substr(middle + 1)))); } } void readDedispersion(map< std::string, map< unsigned int, std::vector< unsigned int > > > & dedispersionParameters, const std::string & dedispersionFilename) { std::string temp; std::ifstream dedispersionFile(dedispersionFilename); while ( ! dedispersionFile.eof() ) { unsigned int splitPoint = 0; std::getline(dedispersionFile, temp); if ( ! std::isalpha(temp[0]) ) { continue; } std::string deviceName; unsigned int nrDMs = 0; std::vector< unsigned int > parameters(4); splitPoint = temp.find(" "); deviceName = temp.substr(0, splitPoint); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[0] = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[1] = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[2] = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); parameters[3] = isa::utils::castToType< std::string, unsigned int >(temp); if ( dedispersionParameters.count(deviceName) == 0 ) { map< unsigned int, std::vector< unsigned int > > container; container.insert(std::make_pair(nrDMs, parameters)); dedispersionParameters.insert(std::make_pair(deviceName, container)); } else { dedispersionParameters[deviceName].insert(std::make_pair(nrDMs, parameters)); } } } void readTranspose(map< std::string, map< unsigned int, unsigned int > > & transposeParameters, const std::string & transposeFilename) { std::string temp; std::ifstream transposeFile(transposeFilename); while ( ! transposeFile.eof() ) { unsigned int splitPoint = 0; std::getline(transposeFile, temp); if ( ! std::isalpha(temp[0]) ) { continue; } std::string deviceName; unsigned int nrDMs = 0; unsigned int parameter = 0; splitPoint = temp.find(" "); deviceName = temp.substr(0, splitPoint); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); parameter = isa::utils::castToType< std::string, unsigned int >(temp); if ( transposeParameters.count(deviceName) == 0 ) { map< unsigned int, unsigned int > container; container.insert(std::make_pair(nrDMs, parameter)); transposeParameters.insert(std::make_pair(deviceName, container)); } else { transposeParameters[deviceName].insert(std::make_pair(nrDMs, parameter)); } } } void readFolding(map< std::string, map< unsigned int, map< unsigned int, std::vector< unsigned int > > > > & foldingParameters, const std::string & foldingFilename) { std::string temp; std::ifstream foldingFile(foldingFilename); while ( ! foldingFile.eof() ) { unsigned int splitPoint = 0; std::getline(foldingFile, temp); if ( ! std::isalpha(temp[0]) ) { continue; } std::string deviceName; unsigned int nrDMs = 0; unsigned int nrPeriods = 0; std::vector< unsigned int > parameters(6); splitPoint = temp.find(" "); deviceName = temp.substr(0, splitPoint); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); nrPeriods = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[0] = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[1] = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[2] = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[3] = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[4] = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); parameters[5] = isa::utils::castToType< std::string, unsigned int >(temp); if ( foldingParameters.count(deviceName) == 0 ) { map< unsigned int, map< unsigned int, std::vector< unsigned int > > > externalContainer; map< unsigned int, std::vector< unsigned int > > internalContainer; internalContainer.insert(std::make_pair(nrPeriods, parameters)); externalContainer.insert(std::make_pair(nrDMs, internalContainer)); foldingParameters.insert(std::make_pair(deviceName, externalContainer)); } else if ( foldingParameters[deviceName].count(nrDMs) == 0 ) { map< unsigned int, std::vector< unsigned int > > internalContainer; internalContainer.insert(std::make_pair(nrPeriods, parameters)); foldingParameters[deviceName].insert(std::make_pair(nrDMs, internalContainer)); } else { foldingParameters[deviceName][nrDMs].insert(std::make_pair(nrPeriods, parameters)); } } } void readSNR(map< std::string, map< unsigned int, map< unsigned int, std::vector< unsigned int > > > > & snrParameters, const std::string & snrFilename) { std::string temp; std::ifstream snrFile(snrFilename); while ( ! snrFile.eof() ) { unsigned int splitPoint = 0; std::getline(snrFile, temp); if ( ! std::isalpha(temp[0]) ) { continue; } std::string deviceName; unsigned int nrDMs = 0; unsigned int nrPeriods = 0; std::vector< unsigned int > parameters(2); splitPoint = temp.find(" "); deviceName = temp.substr(0, splitPoint); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); nrPeriods = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); parameters[0] = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); parameters[1] = isa::utils::castToType< std::string, unsigned int >(temp); if ( snrParameters.count(deviceName) == 0 ) { map< unsigned int, map< unsigned int, std::vector< unsigned int > > > externalContainer; map< unsigned int, std::vector< unsigned int > > internalContainer; internalContainer.insert(std::make_pair(nrPeriods, parameters)); externalContainer.insert(std::make_pair(nrDMs, internalContainer)); snrParameters.insert(std::make_pair(deviceName, externalContainer)); } else if ( snrParameters[deviceName].count(nrDMs) == 0 ) { map< unsigned int, std::vector< unsigned int > > internalContainer; internalContainer.insert(std::make_pair(nrPeriods, parameters)); snrParameters[deviceName].insert(std::make_pair(nrDMs, internalContainer)); } else { snrParameters[deviceName][nrDMs].insert(std::make_pair(nrPeriods, parameters)); } } } <|endoftext|>
<commit_before>/* Persons Model Example Copyright (C) 2012 Aleix Pol Gonzalez <[email protected]> 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 <QApplication> #include <QWidget> #include <QFormLayout> #include <QLabel> #include <QDebug> #include <persondata.h> int main(int argc, char** argv) { QApplication app(argc, argv); if(app.argc()<2) { qWarning() << "Missing argument: \"" << qPrintable(app.arguments().first()) << " <contact id>\""; return 1; } PersonData d; d.setContactId(app.arguments()[1]); QWidget w; QFormLayout* l = new QFormLayout(&w); l->addRow("contactId:", new QLabel(d.contactId())); l->addRow("nickname:", new QLabel(d.nickname())); l->addRow("status:", new QLabel(d.status())); QLabel* avatar = new QLabel; avatar->setPixmap(QPixmap(d.avatar().toLocalFile())); l->addRow("avatar:", avatar); w.show(); app.exec(); } <commit_msg>expose the actions in the niceperson example<commit_after>/* Persons Model Example Copyright (C) 2012 Aleix Pol Gonzalez <[email protected]> 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 <QApplication> #include <QWidget> #include <QFormLayout> #include <QLabel> #include <QDebug> #include <QToolButton> #include <QMenu> #include <persondata.h> #include <personactions.h> int main(int argc, char** argv) { QApplication app(argc, argv); if(app.argc()<2) { qWarning() << "Missing argument: \"" << qPrintable(app.arguments().first()) << " <contact id>\""; return 1; } PersonData d; d.setContactId(app.arguments()[1]); QWidget w; QFormLayout* l = new QFormLayout(&w); l->addRow("contactId:", new QLabel(d.contactId())); l->addRow("nickname:", new QLabel(d.nickname())); l->addRow("status:", new QLabel(d.status())); QLabel* avatar = new QLabel; avatar->setPixmap(QPixmap(d.avatar().toLocalFile())); l->addRow("avatar:", avatar); PersonActions* actions = new PersonActions(&d); actions->setPerson(&d); QToolButton* b = new QToolButton; b->setText("Actions"); QMenu* m = new QMenu(b); m->addActions(actions->actions()); b->setPopupMode(QToolButton::MenuButtonPopup); b->setMenu(m); l->addRow("actions:", b); w.show(); app.exec(); } <|endoftext|>
<commit_before>/************************************************************************* * * 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: mediawindowbase_impl.cxx,v $ * $Revision: 1.7 $ * * 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. * ************************************************************************/ #include "mediawindowbase_impl.hxx" #include <avmedia/mediaitem.hxx> #include "mediamisc.hxx" #include "mediawindow.hrc" #include <tools/urlobj.hxx> #include <comphelper/processfactory.hxx> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/media/XManager.hpp> #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HDL_ #include <com/sun/star/lang/XComponent.hdl> #endif #define MEDIA_TIMER_TIMEOUT 100 using namespace ::com::sun::star; namespace avmedia { namespace priv { // ----------------------- // - MediaWindowBaseImpl - // ----------------------- MediaWindowBaseImpl::MediaWindowBaseImpl( MediaWindow* pMediaWindow ) : mpMediaWindow( pMediaWindow ) { } // --------------------------------------------------------------------- MediaWindowBaseImpl::~MediaWindowBaseImpl() { uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() ); } // ------------------------------------------------------------------------- uno::Reference< media::XPlayer > MediaWindowBaseImpl::createPlayer( const ::rtl::OUString& rURL ) { uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() ); uno::Reference< media::XPlayer > xPlayer; if( xFactory.is() ) { try { uno::Reference< ::com::sun::star::media::XManager > xManager( xFactory->createInstance( ::rtl::OUString::createFromAscii( AVMEDIA_MANAGER_SERVICE_NAME ) ), uno::UNO_QUERY ); if( xManager.is() ) { xPlayer = uno::Reference< ::com::sun::star::media::XPlayer >( xManager->createPlayer( rURL ), uno::UNO_QUERY ); } } catch( ... ) { } } return xPlayer; } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setURL( const ::rtl::OUString& rURL ) { if( rURL != getURL() ) { INetURLObject aURL( maFileURL = rURL ); if( mxPlayer.is() ) mxPlayer->stop(); if( mxPlayerWindow.is() ) { mxPlayerWindow->setVisible( false ); mxPlayerWindow.clear(); } mxPlayer.clear(); if( aURL.GetProtocol() != INET_PROT_NOT_VALID ) maFileURL = aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS ); mxPlayer = createPlayer( maFileURL ); onURLChanged(); } } // --------------------------------------------------------------------- void MediaWindowBaseImpl::onURLChanged() { } // --------------------------------------------------------------------- const ::rtl::OUString& MediaWindowBaseImpl::getURL() const { return maFileURL; } // --------------------------------------------------------------------- bool MediaWindowBaseImpl::isValid() const { return( getPlayer().is() ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::stopPlayingInternal( bool bStop ) { if( isPlaying() ) { if( bStop ) mxPlayer->start(); else mxPlayer->stop(); } } // --------------------------------------------------------------------- MediaWindow* MediaWindowBaseImpl::getMediaWindow() const { return mpMediaWindow; } // --------------------------------------------------------------------- uno::Reference< media::XPlayer > MediaWindowBaseImpl::getPlayer() const { return mxPlayer; } // --------------------------------------------------------------------- uno::Reference< media::XPlayerWindow > MediaWindowBaseImpl::getPlayerWindow() const { return mxPlayerWindow; } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setPlayerWindow( const uno::Reference< media::XPlayerWindow >& rxPlayerWindow ) { mxPlayerWindow = rxPlayerWindow; } // --------------------------------------------------------------------- void MediaWindowBaseImpl::cleanUp() { if( mxPlayer.is() ) { mxPlayer->stop(); uno::Reference< lang::XComponent > xComponent( mxPlayer, uno::UNO_QUERY ); if( xComponent.is() ) xComponent->dispose(); mxPlayer.clear(); } mpMediaWindow = NULL; } // --------------------------------------------------------------------- bool MediaWindowBaseImpl::hasPreferredSize() const { return( mxPlayerWindow.is() ); } // --------------------------------------------------------------------- Size MediaWindowBaseImpl::getPreferredSize() const { Size aRet; if( mxPlayer.is() ) { awt::Size aPrefSize( mxPlayer->getPreferredPlayerWindowSize() ); aRet.Width() = aPrefSize.Width; aRet.Height() = aPrefSize.Height; } return aRet; } // --------------------------------------------------------------------- bool MediaWindowBaseImpl::setZoom( ::com::sun::star::media::ZoomLevel eLevel ) { return( mxPlayerWindow.is() ? mxPlayerWindow->setZoomLevel( eLevel ) : false ); } // ------------------------------------------------------------------------- ::com::sun::star::media::ZoomLevel MediaWindowBaseImpl::getZoom() const { return( mxPlayerWindow.is() ? mxPlayerWindow->getZoomLevel() : ::com::sun::star::media::ZoomLevel_NOT_AVAILABLE ); } // --------------------------------------------------------------------- bool MediaWindowBaseImpl::start() { return( mxPlayer.is() ? ( mxPlayer->start(), true ) : false ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::stop() { if( mxPlayer.is() ) mxPlayer->stop(); } // --------------------------------------------------------------------- bool MediaWindowBaseImpl::isPlaying() const { return( mxPlayer.is() && mxPlayer->isPlaying() ); } // --------------------------------------------------------------------- double MediaWindowBaseImpl::getDuration() const { return( mxPlayer.is() ? mxPlayer->getDuration() : 0.0 ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setMediaTime( double fTime ) { if( mxPlayer.is() ) mxPlayer->setMediaTime( fTime ); } // --------------------------------------------------------------------- double MediaWindowBaseImpl::getMediaTime() const { return( mxPlayer.is() ? mxPlayer->getMediaTime() : 0.0 ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setStopTime( double fTime ) { if( mxPlayer.is() ) mxPlayer->setStopTime( fTime ); } // --------------------------------------------------------------------- double MediaWindowBaseImpl::getStopTime() const { return( mxPlayer.is() ? mxPlayer->getStopTime() : 0.0 ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setRate( double fRate ) { if( mxPlayer.is() ) mxPlayer->setRate( fRate ); } // --------------------------------------------------------------------- double MediaWindowBaseImpl::getRate() const { return( mxPlayer.is() ? mxPlayer->getRate() : 0.0 ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setPlaybackLoop( bool bSet ) { if( mxPlayer.is() ) mxPlayer->setPlaybackLoop( bSet ); } // --------------------------------------------------------------------- bool MediaWindowBaseImpl::isPlaybackLoop() const { return( mxPlayer.is() ? mxPlayer->isPlaybackLoop() : false ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setMute( bool bSet ) { if( mxPlayer.is() ) mxPlayer->setMute( bSet ); } // --------------------------------------------------------------------- bool MediaWindowBaseImpl::isMute() const { return( mxPlayer.is() ? mxPlayer->isMute() : false ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setVolumeDB( sal_Int16 nVolumeDB ) { if( mxPlayer.is() ) mxPlayer->setVolumeDB( nVolumeDB ); } // --------------------------------------------------------------------- sal_Int16 MediaWindowBaseImpl::getVolumeDB() const { return( mxPlayer.is() ? mxPlayer->getVolumeDB() : 0 ); } // ------------------------------------------------------------------------- void MediaWindowBaseImpl::updateMediaItem( MediaItem& rItem ) const { if( isPlaying() ) rItem.setState( ( getRate() > 1.0 ) ? MEDIASTATE_PLAYFFW : MEDIASTATE_PLAY ); else rItem.setState( ( 0.0 == getMediaTime() ) ? MEDIASTATE_STOP : MEDIASTATE_PAUSE ); rItem.setDuration( getDuration() ); rItem.setTime( getMediaTime() ); rItem.setLoop( isPlaybackLoop() ); rItem.setMute( isMute() ); rItem.setVolumeDB( getVolumeDB() ); rItem.setZoom( getZoom() ); rItem.setURL( getURL() ); } // ------------------------------------------------------------------------- void MediaWindowBaseImpl::executeMediaItem( const MediaItem& rItem ) { const sal_uInt32 nMaskSet = rItem.getMaskSet(); // set URL first if( nMaskSet & AVMEDIA_SETMASK_URL ) setURL( rItem.getURL() ); // set different states next if( nMaskSet & AVMEDIA_SETMASK_TIME ) setMediaTime( ::std::min( rItem.getTime(), getDuration() ) ); if( nMaskSet & AVMEDIA_SETMASK_LOOP ) setPlaybackLoop( rItem.isLoop() ); if( nMaskSet & AVMEDIA_SETMASK_MUTE ) setMute( rItem.isMute() ); if( nMaskSet & AVMEDIA_SETMASK_VOLUMEDB ) setVolumeDB( rItem.getVolumeDB() ); if( nMaskSet & AVMEDIA_SETMASK_ZOOM ) setZoom( rItem.getZoom() ); // set play state at last if( nMaskSet & AVMEDIA_SETMASK_STATE ) { switch( rItem.getState() ) { case( MEDIASTATE_PLAY ): case( MEDIASTATE_PLAYFFW ): { /* const double fNewRate = ( ( MEDIASTATE_PLAYFFW == rItem.getState() ) ? AVMEDIA_FFW_PLAYRATE : 1.0 ); if( getRate() != fNewRate ) setRate( fNewRate ); */ if( !isPlaying() ) start(); } break; case( MEDIASTATE_PAUSE ): { if( isPlaying() ) stop(); } break; case( MEDIASTATE_STOP ): { if( isPlaying() ) { setMediaTime( 0.0 ); stop(); setMediaTime( 0.0 ); } } break; } } } } // namespace priv } // namespace avemdia <commit_msg>#i106261# do not confuse stop with start<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: mediawindowbase_impl.cxx,v $ * $Revision: 1.7 $ * * 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. * ************************************************************************/ #include "mediawindowbase_impl.hxx" #include <avmedia/mediaitem.hxx> #include "mediamisc.hxx" #include "mediawindow.hrc" #include <tools/urlobj.hxx> #include <comphelper/processfactory.hxx> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/media/XManager.hpp> #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HDL_ #include <com/sun/star/lang/XComponent.hdl> #endif #define MEDIA_TIMER_TIMEOUT 100 using namespace ::com::sun::star; namespace avmedia { namespace priv { // ----------------------- // - MediaWindowBaseImpl - // ----------------------- MediaWindowBaseImpl::MediaWindowBaseImpl( MediaWindow* pMediaWindow ) : mpMediaWindow( pMediaWindow ) { } // --------------------------------------------------------------------- MediaWindowBaseImpl::~MediaWindowBaseImpl() { uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() ); } // ------------------------------------------------------------------------- uno::Reference< media::XPlayer > MediaWindowBaseImpl::createPlayer( const ::rtl::OUString& rURL ) { uno::Reference< lang::XMultiServiceFactory > xFactory( ::comphelper::getProcessServiceFactory() ); uno::Reference< media::XPlayer > xPlayer; if( xFactory.is() ) { try { uno::Reference< ::com::sun::star::media::XManager > xManager( xFactory->createInstance( ::rtl::OUString::createFromAscii( AVMEDIA_MANAGER_SERVICE_NAME ) ), uno::UNO_QUERY ); if( xManager.is() ) { xPlayer = uno::Reference< ::com::sun::star::media::XPlayer >( xManager->createPlayer( rURL ), uno::UNO_QUERY ); } } catch( ... ) { } } return xPlayer; } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setURL( const ::rtl::OUString& rURL ) { if( rURL != getURL() ) { INetURLObject aURL( maFileURL = rURL ); if( mxPlayer.is() ) mxPlayer->stop(); if( mxPlayerWindow.is() ) { mxPlayerWindow->setVisible( false ); mxPlayerWindow.clear(); } mxPlayer.clear(); if( aURL.GetProtocol() != INET_PROT_NOT_VALID ) maFileURL = aURL.GetMainURL( INetURLObject::DECODE_UNAMBIGUOUS ); mxPlayer = createPlayer( maFileURL ); onURLChanged(); } } // --------------------------------------------------------------------- void MediaWindowBaseImpl::onURLChanged() { } // --------------------------------------------------------------------- const ::rtl::OUString& MediaWindowBaseImpl::getURL() const { return maFileURL; } // --------------------------------------------------------------------- bool MediaWindowBaseImpl::isValid() const { return( getPlayer().is() ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::stopPlayingInternal( bool bStop ) { if( isPlaying() ) { if( bStop ) mxPlayer->stop(); else mxPlayer->start(); } } // --------------------------------------------------------------------- MediaWindow* MediaWindowBaseImpl::getMediaWindow() const { return mpMediaWindow; } // --------------------------------------------------------------------- uno::Reference< media::XPlayer > MediaWindowBaseImpl::getPlayer() const { return mxPlayer; } // --------------------------------------------------------------------- uno::Reference< media::XPlayerWindow > MediaWindowBaseImpl::getPlayerWindow() const { return mxPlayerWindow; } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setPlayerWindow( const uno::Reference< media::XPlayerWindow >& rxPlayerWindow ) { mxPlayerWindow = rxPlayerWindow; } // --------------------------------------------------------------------- void MediaWindowBaseImpl::cleanUp() { if( mxPlayer.is() ) { mxPlayer->stop(); uno::Reference< lang::XComponent > xComponent( mxPlayer, uno::UNO_QUERY ); if( xComponent.is() ) xComponent->dispose(); mxPlayer.clear(); } mpMediaWindow = NULL; } // --------------------------------------------------------------------- bool MediaWindowBaseImpl::hasPreferredSize() const { return( mxPlayerWindow.is() ); } // --------------------------------------------------------------------- Size MediaWindowBaseImpl::getPreferredSize() const { Size aRet; if( mxPlayer.is() ) { awt::Size aPrefSize( mxPlayer->getPreferredPlayerWindowSize() ); aRet.Width() = aPrefSize.Width; aRet.Height() = aPrefSize.Height; } return aRet; } // --------------------------------------------------------------------- bool MediaWindowBaseImpl::setZoom( ::com::sun::star::media::ZoomLevel eLevel ) { return( mxPlayerWindow.is() ? mxPlayerWindow->setZoomLevel( eLevel ) : false ); } // ------------------------------------------------------------------------- ::com::sun::star::media::ZoomLevel MediaWindowBaseImpl::getZoom() const { return( mxPlayerWindow.is() ? mxPlayerWindow->getZoomLevel() : ::com::sun::star::media::ZoomLevel_NOT_AVAILABLE ); } // --------------------------------------------------------------------- bool MediaWindowBaseImpl::start() { return( mxPlayer.is() ? ( mxPlayer->start(), true ) : false ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::stop() { if( mxPlayer.is() ) mxPlayer->stop(); } // --------------------------------------------------------------------- bool MediaWindowBaseImpl::isPlaying() const { return( mxPlayer.is() && mxPlayer->isPlaying() ); } // --------------------------------------------------------------------- double MediaWindowBaseImpl::getDuration() const { return( mxPlayer.is() ? mxPlayer->getDuration() : 0.0 ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setMediaTime( double fTime ) { if( mxPlayer.is() ) mxPlayer->setMediaTime( fTime ); } // --------------------------------------------------------------------- double MediaWindowBaseImpl::getMediaTime() const { return( mxPlayer.is() ? mxPlayer->getMediaTime() : 0.0 ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setStopTime( double fTime ) { if( mxPlayer.is() ) mxPlayer->setStopTime( fTime ); } // --------------------------------------------------------------------- double MediaWindowBaseImpl::getStopTime() const { return( mxPlayer.is() ? mxPlayer->getStopTime() : 0.0 ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setRate( double fRate ) { if( mxPlayer.is() ) mxPlayer->setRate( fRate ); } // --------------------------------------------------------------------- double MediaWindowBaseImpl::getRate() const { return( mxPlayer.is() ? mxPlayer->getRate() : 0.0 ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setPlaybackLoop( bool bSet ) { if( mxPlayer.is() ) mxPlayer->setPlaybackLoop( bSet ); } // --------------------------------------------------------------------- bool MediaWindowBaseImpl::isPlaybackLoop() const { return( mxPlayer.is() ? mxPlayer->isPlaybackLoop() : false ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setMute( bool bSet ) { if( mxPlayer.is() ) mxPlayer->setMute( bSet ); } // --------------------------------------------------------------------- bool MediaWindowBaseImpl::isMute() const { return( mxPlayer.is() ? mxPlayer->isMute() : false ); } // --------------------------------------------------------------------- void MediaWindowBaseImpl::setVolumeDB( sal_Int16 nVolumeDB ) { if( mxPlayer.is() ) mxPlayer->setVolumeDB( nVolumeDB ); } // --------------------------------------------------------------------- sal_Int16 MediaWindowBaseImpl::getVolumeDB() const { return( mxPlayer.is() ? mxPlayer->getVolumeDB() : 0 ); } // ------------------------------------------------------------------------- void MediaWindowBaseImpl::updateMediaItem( MediaItem& rItem ) const { if( isPlaying() ) rItem.setState( ( getRate() > 1.0 ) ? MEDIASTATE_PLAYFFW : MEDIASTATE_PLAY ); else rItem.setState( ( 0.0 == getMediaTime() ) ? MEDIASTATE_STOP : MEDIASTATE_PAUSE ); rItem.setDuration( getDuration() ); rItem.setTime( getMediaTime() ); rItem.setLoop( isPlaybackLoop() ); rItem.setMute( isMute() ); rItem.setVolumeDB( getVolumeDB() ); rItem.setZoom( getZoom() ); rItem.setURL( getURL() ); } // ------------------------------------------------------------------------- void MediaWindowBaseImpl::executeMediaItem( const MediaItem& rItem ) { const sal_uInt32 nMaskSet = rItem.getMaskSet(); // set URL first if( nMaskSet & AVMEDIA_SETMASK_URL ) setURL( rItem.getURL() ); // set different states next if( nMaskSet & AVMEDIA_SETMASK_TIME ) setMediaTime( ::std::min( rItem.getTime(), getDuration() ) ); if( nMaskSet & AVMEDIA_SETMASK_LOOP ) setPlaybackLoop( rItem.isLoop() ); if( nMaskSet & AVMEDIA_SETMASK_MUTE ) setMute( rItem.isMute() ); if( nMaskSet & AVMEDIA_SETMASK_VOLUMEDB ) setVolumeDB( rItem.getVolumeDB() ); if( nMaskSet & AVMEDIA_SETMASK_ZOOM ) setZoom( rItem.getZoom() ); // set play state at last if( nMaskSet & AVMEDIA_SETMASK_STATE ) { switch( rItem.getState() ) { case( MEDIASTATE_PLAY ): case( MEDIASTATE_PLAYFFW ): { /* const double fNewRate = ( ( MEDIASTATE_PLAYFFW == rItem.getState() ) ? AVMEDIA_FFW_PLAYRATE : 1.0 ); if( getRate() != fNewRate ) setRate( fNewRate ); */ if( !isPlaying() ) start(); } break; case( MEDIASTATE_PAUSE ): { if( isPlaying() ) stop(); } break; case( MEDIASTATE_STOP ): { if( isPlaying() ) { setMediaTime( 0.0 ); stop(); setMediaTime( 0.0 ); } } break; } } } } // namespace priv } // namespace avemdia <|endoftext|>
<commit_before>/// Learn from https://github.com/p-ranav/indicators #ifndef BAULK_INDICATORS_HPP #define BAULK_INDICATORS_HPP #include <bela/stdwriter.hpp> #include <algorithm> #include <atomic> #include <cassert> #include <chrono> #include <cmath> #include <thread> #include <condition_variable> #include <memory> #include <type_traits> #include <utility> #include <vector> namespace baulk { [[maybe_unused]] constexpr uint64_t KB = 1024ULL; [[maybe_unused]] constexpr uint64_t MB = KB * 1024; [[maybe_unused]] constexpr uint64_t GB = MB * 1024; [[maybe_unused]] constexpr uint64_t TB = GB * 1024; [[maybe_unused]] constexpr uint32_t MAX_BARLENGTH = 256; template <size_t N> void EncodeRate(wchar_t (&buf)[N], uint64_t x) { if (x >= TB) { _snwprintf_s(buf, N, L"%.2fT", (double)x / TB); return; } if (x >= GB) { _snwprintf_s(buf, N, L"%.2fG", (double)x / GB); return; } if (x >= MB) { _snwprintf_s(buf, N, L"%.2fM", (double)x / MB); return; } if (x > 10 * KB) { _snwprintf_s(buf, N, L"%.2fK", (double)x / KB); return; } _snwprintf_s(buf, N, L"%lldB", x); } enum ProgressState : uint32_t { Running = 33, Completed = 32, Fault = 31 }; class ProgressBar { public: ProgressBar() = default; ProgressBar(const ProgressBar &) = delete; ProgressBar &operator=(const ProgressBar &) = delete; void Maximum(uint64_t mx) { maximum = mx; } void FileName(std::wstring_view fn) { filename = fn; if (filename.size() >= 20) { flen = filename.size(); filename.append(flen, L' '); } } void Update(uint64_t value) { total = value; } void Execute() { worker = std::make_shared<std::thread>([this] { // Progress Loop space.resize(MAX_BARLENGTH + 4, L' '); scs.resize(MAX_BARLENGTH + 4, L'#'); this->Loop(); }); } void Finish() { { std::lock_guard<std::mutex> lock(mtx); active = false; } cv.notify_all(); worker->join(); } void MarkFault() { state = ProgressState::Fault; } void MarkCompleted() { state = ProgressState::Completed; } private: uint64_t maximum{0}; uint64_t previous{0}; mutable std::condition_variable cv; mutable std::mutex mtx; std::shared_ptr<std::thread> worker; std::atomic_uint64_t total{0}; std::atomic_bool active{true}; std::wstring space; std::wstring scs; std::wstring filename; std::atomic_uint32_t state{ProgressState::Running}; uint32_t fnpos{0}; uint32_t pos{0}; uint32_t tick{0}; uint32_t width{80}; size_t flen{20}; inline std::wstring_view MakeSpace(size_t n) { if (n > MAX_BARLENGTH) { return std::wstring_view{}; } return std::wstring_view{space.data(), n}; } inline std::wstring_view MakeRate(size_t n) { if (n > MAX_BARLENGTH) { return std::wstring_view{}; } return std::wstring_view{scs.data(), n}; } inline std::wstring_view MakeFileName() { if (filename.size() <= 19) { return filename; } std::wstring_view sv{filename.data() + fnpos, 19}; fnpos++; if (fnpos == flen) { fnpos = 0; } return sv; } void Loop() { while (active) { { std::unique_lock lock(mtx); cv.wait_for(lock, std::chrono::milliseconds(100)); } // --- draw progress bar Draw(); } bela::FPrintF(stderr, L"\n"); } void Draw() { auto w = bela::TerminalWidth(); if (w != 0 && w <= MAX_BARLENGTH && w != width) { width = w; bela::FPrintF(stderr, L"\r\x1b[0m%s\x1b[0m", MakeSpace((std::min)(w, MAX_BARLENGTH))); } if (width < 80) { width = 80; } // file.tar.gz 17%[###############> ] 1024.00K 1024.00K/s auto barwidth = width - 50; wchar_t totalsuffix[64]; wchar_t ratesuffix[64]; auto total_ = static_cast<uint64_t>(total); pos++; if (pos == barwidth - 3) { pos = 0; } //' 1024.00K 1024.00K/s' 20 auto delta = (total_ - previous) * 10; // cycle 50/1000 s previous = total_; EncodeRate(totalsuffix, total_); EncodeRate(ratesuffix, delta); if (maximum == 0) { // file.tar.gz [ <=> ] 1024.00K 1024.00K/s constexpr std::wstring_view bounce = L"<=>"; // '<=>' auto s0 = MakeSpace(pos); auto s1 = MakeSpace(barwidth - pos); bela::FPrintF(stderr, L"\r\x1b[01;%dm%s [%s%s%s] %s %s/s \x1b[0m", (uint32_t)state, MakeFileName(), s0, bounce, s1, totalsuffix, ratesuffix); return; } auto scale = total_ * 100 / maximum; auto progress = scale * barwidth / 100; auto ps = MakeRate(static_cast<size_t>(progress)); auto sps = MakeSpace(static_cast<size_t>(barwidth - progress)); bela::FPrintF(stderr, L"\r\x1b[01;%dm%s %d%% [%s%s] %s %s/s \x1b[0m", (uint32_t)state, MakeFileName(), scale, ps, sps, totalsuffix, ratesuffix); } }; } // namespace baulk #endif<commit_msg>[baulk] better progress speed<commit_after>/// Learn from https://github.com/p-ranav/indicators #ifndef BAULK_INDICATORS_HPP #define BAULK_INDICATORS_HPP #include <bela/stdwriter.hpp> #include <algorithm> #include <atomic> #include <cassert> #include <chrono> #include <cmath> #include <thread> #include <condition_variable> #include <memory> #include <type_traits> #include <utility> #include <vector> namespace baulk { [[maybe_unused]] constexpr uint64_t KB = 1024ULL; [[maybe_unused]] constexpr uint64_t MB = KB * 1024; [[maybe_unused]] constexpr uint64_t GB = MB * 1024; [[maybe_unused]] constexpr uint64_t TB = GB * 1024; [[maybe_unused]] constexpr uint32_t MAX_BARLENGTH = 256; template <size_t N> void EncodeRate(wchar_t (&buf)[N], uint64_t x) { if (x >= TB) { _snwprintf_s(buf, N, L"%.2fT", (double)x / TB); return; } if (x >= GB) { _snwprintf_s(buf, N, L"%.2fG", (double)x / GB); return; } if (x >= MB) { _snwprintf_s(buf, N, L"%.2fM", (double)x / MB); return; } if (x > 10 * KB) { _snwprintf_s(buf, N, L"%.2fK", (double)x / KB); return; } _snwprintf_s(buf, N, L"%lldB", x); } enum ProgressState : uint32_t { Running = 33, Completed = 32, Fault = 31 }; class ProgressBar { public: ProgressBar() = default; ProgressBar(const ProgressBar &) = delete; ProgressBar &operator=(const ProgressBar &) = delete; void Maximum(uint64_t mx) { maximum = mx; } void FileName(std::wstring_view fn) { filename = fn; if (filename.size() >= 20) { flen = filename.size(); filename.append(flen, L' '); } } void Update(uint64_t value) { total = value; } void Execute() { worker = std::make_shared<std::thread>([this] { // Progress Loop space.resize(MAX_BARLENGTH + 4, L' '); scs.resize(MAX_BARLENGTH + 4, L'#'); memset(speed, 0, sizeof(speed)); this->Loop(); }); } void Finish() { { std::lock_guard<std::mutex> lock(mtx); active = false; } cv.notify_all(); worker->join(); } void MarkFault() { state = ProgressState::Fault; } void MarkCompleted() { state = ProgressState::Completed; } private: uint64_t maximum{0}; uint64_t previous{0}; mutable std::condition_variable cv; mutable std::mutex mtx; std::shared_ptr<std::thread> worker; std::atomic_uint64_t total{0}; std::atomic_bool active{true}; std::wstring space; std::wstring scs; std::wstring filename; std::atomic_uint32_t state{ProgressState::Running}; wchar_t speed[64]; uint32_t tick{0}; uint32_t fnpos{0}; uint32_t pos{0}; uint32_t width{80}; size_t flen{20}; inline std::wstring_view MakeSpace(size_t n) { if (n > MAX_BARLENGTH) { return std::wstring_view{}; } return std::wstring_view{space.data(), n}; } inline std::wstring_view MakeRate(size_t n) { if (n > MAX_BARLENGTH) { return std::wstring_view{}; } return std::wstring_view{scs.data(), n}; } inline std::wstring_view MakeFileName() { if (filename.size() <= 19) { return filename; } std::wstring_view sv{filename.data() + fnpos, 19}; fnpos++; if (fnpos == flen) { fnpos = 0; } return sv; } void Loop() { while (active) { { std::unique_lock lock(mtx); cv.wait_for(lock, std::chrono::milliseconds(100)); } // --- draw progress bar Draw(); } bela::FPrintF(stderr, L"\n"); } void Draw() { auto w = bela::TerminalWidth(); if (w != 0 && w <= MAX_BARLENGTH && w != width) { width = w; bela::FPrintF(stderr, L"\r\x1b[0m%s\x1b[0m", MakeSpace((std::min)(w, MAX_BARLENGTH))); } if (width < 80) { width = 80; } // file.tar.gz 17%[###############> ] 1024.00K 1024.00K/s auto barwidth = width - 50; wchar_t strtotal[64]; auto total_ = static_cast<uint64_t>(total); //' 1024.00K 1024.00K/s' 20 EncodeRate(strtotal, total_); if (tick % 10 == 0) { auto delta = (total_ - previous); // cycle 50/1000 s previous = total_; EncodeRate(speed, delta); } tick++; if (maximum == 0) { // file.tar.gz [ <=> ] 1024.00K 1024.00K/s constexpr std::wstring_view bounce = L"<=>"; pos++; if (pos == barwidth - 3) { pos = 0; } // '<=>' auto s0 = MakeSpace(pos); auto s1 = MakeSpace(barwidth - pos); bela::FPrintF(stderr, L"\r\x1b[01;%dm%s [%s%s%s] %s %s/s \x1b[0m", (uint32_t)state, MakeFileName(), s0, bounce, s1, strtotal, speed); return; } auto scale = total_ * 100 / maximum; auto progress = scale * barwidth / 100; auto ps = MakeRate(static_cast<size_t>(progress)); auto sps = MakeSpace(static_cast<size_t>(barwidth - progress)); bela::FPrintF(stderr, L"\r\x1b[01;%dm%s %d%% [%s%s] %s %s/s \x1b[0m", (uint32_t)state, MakeFileName(), scale, ps, sps, strtotal, speed); } }; } // namespace baulk #endif<|endoftext|>
<commit_before>#ifndef VEXCL_SPMAT_INLINE_SPMV_HPP #define VEXCL_SPMAT_INLINE_SPMV_HPP /* The MIT License Copyright (c) 2012-2013 Denis Demidov <[email protected]> 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. */ /** * \file vexcl/spmat/inline_spmv.hpp * \author Denis Demidov <[email protected]> * \brief Inline SpMV operation. */ #include <vexcl/spmat.hpp> namespace vex { /// \cond INTERNAL struct inline_spmv_terminal {}; struct mv_inline_spmv_terminal {}; typedef vector_expression< typename boost::proto::terminal< inline_spmv_terminal >::type > inline_spmv_terminal_expression; template <typename val_t, typename col_t, typename idx_t> struct inline_spmv : inline_spmv_terminal_expression { typedef spmv<val_t, col_t, idx_t> Base; const typename Base::mat &A; const typename Base::vec &x; inline_spmv(const Base &base) : A(base.A), x(base.x) {} }; typedef multivector_expression< typename boost::proto::terminal< mv_inline_spmv_terminal >::type > mv_inline_spmv_terminal_expression; template <typename val_t, typename col_t, typename idx_t, class MV> struct mv_inline_spmv : mv_inline_spmv_terminal_expression { typedef multispmv<val_t, col_t, idx_t, MV> Base; const typename Base::mat &A; const MV &x; mv_inline_spmv(const Base &base) : A(base.A), x(base.x) {} }; /// \endcond template <typename val_t, typename col_t, typename idx_t> inline_spmv<val_t, col_t, idx_t> make_inline(const spmv<val_t, col_t, idx_t> &base) { precondition(base.x.nparts() == 1, "Can not inline multi-device SpMV operation."); return inline_spmv<val_t, col_t, idx_t>(base); } template <typename val_t, typename col_t, typename idx_t, class MV> mv_inline_spmv<val_t, col_t, idx_t, MV> make_inline(const multispmv<val_t, col_t, idx_t, MV> &base) { precondition(base.x(0).nparts() == 1, "Can not inline multi-device SpMV operation."); return mv_inline_spmv<val_t, col_t, idx_t, MV>(base); } /// \cond INTERNAL // Allow inline products to participate in vector expressions: template <> struct is_vector_expr_terminal< inline_spmv_terminal > : std::true_type { }; template <> struct is_multivector_expr_terminal< mv_inline_spmv_terminal > : std::true_type { }; template <> struct proto_terminal_is_value< mv_inline_spmv_terminal > : std::true_type { }; template <size_t I, typename val_t, typename col_t, typename idx_t, typename MV> struct component< I, mv_inline_spmv<val_t, col_t, idx_t, MV> > { typedef inline_spmv<val_t, col_t, idx_t> type; }; template <size_t I, typename val_t, typename col_t, typename idx_t, typename MV> inline_spmv<val_t, col_t, idx_t> get(const mv_inline_spmv<val_t, col_t, idx_t, MV> &t) { return make_inline(t.A * t.x(I)); } template <typename val_t, typename col_t, typename idx_t> struct kernel_name< inline_spmv<val_t, col_t, idx_t> > { static std::string get() { return "spmv_"; } }; template <typename val_t, typename col_t, typename idx_t> struct partial_vector_expr< inline_spmv<val_t, col_t, idx_t> > { static std::string get(const cl::Device &device, int component, int position, kernel_generator_state &state) { return SpMat<val_t, col_t, idx_t>::inline_expression(device, component, position, state); } }; template <typename val_t, typename col_t, typename idx_t> struct terminal_preamble< inline_spmv<val_t, col_t, idx_t> > { static std::string get(const cl::Device &device, int component, int position, kernel_generator_state &state) { return SpMat<val_t, col_t, idx_t>::inline_preamble(device, component, position, state); } }; template <typename val_t, typename col_t, typename idx_t> struct kernel_param_declaration< inline_spmv<val_t, col_t, idx_t> > { static std::string get(const cl::Device &device, int component, int position, kernel_generator_state &state) { return SpMat<val_t, col_t, idx_t>::inline_parameters(device, component, position, state); } }; template <typename val_t, typename col_t, typename idx_t> struct kernel_arg_setter< inline_spmv<val_t, col_t, idx_t> > { static void set(cl::Kernel &kernel, uint device, size_t index_offset, uint &position, const inline_spmv<val_t, col_t, idx_t> &term, kernel_generator_state &state) { SpMat<val_t, col_t, idx_t>::inline_arguments( kernel, device, index_offset, position, term.A, term.x, state ); } }; template <typename val_t, typename col_t, typename idx_t> struct expression_properties< inline_spmv<val_t, col_t, idx_t> > { static void get(const inline_spmv<val_t, col_t, idx_t> &term, std::vector<cl::CommandQueue> &queue_list, std::vector<size_t> &partition, size_t &size ) { expression_properties< vector<val_t> >::get(term.x, queue_list, partition, size); } }; /// \endcond } // namespace vex #endif <commit_msg>Documenting make_inline() functions<commit_after>#ifndef VEXCL_SPMAT_INLINE_SPMV_HPP #define VEXCL_SPMAT_INLINE_SPMV_HPP /* The MIT License Copyright (c) 2012-2013 Denis Demidov <[email protected]> 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. */ /** * \file vexcl/spmat/inline_spmv.hpp * \author Denis Demidov <[email protected]> * \brief Inline SpMV operation. */ #include <vexcl/spmat.hpp> namespace vex { /// \cond INTERNAL struct inline_spmv_terminal {}; struct mv_inline_spmv_terminal {}; typedef vector_expression< typename boost::proto::terminal< inline_spmv_terminal >::type > inline_spmv_terminal_expression; template <typename val_t, typename col_t, typename idx_t> struct inline_spmv : inline_spmv_terminal_expression { typedef spmv<val_t, col_t, idx_t> Base; const typename Base::mat &A; const typename Base::vec &x; inline_spmv(const Base &base) : A(base.A), x(base.x) {} }; typedef multivector_expression< typename boost::proto::terminal< mv_inline_spmv_terminal >::type > mv_inline_spmv_terminal_expression; template <typename val_t, typename col_t, typename idx_t, class MV> struct mv_inline_spmv : mv_inline_spmv_terminal_expression { typedef multispmv<val_t, col_t, idx_t, MV> Base; const typename Base::mat &A; const MV &x; mv_inline_spmv(const Base &base) : A(base.A), x(base.x) {} }; /// \endcond /// Inlines a sparse matrix - vector product. /** * When applied to a matrix-vector product, the product becomes inlineable. * That is, it may be used in any vector expression (not just additive * expression). This is only possible in single-device contexts, so user has to * guarantee that. * * Example: * \code * // Get maximum residual value: * eps = sum( fabs(f - vex::make_inline(A * x)) ); * \endcode */ template <typename val_t, typename col_t, typename idx_t> inline_spmv<val_t, col_t, idx_t> make_inline(const spmv<val_t, col_t, idx_t> &base) { precondition(base.x.nparts() == 1, "Can not inline multi-device SpMV operation."); return inline_spmv<val_t, col_t, idx_t>(base); } /// Inlines a sparse matrix - multivector product. /** * When applied to a matrix-multivector product, the product becomes * inlineable. That is, it may be used in any multivector expression (not just * additive expression). This is only possible in single-device contexts, so * user has to guarantee that. * * Example: * \code * // Get maximum residual value: * eps = sum( fabs(f - vex::make_inline(A * x)) ); * \endcode */ template <typename val_t, typename col_t, typename idx_t, class MV> mv_inline_spmv<val_t, col_t, idx_t, MV> make_inline(const multispmv<val_t, col_t, idx_t, MV> &base) { precondition(base.x(0).nparts() == 1, "Can not inline multi-device SpMV operation."); return mv_inline_spmv<val_t, col_t, idx_t, MV>(base); } /// \cond INTERNAL // Allow inline products to participate in vector expressions: template <> struct is_vector_expr_terminal< inline_spmv_terminal > : std::true_type { }; template <> struct is_multivector_expr_terminal< mv_inline_spmv_terminal > : std::true_type { }; template <> struct proto_terminal_is_value< mv_inline_spmv_terminal > : std::true_type { }; template <size_t I, typename val_t, typename col_t, typename idx_t, typename MV> struct component< I, mv_inline_spmv<val_t, col_t, idx_t, MV> > { typedef inline_spmv<val_t, col_t, idx_t> type; }; template <size_t I, typename val_t, typename col_t, typename idx_t, typename MV> inline_spmv<val_t, col_t, idx_t> get(const mv_inline_spmv<val_t, col_t, idx_t, MV> &t) { return make_inline(t.A * t.x(I)); } template <typename val_t, typename col_t, typename idx_t> struct kernel_name< inline_spmv<val_t, col_t, idx_t> > { static std::string get() { return "spmv_"; } }; template <typename val_t, typename col_t, typename idx_t> struct partial_vector_expr< inline_spmv<val_t, col_t, idx_t> > { static std::string get(const cl::Device &device, int component, int position, kernel_generator_state &state) { return SpMat<val_t, col_t, idx_t>::inline_expression(device, component, position, state); } }; template <typename val_t, typename col_t, typename idx_t> struct terminal_preamble< inline_spmv<val_t, col_t, idx_t> > { static std::string get(const cl::Device &device, int component, int position, kernel_generator_state &state) { return SpMat<val_t, col_t, idx_t>::inline_preamble(device, component, position, state); } }; template <typename val_t, typename col_t, typename idx_t> struct kernel_param_declaration< inline_spmv<val_t, col_t, idx_t> > { static std::string get(const cl::Device &device, int component, int position, kernel_generator_state &state) { return SpMat<val_t, col_t, idx_t>::inline_parameters(device, component, position, state); } }; template <typename val_t, typename col_t, typename idx_t> struct kernel_arg_setter< inline_spmv<val_t, col_t, idx_t> > { static void set(cl::Kernel &kernel, uint device, size_t index_offset, uint &position, const inline_spmv<val_t, col_t, idx_t> &term, kernel_generator_state &state) { SpMat<val_t, col_t, idx_t>::inline_arguments( kernel, device, index_offset, position, term.A, term.x, state ); } }; template <typename val_t, typename col_t, typename idx_t> struct expression_properties< inline_spmv<val_t, col_t, idx_t> > { static void get(const inline_spmv<val_t, col_t, idx_t> &term, std::vector<cl::CommandQueue> &queue_list, std::vector<size_t> &partition, size_t &size ) { expression_properties< vector<val_t> >::get(term.x, queue_list, partition, size); } }; /// \endcond } // namespace vex #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: macros.hxx,v $ * * $Revision: 1.15 $ * * last change: $Author: hr $ $Date: 2003-04-28 16:26:28 $ * * 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 _CPPU_MACROS_HXX_ #define _CPPU_MACROS_HXX_ #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _UNO_LBNAMES_H_ #include <uno/lbnames.h> #endif /** Namespace name for compiler/ platform, e.g. gcc3, msci */ #define CPPU_CURRENT_NAMESPACE CPPU_ENV /** Patching the gcc 3 incomatible alignment change for linux. This pragma macro is appended by the cppumaker tool to every first member of a struct, iff the struct inherits from a base struct the first member is no double or [unsigned] long long. @internal */ #if defined(__GNUC__) && (defined(LINUX) || defined(FREEBSD)) && (defined(INTEL) || defined(POWERPC) || defined(X86_64) || defined(S390) || defined(SPARC)) && (__GNUC__ == 3) #define CPPU_GCC3_ALIGN( base_struct ) __attribute__ ((aligned (__alignof__ (base_struct)))) #else #define CPPU_GCC3_ALIGN( base_struct ) #endif #endif // _CPPU_MACROS_HXX_ <commit_msg>INTEGRATION: CWS ooo11rc2 (1.15.14); FILE MERGED 2003/07/14 14:29:55 fa 1.15.14.1: Generalize the CPPU_GCC3_ALIGN define for all gcc 3 platforms instead of explicitly specifying all of them.<commit_after>/************************************************************************* * * $RCSfile: macros.hxx,v $ * * $Revision: 1.16 $ * * last change: $Author: hr $ $Date: 2003-07-16 17:38:25 $ * * 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 _CPPU_MACROS_HXX_ #define _CPPU_MACROS_HXX_ #ifndef _SAL_TYPES_H_ #include <sal/types.h> #endif #ifndef _UNO_LBNAMES_H_ #include <uno/lbnames.h> #endif /** Namespace name for compiler/ platform, e.g. gcc3, msci */ #define CPPU_CURRENT_NAMESPACE CPPU_ENV /** Patching the gcc 3 incomatible alignment change for linux. This pragma macro is appended by the cppumaker tool to every first member of a struct, iff the struct inherits from a base struct the first member is no double or [unsigned] long long. @internal */ #if defined(__GNUC__) && (__GNUC__ >= 3) #define CPPU_GCC3_ALIGN( base_struct ) __attribute__ ((aligned (__alignof__ (base_struct)))) #else #define CPPU_GCC3_ALIGN( base_struct ) #endif #endif // _CPPU_MACROS_HXX_ <|endoftext|>
<commit_before>// fidi_request_handler.cc --- -*- mode: c++; -*- // Copyright 2018-2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. /// \file /// \ingroup app /// /// This file provides the implementation of the request handling /// functionality for the fidi (φίδι) HTTP server. This creates /// multiple instances of the fidi::AppCaller class to actually make /// downstream calls. This sets up a priority queue, a threadpool, and /// a task manager to handle calls in parallel and in sequence. // Code: #include "src/fidi_request_handler.h" void fidi::FidiRequestHandler::handleRequest(Poco::Net::HTTPServerRequest & req, Poco::Net::HTTPServerResponse &resp) { std::ostream &response_stream = resp.send(); Poco::Logger::get("ConsoleLogger") .information("Request from " + req.clientAddress().toString()); bool failed = false; resp.setChunkedTransferEncoding(true); resp.setContentType("text/html"); response_stream << "<html><head><title>Fidi (φίδι) -- a service mock " "instance\n</title></head>\n" "<body>\n" "<h1>Hello world!</h1>\n" "<p>Count: " << ++count_ << "</p>\n" "<p>Method: " << req.getMethod() << "</p>\n" "<p>URI: " << req.getURI() << "</p>\n"; try { driver_.Parse(req.stream()); } catch (std::bad_alloc &ba) { std::cerr << "Got memory error: " << ba.what() << "\n"; std::cerr.flush(); return; } // Fail fast on OOM auto parse_errors = driver_.get_errors(); if (parse_errors.first != 0) { // take action to return errors // Set response, generate error message resp.setStatus(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST); response_stream << " <h2>Parse Syntax Errors</h2>\n\n\n" << parse_errors.second; Poco::Logger::get("ConsoleLogger").error("Errors " + parse_errors.second); Poco::Logger::get("FileLogger").error("Errors " + parse_errors.second); failed = true; } std::string warning_message; int warning = driver_.SanityChecks(&warning_message); if (warning) { resp.setStatus(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST); response_stream << " <h2>Warning</h2>\n\n\n" << warning_message; Poco::Logger::get("ConsoleLogger").warning("Warnings " + warning_message); Poco::Logger::get("FileLogger").warning("Warnings " + warning_message); failed = true; } if (!failed) { driver_.set_resp(resp); try { Poco::Logger::get("ConsoleLogger").trace("Request parsed OK."); driver_.Execute(response_stream); } catch (std::bad_alloc &ba) { std::cerr << "Got memory error: " << ba.what() << "\n"; std::cerr.flush(); return; } // Fail fast on OOM } response_stream << "</body></html>"; response_stream.flush(); Poco::Logger::get("FileLogger") .trace("Response sent for count=" + std::to_string(count_) + " and URI=" + req.getURI() + "\n"); } // // fidi_request_handler.cc ends here <commit_msg>[fidi]: Implement a /healthz mechanism<commit_after>// fidi_request_handler.cc --- -*- mode: c++; -*- // Copyright 2018-2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. /// \file /// \ingroup app /// /// This file provides the implementation of the request handling /// functionality for the fidi (φίδι) HTTP server. This creates /// multiple instances of the fidi::AppCaller class to actually make /// downstream calls. This sets up a priority queue, a threadpool, and /// a task manager to handle calls in parallel and in sequence. // Code: #include "src/fidi_request_handler.h" void fidi::FidiRequestHandler::handleRequest(Poco::Net::HTTPServerRequest & req, Poco::Net::HTTPServerResponse &resp) { std::ostream &response_stream = resp.send(); Poco::Logger::get("ConsoleLogger") .information("Request from " + req.clientAddress().toString()); bool failed = false; resp.setChunkedTransferEncoding(true); resp.setContentType("text/html"); Poco::URI uri(req.getURI()); if (uri.getPath().compare("/healthz") == 0) { Poco::Logger::get("FileLogger").trace("Healthz"); // TODO: Check for and set a not OK status if we are not healthy resp.setStatus(Poco::Net::HTTPResponse::HTTP_OK); return; } response_stream << "<html><head><title>Fidi (φίδι) -- a service mock " "instance\n</title></head>\n" "<body>\n" "<h1>Hello world!</h1>\n" "<p>Count: " << ++count_ << "</p>\n" "<p>Method: " << req.getMethod() << "</p>\n" "<p>URI: " << req.getURI() << "</p>\n"; try { driver_.Parse(req.stream()); } catch (std::bad_alloc &ba) { std::cerr << "Got memory error: " << ba.what() << "\n"; std::cerr.flush(); return; } // Fail fast on OOM auto parse_errors = driver_.get_errors(); if (parse_errors.first != 0) { // take action to return errors // Set response, generate error message resp.setStatus(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST); response_stream << " <h2>Parse Syntax Errors</h2>\n\n\n" << parse_errors.second; Poco::Logger::get("ConsoleLogger").error("Errors " + parse_errors.second); Poco::Logger::get("FileLogger").error("Errors " + parse_errors.second); failed = true; } std::string warning_message; int warning = driver_.SanityChecks(&warning_message); if (warning) { resp.setStatus(Poco::Net::HTTPResponse::HTTP_BAD_REQUEST); response_stream << " <h2>Warning</h2>\n\n\n" << warning_message; Poco::Logger::get("ConsoleLogger").warning("Warnings " + warning_message); Poco::Logger::get("FileLogger").warning("Warnings " + warning_message); failed = true; } if (!failed) { driver_.set_resp(resp); try { Poco::Logger::get("ConsoleLogger").trace("Request parsed OK."); driver_.Execute(response_stream); } catch (std::bad_alloc &ba) { std::cerr << "Got memory error: " << ba.what() << "\n"; std::cerr.flush(); return; } // Fail fast on OOM } response_stream << "</body></html>"; response_stream.flush(); Poco::Logger::get("FileLogger") .trace("Response sent for count=" + std::to_string(count_) + " and URI=" + req.getURI() + "\n"); } // // fidi_request_handler.cc ends here <|endoftext|>
<commit_before>// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, [email protected] // // This file is part of Virvo. // // Virvo 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 (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #ifdef HAVE_CONFIG_H #include "vvconfig.h" #endif #include "vvdebugmsg.h" #include "vvinttypes.h" #include "vvmulticast.h" #include "vvsocketmonitor.h" #include "vvinttypes.h" #include <algorithm> #include <cmath> #ifdef HAVE_NORM #include <normApi.h> #include <stdlib.h> #endif vvMulticast::vvMulticast(const char* addr, const ushort port, const MulticastType type, const MulticastApi api) : _type(type), _api(api) { if(VV_NORM == _api) { #ifdef HAVE_NORM _instance = NormCreateInstance(); _session = NormCreateSession(_instance, addr, port, NORM_NODE_ANY); NormSetCongestionControl(_session, true); if(VV_SENDER == type) { NormSessionId sessionId = (NormSessionId)rand(); // TODO: Adjust these numbers depending on the used network topology NormSetTransmitRate(_session, 8e10); NormSetTransmitCacheBounds(_session, CHUNK_SIZE, 1, 128); //NormSetGroupSize(_session, 10); NormStartSender(_session, sessionId, 1024*1024, 1400, 64, 2); NormSetTxSocketBuffer(_session, 1024*1024*32); } else if(VV_RECEIVER == type) { NormStartReceiver(_session, 1024*1024); NormSetRxSocketBuffer(_session, 1024*1024*64); NormDescriptor normDesc = NormGetDescriptor(_instance); _nodes.push_back(NormGetLocalNodeId(_session)); _normSocket = new vvSocket(vvSocket::VV_UDP, int(normDesc)); } #else (void)addr; (void)port; #endif } else if(VV_VVSOCKET == _api) { if(VV_SENDER == _type) { _socket = new vvSocket(port, addr, vvSocket::VV_MC_SENDER); } else if(VV_RECEIVER == _type) { _socket = new vvSocket(port, addr, vvSocket::VV_MC_RECEIVER); } _socket->init(); } } vvMulticast::~vvMulticast() { if(VV_NORM == _api) { #ifdef HAVE_NORM if(VV_SENDER == _type) { NormStopSender(_session); } else if(VV_RECEIVER == _type) { NormStopReceiver(_session); delete _normSocket; } NormDestroySession(_session); NormDestroyInstance(_instance); #endif } else if(VV_VVSOCKET == _api) { delete _socket; } } ssize_t vvMulticast::write(const uchar* bytes, const size_t size, double timeout) { vvDebugMsg::msg(3, "vvMulticast::write()"); if(VV_NORM == _api) { #ifdef HAVE_NORM for(std::vector<NormNodeId>::const_iterator it = _nodes.begin(); it != _nodes.end(); ++it) { NormAddAckingNode(_session, *it); } for(unsigned int i=0; i<size; i+=CHUNK_SIZE) { size_t frameSize = std::min(size_t(CHUNK_SIZE), size); _object = NormDataEnqueue(_session, (char*)&bytes[i*CHUNK_SIZE], frameSize); NormSetWatermark(_session, _object); if(NORM_OBJECT_INVALID ==_object) { vvDebugMsg::msg(2, "vvMulticast::write(): Norm Object is invalid!"); return -2; } NormDescriptor normDesc = NormGetDescriptor(_instance); vvSocketMonitor* monitor = new vvSocketMonitor; std::vector<vvSocket*> sock; sock.push_back(new vvSocket(vvSocket::VV_UDP, int(normDesc))); monitor->setReadFds(sock); NormEvent theEvent; size_t bytesSent = 0; bool keepGoing = true; while(keepGoing) { vvSocket* ready = NULL; vvSocketMonitor::ErrorType err = monitor->wait(&ready, &timeout); if(vvSocketMonitor::VV_TIMEOUT == err) { vvDebugMsg::msg(2, "vvMulticast::write() timeout reached."); return bytesSent; } else if(vvSocketMonitor::VV_ERROR == err) { vvDebugMsg::msg(2, "vvMulticast::write() error."); return -1; } else { NormGetNextEvent(_instance, &theEvent); switch(theEvent.type) { case NORM_CC_ACTIVE: vvDebugMsg::msg(3, "vvMulticast::write() NORM_CC_ACTIVE: transmission still active"); break; case NORM_TX_FLUSH_COMPLETED: case NORM_LOCAL_SENDER_CLOSED: case NORM_TX_OBJECT_SENT: vvDebugMsg::msg(3, "vvMulticast::write(): chunk-transfer completed."); bytesSent += size_t(NormObjectGetSize(theEvent.object)); keepGoing = false; break; default: { std::string eventmsg = std::string("vvMulticast::write() Norm-Event: "); eventmsg += theEvent.type; vvDebugMsg::msg(3, eventmsg.c_str()); break; } } } } } return size; #else (void)bytes; (void)size; (void)timeout; return -1; #endif } else { // number datagrams uchar *ndata = numberConsecutively(bytes, size); size_t nsize = size+(ceil(float(size)/float((DGRAM_SIZE-4)))*4); size_t nleft = nsize; while(nleft > 0) { size_t towrite = std::min(size_t(DGRAM_SIZE), nleft); vvSocket::ErrorType err = _socket->write_data((uchar*)&ndata[nsize-nleft], towrite); if(vvSocket::VV_OK != err) { vvDebugMsg::msg(1, "vvMulticast::write() error", true); return -1; } else { nleft -= towrite; } } return size; } } ssize_t vvMulticast::read(uchar* data, const size_t size, double timeout) { vvDebugMsg::msg(3, "vvMulticast::read()"); if(VV_NORM == _api) { #ifdef HAVE_NORM vvSocketMonitor monitor; std::vector<vvSocket*> sock; sock.push_back(_normSocket); monitor.setReadFds(sock); NormEvent theEvent; size_t chunk = 0; size_t bytesReceived = 0; bool keepGoing = true; do { vvSocket* ready = NULL; vvSocketMonitor::ErrorType err = monitor.wait(&ready, &timeout); if(vvSocketMonitor::VV_TIMEOUT == err) { vvDebugMsg::msg(2, "vvMulticast::read() timeout reached."); return bytesReceived; } else if(vvSocketMonitor::VV_ERROR == err) { vvDebugMsg::msg(2, "vvMulticast::read() error."); return -1; } else { NormGetNextEvent(_instance, &theEvent); switch(theEvent.type) { case NORM_RX_OBJECT_UPDATED: vvDebugMsg::msg(3, "vvMulticast::read() NORM_RX_OBJECT_UPDATED: the identified receive object has newly received data content."); break; case NORM_RX_OBJECT_COMPLETED: { vvDebugMsg::msg(3, "vvMulticast::read() NORM_RX_OBJECT_COMPLETED: transfer completed."); bytesReceived += size_t(NormObjectGetSize(theEvent.object)); // copy data into array uchar *t_data = (uchar*)NormDataDetachData(theEvent.object); for(int i=0;i<NormObjectGetSize(theEvent.object);i++) { data[i+chunk*CHUNK_SIZE] = t_data[i]; } chunk++; break; } case NORM_RX_OBJECT_ABORTED: vvDebugMsg::msg(2, "vvMulticast::read() NORM_RX_OBJECT_ABORTED: transfer incomplete!"); return -1; break; default: { std::string eventmsg = std::string("vvMulticast::read() Norm-Event: "); eventmsg += theEvent.type; vvDebugMsg::msg(3, eventmsg.c_str()); break; } } } if(bytesReceived >= size) keepGoing = false; } while((0.0 < timeout || -1.0 == timeout) && keepGoing); return bytesReceived; #else (void)size; (void)data; (void)timeout; return -1; #endif } else { size_t nsize = size+(ceil(float(size)/float((DGRAM_SIZE-4)))*4); size_t nleft = nsize; while(nleft > 0) { uchar dgram[DGRAM_SIZE]; dgram[0] = 1; dgram[1] = 2; dgram[3] = 3; dgram[4] = 4; dgram[5] = 5; ssize_t ret; vvSocket::ErrorType err = _socket->read_data(dgram, DGRAM_SIZE, &ret); if(vvSocket::VV_OK != err) { vvDebugMsg::msg(1, "vvMulticast::read() error", true); return -1; } else { union bytesToInt32 { uchar x[4]; uint32_t y; }; bytesToInt32 t; t.x[0] = dgram[ret-4]; t.x[1] = dgram[ret-3]; t.x[2] = dgram[ret-2]; t.x[3] = dgram[ret-1]; uint32_t c = ntohl(t.y); size_t pos = c*(DGRAM_SIZE-4); for(unsigned int i=0;i<ret-4;i++) { data[pos+i] = dgram[i]; } nleft -= ret; } } return size; } } uchar* vvMulticast::numberConsecutively(const uchar* data, const size_t size) { if(VV_NORM == _api) { vvDebugMsg::msg(1, "vvMulticast::numberConsecutively() is not available (nor necessary) for NormAPI"); (void) data; (void) size; return NULL; } else { uchar *numbered = new uchar[size_t(size+(ceil(float(size)/float((DGRAM_SIZE-4)))*4))]; size_t i = 0; size_t n = 0; uint32_t c = 0; while(i < size) { numbered[n++] = data[i++]; if((n+4)%DGRAM_SIZE == 0) { *((uint32_t*)(&numbered[n])) = htonl(c); n += 4; c++; } } // add last number if dgram not full if(n % DGRAM_SIZE != 0) { *((uint32_t*)(&numbered[n])) = htonl(c); } return numbered; } } // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0 <commit_msg>remove unreachable code<commit_after>// Virvo - Virtual Reality Volume Rendering // Copyright (C) 1999-2003 University of Stuttgart, 2004-2005 Brown University // Contact: Jurgen P. Schulze, [email protected] // // This file is part of Virvo. // // Virvo 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 (see license.txt); if not, write to the // Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA #ifdef HAVE_CONFIG_H #include "vvconfig.h" #endif #include "vvdebugmsg.h" #include "vvinttypes.h" #include "vvmulticast.h" #include "vvsocketmonitor.h" #include "vvinttypes.h" #include <algorithm> #include <cmath> #ifdef HAVE_NORM #include <normApi.h> #include <stdlib.h> #endif vvMulticast::vvMulticast(const char* addr, const ushort port, const MulticastType type, const MulticastApi api) : _type(type), _api(api) { if(VV_NORM == _api) { #ifdef HAVE_NORM _instance = NormCreateInstance(); _session = NormCreateSession(_instance, addr, port, NORM_NODE_ANY); NormSetCongestionControl(_session, true); if(VV_SENDER == type) { NormSessionId sessionId = (NormSessionId)rand(); // TODO: Adjust these numbers depending on the used network topology NormSetTransmitRate(_session, 8e10); NormSetTransmitCacheBounds(_session, CHUNK_SIZE, 1, 128); //NormSetGroupSize(_session, 10); NormStartSender(_session, sessionId, 1024*1024, 1400, 64, 2); NormSetTxSocketBuffer(_session, 1024*1024*32); } else if(VV_RECEIVER == type) { NormStartReceiver(_session, 1024*1024); NormSetRxSocketBuffer(_session, 1024*1024*64); NormDescriptor normDesc = NormGetDescriptor(_instance); _nodes.push_back(NormGetLocalNodeId(_session)); _normSocket = new vvSocket(vvSocket::VV_UDP, int(normDesc)); } #else (void)addr; (void)port; #endif } else if(VV_VVSOCKET == _api) { if(VV_SENDER == _type) { _socket = new vvSocket(port, addr, vvSocket::VV_MC_SENDER); } else if(VV_RECEIVER == _type) { _socket = new vvSocket(port, addr, vvSocket::VV_MC_RECEIVER); } _socket->init(); } } vvMulticast::~vvMulticast() { if(VV_NORM == _api) { #ifdef HAVE_NORM if(VV_SENDER == _type) { NormStopSender(_session); } else if(VV_RECEIVER == _type) { NormStopReceiver(_session); delete _normSocket; } NormDestroySession(_session); NormDestroyInstance(_instance); #endif } else if(VV_VVSOCKET == _api) { delete _socket; } } ssize_t vvMulticast::write(const uchar* bytes, const size_t size, double timeout) { vvDebugMsg::msg(3, "vvMulticast::write()"); if(VV_NORM == _api) { #ifdef HAVE_NORM for(std::vector<NormNodeId>::const_iterator it = _nodes.begin(); it != _nodes.end(); ++it) { NormAddAckingNode(_session, *it); } for(unsigned int i=0; i<size; i+=CHUNK_SIZE) { size_t frameSize = std::min(size_t(CHUNK_SIZE), size); _object = NormDataEnqueue(_session, (char*)&bytes[i*CHUNK_SIZE], frameSize); NormSetWatermark(_session, _object); if(NORM_OBJECT_INVALID ==_object) { vvDebugMsg::msg(2, "vvMulticast::write(): Norm Object is invalid!"); return -2; } NormDescriptor normDesc = NormGetDescriptor(_instance); vvSocketMonitor* monitor = new vvSocketMonitor; std::vector<vvSocket*> sock; sock.push_back(new vvSocket(vvSocket::VV_UDP, int(normDesc))); monitor->setReadFds(sock); NormEvent theEvent; size_t bytesSent = 0; bool keepGoing = true; while(keepGoing) { vvSocket* ready = NULL; vvSocketMonitor::ErrorType err = monitor->wait(&ready, &timeout); if(vvSocketMonitor::VV_TIMEOUT == err) { vvDebugMsg::msg(2, "vvMulticast::write() timeout reached."); return bytesSent; } else if(vvSocketMonitor::VV_ERROR == err) { vvDebugMsg::msg(2, "vvMulticast::write() error."); return -1; } else { NormGetNextEvent(_instance, &theEvent); switch(theEvent.type) { case NORM_CC_ACTIVE: vvDebugMsg::msg(3, "vvMulticast::write() NORM_CC_ACTIVE: transmission still active"); break; case NORM_TX_FLUSH_COMPLETED: case NORM_LOCAL_SENDER_CLOSED: case NORM_TX_OBJECT_SENT: vvDebugMsg::msg(3, "vvMulticast::write(): chunk-transfer completed."); bytesSent += size_t(NormObjectGetSize(theEvent.object)); keepGoing = false; break; default: { std::string eventmsg = std::string("vvMulticast::write() Norm-Event: "); eventmsg += theEvent.type; vvDebugMsg::msg(3, eventmsg.c_str()); break; } } } } } return size; #else (void)bytes; (void)size; (void)timeout; return -1; #endif } else { // number datagrams uchar *ndata = numberConsecutively(bytes, size); size_t nsize = size+(ceil(float(size)/float((DGRAM_SIZE-4)))*4); size_t nleft = nsize; while(nleft > 0) { size_t towrite = std::min(size_t(DGRAM_SIZE), nleft); vvSocket::ErrorType err = _socket->write_data((uchar*)&ndata[nsize-nleft], towrite); if(vvSocket::VV_OK != err) { vvDebugMsg::msg(1, "vvMulticast::write() error", true); return -1; } else { nleft -= towrite; } } return size; } } ssize_t vvMulticast::read(uchar* data, const size_t size, double timeout) { vvDebugMsg::msg(3, "vvMulticast::read()"); if(VV_NORM == _api) { #ifdef HAVE_NORM vvSocketMonitor monitor; std::vector<vvSocket*> sock; sock.push_back(_normSocket); monitor.setReadFds(sock); NormEvent theEvent; size_t chunk = 0; size_t bytesReceived = 0; bool keepGoing = true; do { vvSocket* ready = NULL; vvSocketMonitor::ErrorType err = monitor.wait(&ready, &timeout); if(vvSocketMonitor::VV_TIMEOUT == err) { vvDebugMsg::msg(2, "vvMulticast::read() timeout reached."); return bytesReceived; } else if(vvSocketMonitor::VV_ERROR == err) { vvDebugMsg::msg(2, "vvMulticast::read() error."); return -1; } else { NormGetNextEvent(_instance, &theEvent); switch(theEvent.type) { case NORM_RX_OBJECT_UPDATED: vvDebugMsg::msg(3, "vvMulticast::read() NORM_RX_OBJECT_UPDATED: the identified receive object has newly received data content."); break; case NORM_RX_OBJECT_COMPLETED: { vvDebugMsg::msg(3, "vvMulticast::read() NORM_RX_OBJECT_COMPLETED: transfer completed."); bytesReceived += size_t(NormObjectGetSize(theEvent.object)); // copy data into array uchar *t_data = (uchar*)NormDataDetachData(theEvent.object); for(int i=0;i<NormObjectGetSize(theEvent.object);i++) { data[i+chunk*CHUNK_SIZE] = t_data[i]; } chunk++; break; } case NORM_RX_OBJECT_ABORTED: vvDebugMsg::msg(2, "vvMulticast::read() NORM_RX_OBJECT_ABORTED: transfer incomplete!"); return -1; break; default: { std::string eventmsg = std::string("vvMulticast::read() Norm-Event: "); eventmsg += theEvent.type; vvDebugMsg::msg(3, eventmsg.c_str()); break; } } } if(bytesReceived >= size) keepGoing = false; } while((0.0 < timeout || -1.0 == timeout) && keepGoing); return bytesReceived; #else (void)size; (void)data; (void)timeout; return -1; #endif } else { size_t nsize = size+(ceil(float(size)/float((DGRAM_SIZE-4)))*4); size_t nleft = nsize; while(nleft > 0) { uchar dgram[DGRAM_SIZE]; dgram[0] = 1; dgram[1] = 2; dgram[3] = 3; dgram[4] = 4; dgram[5] = 5; ssize_t ret; vvSocket::ErrorType err = _socket->read_data(dgram, DGRAM_SIZE, &ret); if(vvSocket::VV_OK != err) { vvDebugMsg::msg(1, "vvMulticast::read() error", true); return -1; } else { union bytesToInt32 { uchar x[4]; uint32_t y; }; bytesToInt32 t; t.x[0] = dgram[ret-4]; t.x[1] = dgram[ret-3]; t.x[2] = dgram[ret-2]; t.x[3] = dgram[ret-1]; uint32_t c = ntohl(t.y); size_t pos = c*(DGRAM_SIZE-4); for(unsigned int i=0;i<ret-4;i++) { data[pos+i] = dgram[i]; } nleft -= ret; } } return size; } } uchar* vvMulticast::numberConsecutively(const uchar* data, const size_t size) { uchar *numbered = new uchar[size_t(size+(ceil(float(size)/float((DGRAM_SIZE-4)))*4))]; size_t i = 0; size_t n = 0; uint32_t c = 0; while(i < size) { numbered[n++] = data[i++]; if((n+4)%DGRAM_SIZE == 0) { *((uint32_t*)(&numbered[n])) = htonl(c); n += 4; c++; } } // add last number if dgram not full if(n % DGRAM_SIZE != 0) { *((uint32_t*)(&numbered[n])) = htonl(c); } return numbered; } // vim: sw=2:expandtab:softtabstop=2:ts=2:cino=\:0g0t0 <|endoftext|>
<commit_before>// Copyright (c) 2016 Tchernopyatov Alexey. Contacts: [email protected] // Under MIT license, view LICENSE.txt #include "createexercisedialog.h" #include <QWidget> #include <QLabel> #include <QBoxLayout> #include <QSpinBox> #include <QPushButton> #include <QFileDialog> #include <QApplication> #include <QPixmap> #include <QDialog> #include <QDebug> #include <QLineEdit> #include "exercisewidget.h" #include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> #include <QVariantMap> CreateExerciseDialog::CreateExerciseDialog(QWidget *parent) : QDialog(parent) { QVBoxLayout* mainLout = new QVBoxLayout(this); createBaseSettings(mainLout); createExerciseField(mainLout); createConfirmButton(mainLout); mainLout->addStretch(1); } CreateExerciseDialog::~CreateExerciseDialog() { } /** * set language for dialog * @param lang - words for set * @author Чернопятов А.В. * @date 2015.02.07 */ void CreateExerciseDialog::setLanguage(const LanguageStruct &lang) { currentLanguage = lang; nameLbl->setText(currentLanguage.words["CREATE_EXERCISE_DLG_CYCLE_NAME"]); setCountSpinBox->setPrefix(currentLanguage.words["CREATE_EXERCISE_DLG_SET_COUNT"]); addExerciseBtn->setText(currentLanguage.words["CREATE_EXERCISE_DLG_ADD_EXERCISE"]); this->btnOk->setText(currentLanguage.words["BTN_OK"]); this->btnCancel->setText(currentLanguage.words["BTN_CANCEL"]); for(int i = 0; i < exersiseVector.size(); i++) { exersiseVector[i]->setLanguage(lang); } } void CreateExerciseDialog::createBaseSettings(QBoxLayout*lout) { { QHBoxLayout* hlout = new QHBoxLayout(); nameLbl = new QLabel(this); nameLbl->setText(currentLanguage.words["CREATE_EXERCISE_DLG_CYCLE_NAME"]); hlout->addWidget(nameLbl); nameEdit = new QLineEdit(this); hlout->addWidget(nameEdit); lout->addLayout(hlout); } { QHBoxLayout* hlout = new QHBoxLayout(); setCountSpinBox = new QSpinBox(this); setCountSpinBox->setPrefix(currentLanguage.words["CREATE_EXERCISE_DLG_SET_COUNT"]); setCountSpinBox->setMinimum(1); setCountSpinBox->setMaximum(32); hlout->addWidget(setCountSpinBox); addExerciseBtn = new QPushButton(this); addExerciseBtn->setText(currentLanguage.words["CREATE_EXERCISE_DLG_ADD_EXERCISE"]); connect(addExerciseBtn,SIGNAL(clicked()),this,SLOT(pushButtonClicked())); hlout->addWidget(addExerciseBtn); lout->addLayout(hlout); } } void CreateExerciseDialog::createExerciseField(QBoxLayout *lout) { exerciseLout = new QGridLayout(); lout->addLayout(exerciseLout); } ExerciseWidget* CreateExerciseDialog::createExersise() { QString title = currentLanguage.words["CREATE_EXERCISE_DLG_EXERCISE"]+ QString::number(exersiseVector.size()+1); ExerciseWidget* wdg = new ExerciseWidget(this); connect(wdg,SIGNAL(removeMe()),this,SLOT(removeExercise())); wdg->setBoxTitle(title); exersiseVector.push_back(wdg); return wdg; } void CreateExerciseDialog::pushButtonClicked() { QPushButton* btn = (qobject_cast<QPushButton*>(sender())); if(btn == addExerciseBtn) { this->createExersise(); updateGrid(); } } void CreateExerciseDialog::createConfirmButton(QBoxLayout *lout) { btnOk = new QPushButton(currentLanguage.words["BTN_OK"],this); btnCancel = new QPushButton(currentLanguage.words["BTN_CANCEL"],this); QHBoxLayout *hlout = new QHBoxLayout(); hlout->addWidget(btnOk); hlout->addWidget(btnCancel); connect(btnOk,SIGNAL(clicked()),SLOT(accept())); connect(btnCancel,SIGNAL(clicked()),SLOT(reject())); lout->addLayout(hlout); } void CreateExerciseDialog::removeExercise() { ExerciseWidget* wdg = (qobject_cast<ExerciseWidget*>(sender())); disconnect(wdg,SIGNAL(removeMe()),this,SLOT(removeExercise())); exerciseLout->removeWidget(wdg); exersiseVector.removeOne(wdg); wdg->deleteLater(); updateGrid(); } void CreateExerciseDialog::updateGrid() { for(int i = 0; i < exersiseVector.size(); i++) { QString title = currentLanguage.words["CREATE_EXERCISE_DLG_EXERCISE"] + QString::number(i+1); exersiseVector[i]->setBoxTitle(title); exerciseLout->removeWidget(exersiseVector[i]); int maxR = 3; int maxC = 3; int sz = i; int row = sz/maxR; int col = sz - row*maxC; exerciseLout->addWidget(exersiseVector[i],row,col); } } QByteArray CreateExerciseDialog::getExerciseData() { QJsonDocument doc; QVariantMap map; map.insert("name", nameEdit->text()); map.insert("set_count",setCountSpinBox->value()); QVariantMap step; QVariantList lst; ExerciseStruct es; for(int i = 0; i< exersiseVector.size(); i++) { es= exersiseVector.at(i)->getData(); step["name"] = es.name; step["time"] = es.time; lst.push_back(step); } map.insert("exercises",lst); QJsonObject json = QJsonObject::fromVariantMap(map); //obj["name"]=nameEdit->text(); doc.setObject(json); qDebug() << " " << doc.toJson(); return doc.toJson(); } void CreateExerciseDialog::loadExerciseData(const QByteArray &data) { qDebug() << " data = " << data; QJsonDocument doc; doc = QJsonDocument::fromJson(data); qDebug() << "readed " << doc.toJson(); SetStruct ss(doc); this->loadExerciseData(ss); updateGrid(); } void CreateExerciseDialog::loadExerciseData(const SetStruct &data) { nameEdit->setText(data.name); setCountSpinBox->setValue(data.count); for(int i = 0; i < data.exercise.size(); i++) { qDebug() << "[" << i << "]" << data.exercise[i].name << " time = " << data.exercise[i].time; ExerciseWidget* wdg = this->createExersise(); ExerciseStruct es; es.name = data.exercise[i].name; es.time = data.exercise[i].time; wdg->setData(es); } } <commit_msg>Update createexercisedialog.cpp<commit_after>// Copyright (c) 2016 Tchernopyatov Alexey. Contacts: [email protected] // Under MIT license, view LICENSE.txt #include "createexercisedialog.h" #include <QWidget> #include <QLabel> #include <QBoxLayout> #include <QSpinBox> #include <QPushButton> #include <QFileDialog> #include <QApplication> #include <QPixmap> #include <QDialog> #include <QDebug> #include <QLineEdit> #include "exercisewidget.h" #include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> #include <QVariantMap> CreateExerciseDialog::CreateExerciseDialog(QWidget *parent) : QDialog(parent) { QVBoxLayout* mainLout = new QVBoxLayout(this); createBaseSettings(mainLout); createExerciseField(mainLout); createConfirmButton(mainLout); mainLout->addStretch(1); } CreateExerciseDialog::~CreateExerciseDialog() { } /** * set language for dialog * @param lang - words for set * @author Чернопятов А.В. * @date 2015.02.07 */ void CreateExerciseDialog::setLanguage(const LanguageStruct &lang) { currentLanguage = lang; nameLbl->setText(currentLanguage.words["CREATE_EXERCISE_DLG_CYCLE_NAME"]); setCountSpinBox->setPrefix(currentLanguage.words["CREATE_EXERCISE_DLG_SET_COUNT"]); addExerciseBtn->setText(currentLanguage.words["CREATE_EXERCISE_DLG_ADD_EXERCISE"]); this->btnOk->setText(currentLanguage.words["BTN_OK"]); this->btnCancel->setText(currentLanguage.words["BTN_CANCEL"]); for(int i = 0; i < exersiseVector.size(); i++) { exersiseVector[i]->setLanguage(lang); } } void CreateExerciseDialog::createBaseSettings(QBoxLayout*lout) { { QHBoxLayout* hlout = new QHBoxLayout(); nameLbl = new QLabel(this); nameLbl->setText(currentLanguage.words["CREATE_EXERCISE_DLG_CYCLE_NAME"]); hlout->addWidget(nameLbl); nameEdit = new QLineEdit(this); hlout->addWidget(nameEdit); lout->addLayout(hlout); } { QHBoxLayout* hlout = new QHBoxLayout(); setCountSpinBox = new QSpinBox(this); setCountSpinBox->setPrefix(currentLanguage.words["CREATE_EXERCISE_DLG_SET_COUNT"]); setCountSpinBox->setMinimum(1); setCountSpinBox->setMaximum(32); hlout->addWidget(setCountSpinBox); addExerciseBtn = new QPushButton(this); addExerciseBtn->setText(currentLanguage.words["CREATE_EXERCISE_DLG_ADD_EXERCISE"]); connect(addExerciseBtn,SIGNAL(clicked()),this,SLOT(pushButtonClicked())); hlout->addWidget(addExerciseBtn); lout->addLayout(hlout); } } void CreateExerciseDialog::createExerciseField(QBoxLayout *lout) { exerciseLout = new QGridLayout(); lout->addLayout(exerciseLout); } ExerciseWidget* CreateExerciseDialog::createExersise() { QString title = currentLanguage.words["CREATE_EXERCISE_DLG_EXERCISE"]+ QString::number(exersiseVector.size()+1); ExerciseWidget* wdg = new ExerciseWidget(this); connect(wdg,SIGNAL(removeMe()),this,SLOT(removeExercise())); wdg->setBoxTitle(title); exersiseVector.push_back(wdg); return wdg; } void CreateExerciseDialog::pushButtonClicked() { QPushButton* btn = (qobject_cast<QPushButton*>(sender())); if(btn == addExerciseBtn) { this->createExersise(); updateGrid(); } } void CreateExerciseDialog::createConfirmButton(QBoxLayout *lout) { btnOk = new QPushButton(currentLanguage.words["BTN_OK"],this); btnCancel = new QPushButton(currentLanguage.words["BTN_CANCEL"],this); QHBoxLayout *hlout = new QHBoxLayout(); hlout->addWidget(btnOk); hlout->addWidget(btnCancel); connect(btnOk,SIGNAL(clicked()),SLOT(accept())); connect(btnCancel,SIGNAL(clicked()),SLOT(reject())); lout->addLayout(hlout); } void CreateExerciseDialog::removeExercise() { ExerciseWidget* wdg = (qobject_cast<ExerciseWidget*>(sender())); disconnect(wdg,SIGNAL(removeMe()),this,SLOT(removeExercise())); exerciseLout->removeWidget(wdg); exersiseVector.removeOne(wdg); wdg->deleteLater(); updateGrid(); } void CreateExerciseDialog::updateGrid() { for(int i = 0; i < exersiseVector.size(); i++) { QString title = currentLanguage.words["CREATE_EXERCISE_DLG_EXERCISE"] + QString::number(i+1); exersiseVector[i]->setBoxTitle(title); exerciseLout->removeWidget(exersiseVector[i]); int maxR = 3; int maxC = 3; int sz = i; int row = sz/maxR; int col = sz - row*maxC; exerciseLout->addWidget(exersiseVector[i],row,col); } } QByteArray CreateExerciseDialog::getExerciseData() { QJsonDocument doc; QVariantMap map; map.insert("name", nameEdit->text()); map.insert("set_count",setCountSpinBox->value()); QVariantMap step; QVariantList lst; ExerciseStruct es; for(int i = 0; i< exersiseVector.size(); i++) { es= exersiseVector.at(i)->getData(); step["name"] = es.name; step["time"] = es.time; lst.push_back(step); } map.insert("exercises",lst); QJsonObject json = QJsonObject::fromVariantMap(map); //obj["name"]=nameEdit->text(); doc.setObject(json); qDebug() << " " << doc.toJson(); return doc.toJson(); } void CreateExerciseDialog::loadExerciseData(const QByteArray &data) { qDebug() << " data = " << data; QJsonDocument doc; doc = QJsonDocument::fromJson(data); qDebug() << "readed " << doc.toJson(); SetStruct ss(doc); this->loadExerciseData(ss); updateGrid(); } void CreateExerciseDialog::loadExerciseData(const SetStruct &data) { nameEdit->setText(data.name); setCountSpinBox->setValue(data.count); for(int i = 0; i < data.exercise.size(); i++) { qDebug() << "[" << i << "]" << data.exercise[i].name << " time = " << data.exercise[i].time; ExerciseWidget* wdg = this->createExersise(); wdg->setLanguage(currentLanguage); ExerciseStruct es; es.name = data.exercise[i].name; es.time = data.exercise[i].time; wdg->setData(es); } } <|endoftext|>
<commit_before>#include "tidyup_state_creators/stateCreatorFromPlanningScene.h" #include "tidyup_utils/stringutil.h" #include <pluginlib/class_list_macros.h> #include <ros/ros.h> #include <tf/tf.h> #include <moveit/move_group/capability_names.h> #include <moveit_msgs/GetPlanningScene.h> #include <moveit_msgs/PlanningScene.h> PLUGINLIB_EXPORT_CLASS(tidyup_state_creators::StateCreatorFromPlanningScene, continual_planning_executive::StateCreator) namespace tidyup_state_creators { StateCreatorFromPlanningScene::StateCreatorFromPlanningScene() { ros::NodeHandle nh; srvPlanningScene_ = nh.serviceClient<moveit_msgs::GetPlanningScene>(move_group::GET_PLANNING_SCENE_SERVICE_NAME); } StateCreatorFromPlanningScene::~StateCreatorFromPlanningScene() { } void StateCreatorFromPlanningScene::initialize(const std::deque<std::string>& arguments) { } bool StateCreatorFromPlanningScene::fillState(SymbolicState& state) { initializePlanningScene(); // Tables have been added to symbolic state in goalCreatorLoadTablesIntoPlanningScene initializeTables(state); ROS_DEBUG_STREAM("StateCreatorFromPlanningScene::" << __func__ << ": number of collision objects in planning scene: " << planningScene_.world.collision_objects.size()); forEach(const moveit_msgs::CollisionObject& object, planningScene_.world.collision_objects) { ROS_DEBUG_STREAM("StateCreatorFromPlanningScene::" << __func__ << ": processing object: " << object.id); if (StringUtil::startsWith(object.id, "table")) { // tables are already in symbolic state - load in goalCreatorLoadTablesIntoPlanningScene continue; } if (StringUtil::startsWith(object.id, "door")) { continue; } if (StringUtil::startsWith(object.id, "sponge")) { continue; } addObjectToSymbolicState(state, object, "movable_object"); findMatchingTable(state, planningScene_.world.collision_objects, object); } // attached objects forEach(const moveit_msgs::AttachedCollisionObject& attachedObject, planningScene_.robot_state.attached_collision_objects) { const moveit_msgs::CollisionObject& object = attachedObject.object; addObjectToSymbolicState(state, object, "movable_object"); // grasped predicate vector<string> params; params.push_back(object.id); params.push_back("arm_name"); if (StringUtil::startsWith(attachedObject.link_name, "l_")) { ROS_DEBUG_STREAM("processing attached object " << object.id << " on left_arm."); params[1] = "left_arm"; state.setBooleanPredicate("object-grasped", params, true); } else if (StringUtil::startsWith(attachedObject.link_name, "r_")) { ROS_DEBUG_STREAM("processing attached object " << object.id << " on right_arm."); params[1] = "right_arm"; state.setBooleanPredicate("object-grasped", params, true); } else { ROS_ERROR_STREAM("processing attached object " << object.id << " on unknown link."); } } return true; } void StateCreatorFromPlanningScene::initializePlanningScene() { ROS_INFO("StateCreatorFromPlanningScene::%s: Waiting for %s service.", __func__, move_group::GET_PLANNING_SCENE_SERVICE_NAME.c_str()); srvPlanningScene_.waitForExistence(); moveit_msgs::GetPlanningScene::Request request; moveit_msgs::GetPlanningScene::Response response; //request.components.WORLD_OBJECT_NAMES; IMPORTANT: This declaration does not work! request.components.components = moveit_msgs::PlanningSceneComponents::WORLD_OBJECT_GEOMETRY | moveit_msgs::PlanningSceneComponents::ROBOT_STATE_ATTACHED_OBJECTS; if (!srvPlanningScene_.call(request, response)) { ROS_ERROR("StateCreatorFromPlanningScene::%s: Failed to get initial planning scene.", __func__); } ROS_DEBUG("StateCreatorFromPlanningScene::%s: Number of collision objects: %lu", __func__, response.scene.world.collision_objects.size()); setPlanningScene(response.scene); } void StateCreatorFromPlanningScene::setPlanningScene(const moveit_msgs::PlanningScene& scene) { planningScene_ = scene; } void StateCreatorFromPlanningScene::initializeTables(const SymbolicState& currentState) { ROS_DEBUG_STREAM("processing tables"); pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> tablesRange = currentState.getTypedObjects().equal_range("table"); for (SymbolicState::TypedObjectConstIterator tablesIterator = tablesRange.first; tablesIterator != tablesRange.second; tablesIterator++) { ROS_DEBUG_STREAM("processing "<<tablesIterator->second); tables_.insert(tablesIterator->second); // pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> locationsRange = // currentState.getTypedObjects().equal_range("manipulation_location"); // for (SymbolicState::TypedObjectConstIterator locationsIterator = locationsRange.first; // locationsIterator != locationsRange.second; locationsIterator++) // { // // (location-near-table ?l - manipulation-location ?t - table) // Predicate pAt; // pAt.name = "location-near-table"; // pAt.parameters.push_back(locationsIterator->second); // pAt.parameters.push_back(tablesIterator->second); // bool value = false; // currentState.hasBooleanPredicate(pAt, &value); // if (value) // { // ROS_DEBUG_STREAM("adding location "<<locationsIterator->second<<" to "<<tablesIterator->second); // tableLocations_.insert(make_pair(tablesIterator->second, locationsIterator->second)); // } // } } } bool StateCreatorFromPlanningScene::extractPoseStampedFromCollisionObject(const moveit_msgs::CollisionObject& co, geometry_msgs::PoseStamped& pose) const { if (co.mesh_poses.empty() && co.primitive_poses.empty()) { ROS_WARN("stateCreatorFromPlanningScene::%s: CollisionObject %s had no mesh_poses nor primitive_poses", __func__, co.id.c_str()); return false; } std::vector<geometry_msgs::Pose> poses; if(!co.mesh_poses.empty() && !co.primitive_poses.empty()) { ROS_WARN("%s: CollisionObject %s had mesh_poses and primitive_poses -> using primitive_poses", __func__, co.id.c_str()); poses = co.primitive_poses; } else if(!co.primitive_poses.empty()) { poses = co.primitive_poses; } else { ROS_ASSERT(!co.mesh_poses.empty()); poses = co.mesh_poses; } if(poses.size() > 1) { ROS_WARN("%s: CollisionObject %s had %zu poses -> using first.", __func__, co.id.c_str(), poses.size()); } pose.pose = poses.front(); pose.header = co.header; return true; } void StateCreatorFromPlanningScene::addObjectToSymbolicState(SymbolicState& state, const moveit_msgs::CollisionObject& co, const std::string& objectType) { // Verify that objectType is spelled correctly if (!doesObjectTypeExist(objectType)) return; state.addObject(co.id, objectType); state.setNumericalFluent("timestamp", co.id, co.header.stamp.toSec()); state.addObject(co.header.frame_id, "frameid"); ROS_DEBUG_STREAM("StateCreatorFromPlanningScene::" << __func__ << " object: " << co.id << " has frame: " << co.header.frame_id); state.setObjectFluent("frame-id", co.id, co.header.frame_id); geometry_msgs::PoseStamped poseStamped; if (!extractPoseStampedFromCollisionObject(co, poseStamped)) { ROS_ERROR("StateCreatorFromPlanningScene::%s: object:%s does not have a pose!", __func__, co.id.c_str()); return; } geometry_msgs::Pose pose = poseStamped.pose; state.setNumericalFluent("x", co.id, pose.position.x); state.setNumericalFluent("y", co.id, pose.position.y); state.setNumericalFluent("z", co.id, pose.position.z); state.setNumericalFluent("qx", co.id, pose.orientation.x); state.setNumericalFluent("qy", co.id, pose.orientation.y); state.setNumericalFluent("qz", co.id, pose.orientation.z); state.setNumericalFluent("qw", co.id, pose.orientation.w); } bool StateCreatorFromPlanningScene::doesObjectTypeExist(const string& objectType) { std::string types[] = { "pose", "frameid", "location", "manipulation_location", "table", "movable_object", "arm", "arm_state" }; std::set<std::string> objectTypes(types, types + sizeof(types) / sizeof(types[0])); ROS_ASSERT(objectTypes.size() == 8); if (objectTypes.find(objectType) != objectTypes.end()) { return true; } else { ROS_ERROR("StateCreatorFromPlanningScene::%s: Object Type %s does not exist " "- maybe typo", __func__, objectType.c_str()); return false; } } void StateCreatorFromPlanningScene::findMatchingTable(SymbolicState& currentState, const std::vector<moveit_msgs::CollisionObject>& allCos, const moveit_msgs::CollisionObject& co) { string closest_table = "table"; double closest_distance = 2.0; forEach(const moveit_msgs::CollisionObject& table, allCos) { // if collisionObject table is really a table (was added in initializedTables()) if (tables_.find(table.id) != tables_.end()) { geometry_msgs::PoseStamped tablePoseStamped; if (!extractPoseStampedFromCollisionObject(table, tablePoseStamped)) { ROS_ERROR("StateCreatorFromPlanningScene::%s: table:%s does not have a pose!", __func__, table.id.c_str()); return; } const geometry_msgs::Point& origin = tablePoseStamped.pose.position; // get the point of co geometry_msgs::PoseStamped coPoseStamped; if (!extractPoseStampedFromCollisionObject(co, coPoseStamped)) { ROS_ERROR("StateCreatorFromPlanningScene::%s: object:%s does not have a pose!", __func__, co.id.c_str()); return; } const geometry_msgs::Point& coPoint = coPoseStamped.pose.position; // co is beneath table if (origin.z > coPoint.z) continue; // simplified: find table with smallest distance to object double distance = hypot(coPoint.x - origin.x, coPoint.y - origin.y); if (distance < closest_distance) { closest_distance = distance; closest_table = table.id; } } } if (closest_table != "table") // found a matching table { ROS_DEBUG_STREAM("putting " << co.id << " on " << closest_table); Predicate pOn; pOn.name = "object-on"; pOn.parameters.push_back(co.id); pOn.parameters.push_back(closest_table); currentState.setBooleanPredicate(pOn.name, pOn.parameters, true); } else ROS_WARN("StateCreatorFromPlanningScene::%s: NO matching Table found for object: %s", __func__, co.id.c_str()); } // std::pair<double, double> StateCreatorFromPlanningScene::distanceBetweenTwoPoses(const geometry_msgs::PoseStamped & posePS, // const geometry_msgs::PoseStamped & poseState) // { // // OR poses might be in a sensor frame -> transform to PS frame first // geometry_msgs::PoseStamped poseOR_transformed; // try { // tf_.waitForTransform(posePS.header.frame_id, poseState.header.frame_id, poseState.header.stamp, // ros::Duration(0.5)); // tf_.transformPose(posePS.header.frame_id, poseState, poseOR_transformed); // } catch (tf::TransformException &ex) { // ROS_ERROR("%s", ex.what()); // } // // ROS_DEBUG_STREAM("StateCreatorFromPlanningScene::" << __func__ << ": frame ObjPlanningScene: " // << posePS.header.frame_id << ": frame ObjSymbolicState: " // << poseState.header.frame_id); // tf::Pose tfPS; // tf::Pose tfState; // tf::poseMsgToTF(posePS.pose, tfPS); // tf::poseMsgToTF(poseState.pose, tfState); // tf::Pose delta = tfPS.inverseTimes(tfState); // return std::make_pair(hypot(delta.getOrigin().x(), delta.getOrigin().y()), // fabs(delta.getOrigin().z())); // usually we're interested in the 2d distance independently // } }; <commit_msg>removing all movable object from sym state<commit_after>#include "tidyup_state_creators/stateCreatorFromPlanningScene.h" #include "tidyup_utils/stringutil.h" #include <pluginlib/class_list_macros.h> #include <ros/ros.h> #include <tf/tf.h> #include <moveit/move_group/capability_names.h> #include <moveit_msgs/GetPlanningScene.h> #include <moveit_msgs/PlanningScene.h> PLUGINLIB_EXPORT_CLASS(tidyup_state_creators::StateCreatorFromPlanningScene, continual_planning_executive::StateCreator) namespace tidyup_state_creators { StateCreatorFromPlanningScene::StateCreatorFromPlanningScene() { ros::NodeHandle nh; srvPlanningScene_ = nh.serviceClient<moveit_msgs::GetPlanningScene>(move_group::GET_PLANNING_SCENE_SERVICE_NAME); } StateCreatorFromPlanningScene::~StateCreatorFromPlanningScene() { } void StateCreatorFromPlanningScene::initialize(const std::deque<std::string>& arguments) { } bool StateCreatorFromPlanningScene::fillState(SymbolicState& state) { initializePlanningScene(); // Tables have been added to symbolic state in goalCreatorLoadTablesIntoPlanningScene initializeTables(state); // delete all movable objects from symbolic state, and re-add the important objects later (from PS) const multimap<string, string> objects = state.getTypedObjects(); std::pair<multimap<string, string>::const_iterator, multimap<string, string>::const_iterator> iterators = objects.equal_range("movable_object"); for (multimap<string, string>::const_iterator it = iterators.first; it != iterators.second; it++) { // also predicates with the objects are removed state.removeObject(it->second); } ROS_DEBUG_STREAM("StateCreatorFromPlanningScene::" << __func__ << ": number of collision objects in planning scene: " << planningScene_.world.collision_objects.size()); forEach(const moveit_msgs::CollisionObject& object, planningScene_.world.collision_objects) { ROS_DEBUG_STREAM("StateCreatorFromPlanningScene::" << __func__ << ": processing object: " << object.id); if (StringUtil::startsWith(object.id, "table")) { // tables are already in symbolic state - load in goalCreatorLoadTablesIntoPlanningScene continue; } if (StringUtil::startsWith(object.id, "door")) { continue; } if (StringUtil::startsWith(object.id, "sponge")) { continue; } addObjectToSymbolicState(state, object, "movable_object"); // add object-on predicate to object findMatchingTable(state, planningScene_.world.collision_objects, object); } // attached objects forEach(const moveit_msgs::AttachedCollisionObject& attachedObject, planningScene_.robot_state.attached_collision_objects) { const moveit_msgs::CollisionObject& object = attachedObject.object; addObjectToSymbolicState(state, object, "movable_object"); // grasped predicate vector<string> params; params.push_back(object.id); params.push_back("arm_name"); if (StringUtil::startsWith(attachedObject.link_name, "l_")) { ROS_DEBUG_STREAM("processing attached object " << object.id << " on left_arm."); params[1] = "left_arm"; state.setBooleanPredicate("object-grasped", params, true); } else if (StringUtil::startsWith(attachedObject.link_name, "r_")) { ROS_DEBUG_STREAM("processing attached object " << object.id << " on right_arm."); params[1] = "right_arm"; state.setBooleanPredicate("object-grasped", params, true); } else { ROS_ERROR_STREAM("processing attached object " << object.id << " on unknown link."); } } return true; } void StateCreatorFromPlanningScene::initializePlanningScene() { ROS_INFO("StateCreatorFromPlanningScene::%s: Waiting for %s service.", __func__, move_group::GET_PLANNING_SCENE_SERVICE_NAME.c_str()); srvPlanningScene_.waitForExistence(); moveit_msgs::GetPlanningScene::Request request; moveit_msgs::GetPlanningScene::Response response; //request.components.WORLD_OBJECT_NAMES; IMPORTANT: This declaration does not work! request.components.components = moveit_msgs::PlanningSceneComponents::WORLD_OBJECT_GEOMETRY | moveit_msgs::PlanningSceneComponents::ROBOT_STATE_ATTACHED_OBJECTS; if (!srvPlanningScene_.call(request, response)) { ROS_ERROR("StateCreatorFromPlanningScene::%s: Failed to get initial planning scene.", __func__); } ROS_DEBUG("StateCreatorFromPlanningScene::%s: Number of collision objects: %lu", __func__, response.scene.world.collision_objects.size()); setPlanningScene(response.scene); } void StateCreatorFromPlanningScene::setPlanningScene(const moveit_msgs::PlanningScene& scene) { planningScene_ = scene; } void StateCreatorFromPlanningScene::initializeTables(const SymbolicState& currentState) { ROS_DEBUG_STREAM("processing tables"); pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> tablesRange = currentState.getTypedObjects().equal_range("table"); for (SymbolicState::TypedObjectConstIterator tablesIterator = tablesRange.first; tablesIterator != tablesRange.second; tablesIterator++) { ROS_DEBUG_STREAM("processing "<<tablesIterator->second); tables_.insert(tablesIterator->second); // pair<SymbolicState::TypedObjectConstIterator, SymbolicState::TypedObjectConstIterator> locationsRange = // currentState.getTypedObjects().equal_range("manipulation_location"); // for (SymbolicState::TypedObjectConstIterator locationsIterator = locationsRange.first; // locationsIterator != locationsRange.second; locationsIterator++) // { // // (location-near-table ?l - manipulation-location ?t - table) // Predicate pAt; // pAt.name = "location-near-table"; // pAt.parameters.push_back(locationsIterator->second); // pAt.parameters.push_back(tablesIterator->second); // bool value = false; // currentState.hasBooleanPredicate(pAt, &value); // if (value) // { // ROS_DEBUG_STREAM("adding location "<<locationsIterator->second<<" to "<<tablesIterator->second); // tableLocations_.insert(make_pair(tablesIterator->second, locationsIterator->second)); // } // } } } bool StateCreatorFromPlanningScene::extractPoseStampedFromCollisionObject(const moveit_msgs::CollisionObject& co, geometry_msgs::PoseStamped& pose) const { if (co.mesh_poses.empty() && co.primitive_poses.empty()) { ROS_WARN("stateCreatorFromPlanningScene::%s: CollisionObject %s had no mesh_poses nor primitive_poses", __func__, co.id.c_str()); return false; } std::vector<geometry_msgs::Pose> poses; if(!co.mesh_poses.empty() && !co.primitive_poses.empty()) { ROS_WARN("%s: CollisionObject %s had mesh_poses and primitive_poses -> using primitive_poses", __func__, co.id.c_str()); poses = co.primitive_poses; } else if(!co.primitive_poses.empty()) { poses = co.primitive_poses; } else { ROS_ASSERT(!co.mesh_poses.empty()); poses = co.mesh_poses; } if(poses.size() > 1) { ROS_WARN("%s: CollisionObject %s had %zu poses -> using first.", __func__, co.id.c_str(), poses.size()); } pose.pose = poses.front(); pose.header = co.header; return true; } void StateCreatorFromPlanningScene::addObjectToSymbolicState(SymbolicState& state, const moveit_msgs::CollisionObject& co, const std::string& objectType) { // Verify that objectType is spelled correctly if (!doesObjectTypeExist(objectType)) return; state.addObject(co.id, objectType); state.setNumericalFluent("timestamp", co.id, co.header.stamp.toSec()); state.addObject(co.header.frame_id, "frameid"); ROS_DEBUG_STREAM("StateCreatorFromPlanningScene::" << __func__ << " object: " << co.id << " has frame: " << co.header.frame_id); state.setObjectFluent("frame-id", co.id, co.header.frame_id); geometry_msgs::PoseStamped poseStamped; if (!extractPoseStampedFromCollisionObject(co, poseStamped)) { ROS_ERROR("StateCreatorFromPlanningScene::%s: object:%s does not have a pose!", __func__, co.id.c_str()); return; } geometry_msgs::Pose pose = poseStamped.pose; state.setNumericalFluent("x", co.id, pose.position.x); state.setNumericalFluent("y", co.id, pose.position.y); state.setNumericalFluent("z", co.id, pose.position.z); state.setNumericalFluent("qx", co.id, pose.orientation.x); state.setNumericalFluent("qy", co.id, pose.orientation.y); state.setNumericalFluent("qz", co.id, pose.orientation.z); state.setNumericalFluent("qw", co.id, pose.orientation.w); } bool StateCreatorFromPlanningScene::doesObjectTypeExist(const string& objectType) { std::string types[] = { "pose", "frameid", "location", "manipulation_location", "table", "movable_object", "arm", "arm_state" }; std::set<std::string> objectTypes(types, types + sizeof(types) / sizeof(types[0])); ROS_ASSERT(objectTypes.size() == 8); if (objectTypes.find(objectType) != objectTypes.end()) { return true; } else { ROS_ERROR("StateCreatorFromPlanningScene::%s: Object Type %s does not exist " "- maybe typo", __func__, objectType.c_str()); return false; } } void StateCreatorFromPlanningScene::findMatchingTable(SymbolicState& currentState, const std::vector<moveit_msgs::CollisionObject>& allCos, const moveit_msgs::CollisionObject& co) { string closest_table = "table"; double closest_distance = 2.0; forEach(const moveit_msgs::CollisionObject& table, allCos) { // if collisionObject table is really a table (was added in initializedTables()) if (tables_.find(table.id) != tables_.end()) { geometry_msgs::PoseStamped tablePoseStamped; if (!extractPoseStampedFromCollisionObject(table, tablePoseStamped)) { ROS_ERROR("StateCreatorFromPlanningScene::%s: table:%s does not have a pose!", __func__, table.id.c_str()); return; } const geometry_msgs::Point& origin = tablePoseStamped.pose.position; // get the point of co geometry_msgs::PoseStamped coPoseStamped; if (!extractPoseStampedFromCollisionObject(co, coPoseStamped)) { ROS_ERROR("StateCreatorFromPlanningScene::%s: object:%s does not have a pose!", __func__, co.id.c_str()); return; } const geometry_msgs::Point& coPoint = coPoseStamped.pose.position; // co is beneath table if (origin.z > coPoint.z) continue; // simplified: find table with smallest distance to object double distance = hypot(coPoint.x - origin.x, coPoint.y - origin.y); if (distance < closest_distance) { closest_distance = distance; closest_table = table.id; } } } if (closest_table != "table") // found a matching table { ROS_DEBUG_STREAM("putting " << co.id << " on " << closest_table); Predicate pOn; pOn.name = "object-on"; pOn.parameters.push_back(co.id); pOn.parameters.push_back(closest_table); currentState.setBooleanPredicate(pOn.name, pOn.parameters, true); } else ROS_WARN("StateCreatorFromPlanningScene::%s: NO matching Table found for object: %s", __func__, co.id.c_str()); } // std::pair<double, double> StateCreatorFromPlanningScene::distanceBetweenTwoPoses(const geometry_msgs::PoseStamped & posePS, // const geometry_msgs::PoseStamped & poseState) // { // // OR poses might be in a sensor frame -> transform to PS frame first // geometry_msgs::PoseStamped poseOR_transformed; // try { // tf_.waitForTransform(posePS.header.frame_id, poseState.header.frame_id, poseState.header.stamp, // ros::Duration(0.5)); // tf_.transformPose(posePS.header.frame_id, poseState, poseOR_transformed); // } catch (tf::TransformException &ex) { // ROS_ERROR("%s", ex.what()); // } // // ROS_DEBUG_STREAM("StateCreatorFromPlanningScene::" << __func__ << ": frame ObjPlanningScene: " // << posePS.header.frame_id << ": frame ObjSymbolicState: " // << poseState.header.frame_id); // tf::Pose tfPS; // tf::Pose tfState; // tf::poseMsgToTF(posePS.pose, tfPS); // tf::poseMsgToTF(poseState.pose, tfState); // tf::Pose delta = tfPS.inverseTimes(tfState); // return std::make_pair(hypot(delta.getOrigin().x(), delta.getOrigin().y()), // fabs(delta.getOrigin().z())); // usually we're interested in the 2d distance independently // } }; <|endoftext|>
<commit_before>#include "mlp_cv.hpp" /// PROJECT #include <csapex/msg/io.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex/param/parameter_factory.h> #include <csapex/model/node_modifier.h> #include <csapex/msg/generic_vector_message.hpp> #include <csapex/signal/slot.h> #include <QFile> CSAPEX_REGISTER_CLASS(csapex::MLPCv, csapex::Node) using namespace csapex; using namespace csapex::connection_types; MLPCv::MLPCv() : loaded_(false) { } void MLPCv::setup(NodeModifier &node_modifier) { input_ = node_modifier.addInput<GenericVectorMessage, FeaturesMessage>("Unclassified feature"); output_ = node_modifier.addOutput<GenericVectorMessage, FeaturesMessage>("Classified features"); reload_ = node_modifier.addSlot("Reload", std::bind(&MLPCv::reloadMLP, this)); } void MLPCv::setupParameters(Parameterizable &parameters) { parameters.addParameter(csapex::param::ParameterFactory::declareFileInputPath("file", "mlp.yaml"), [this](param::Parameter* p) { auto path = p->as<std::string>(); if(path != path_){ path_ = path; reloadMLP(); } }); } void MLPCv::loadMLP() { #if CV_MAJOR_VERSION == 2 mlp_.load(path_.c_str()); loaded_ = mlp_.get_layer_count() > 0; // oddly opencv does not check if file is valid #elif CV_MAJOR_VERSION == 3 mlp_ = cv::ml::ANN_MLP::load(path_); cv::Mat sizes = mlp_->getLayerSizes(); loaded_ = sizes.rows > 0 || sizes.cols > 0; #endif } void MLPCv::process() { std::shared_ptr<std::vector<FeaturesMessage> const> input = msg::getMessage<GenericVectorMessage, FeaturesMessage>(input_); std::shared_ptr<std::vector<FeaturesMessage>> output(new std::vector<FeaturesMessage>); if(!loaded_) { if(QFile(QString::fromStdString(path_)).exists()) { loadMLP(); } } if(loaded_) { std::size_t n = input->size(); output->resize(n); for(std::size_t i = 0; i < n; ++i) { classify(input->at(i),output->at(i)); } } else { *output = *input; node_modifier_->setWarning("cannot classfiy, no MLP loaded"); } msg::publish<GenericVectorMessage, FeaturesMessage>(output_, output); } void MLPCv::classify(const FeaturesMessage &input, FeaturesMessage &output) { output = input; cv::Mat feature(1, input.value.size(),cv::DataType<float>::type); for(std::size_t i = 0; i < input.value.size(); ++i){ feature.at<float>(0,i) = input.value[i]; } cv::Mat response; #if CV_MAJOR_VERSION == 2 mlp_.predict(feature, response); #elif CV_MAJOR_VERSION == 3 mlp_->predict(feature, response); #endif cv::Point max; cv::minMaxLoc(response, nullptr, nullptr, nullptr, &max); output.classification = max.x; } void MLPCv::reloadMLP() { loaded_ = false; } <commit_msg>mlp do not use qfile<commit_after>#include "mlp_cv.hpp" /// PROJECT #include <csapex/msg/io.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex/param/parameter_factory.h> #include <csapex/model/node_modifier.h> #include <csapex/msg/generic_vector_message.hpp> #include <csapex/signal/slot.h> CSAPEX_REGISTER_CLASS(csapex::MLPCv, csapex::Node) using namespace csapex; using namespace csapex::connection_types; MLPCv::MLPCv() : loaded_(false) { } void MLPCv::setup(NodeModifier &node_modifier) { input_ = node_modifier.addInput<GenericVectorMessage, FeaturesMessage>("Unclassified feature"); output_ = node_modifier.addOutput<GenericVectorMessage, FeaturesMessage>("Classified features"); reload_ = node_modifier.addSlot("Reload", std::bind(&MLPCv::reloadMLP, this)); } void MLPCv::setupParameters(Parameterizable &parameters) { parameters.addParameter(csapex::param::ParameterFactory::declareFileInputPath("file", "mlp.yaml"), [this](param::Parameter* p) { auto path = p->as<std::string>(); if(path != path_){ path_ = path; reloadMLP(); } }); } void MLPCv::loadMLP() { #if CV_MAJOR_VERSION == 2 mlp_.load(path_.c_str()); loaded_ = mlp_.get_layer_count() > 0; // oddly opencv does not check if file is valid #elif CV_MAJOR_VERSION == 3 mlp_ = cv::ml::ANN_MLP::load(path_); cv::Mat sizes = mlp_->getLayerSizes(); loaded_ = sizes.rows > 0 || sizes.cols > 0; #endif } void MLPCv::process() { std::shared_ptr<std::vector<FeaturesMessage> const> input = msg::getMessage<GenericVectorMessage, FeaturesMessage>(input_); std::shared_ptr<std::vector<FeaturesMessage>> output(new std::vector<FeaturesMessage>); if(!loaded_) { if(path_ != "") { loadMLP(); } } if(loaded_) { std::size_t n = input->size(); output->resize(n); for(std::size_t i = 0; i < n; ++i) { classify(input->at(i),output->at(i)); } } else { *output = *input; node_modifier_->setWarning("cannot classfiy, no MLP loaded"); } msg::publish<GenericVectorMessage, FeaturesMessage>(output_, output); } void MLPCv::classify(const FeaturesMessage &input, FeaturesMessage &output) { output = input; cv::Mat feature(1, input.value.size(),cv::DataType<float>::type); for(std::size_t i = 0; i < input.value.size(); ++i){ feature.at<float>(0,i) = input.value[i]; } cv::Mat response; #if CV_MAJOR_VERSION == 2 mlp_.predict(feature, response); #elif CV_MAJOR_VERSION == 3 mlp_->predict(feature, response); #endif cv::Point max; cv::minMaxLoc(response, nullptr, nullptr, nullptr, &max); output.classification = max.x; } void MLPCv::reloadMLP() { loaded_ = false; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <sstream> #include "rviz/display_context.h" #include "rviz/failed_view_controller.h" #include "rviz/properties/enum_property.h" #include "rviz/properties/property_tree_model.h" #include "rviz/render_panel.h" #include "rviz/view_controller.h" #include "rviz/view_manager.h" namespace rviz { ViewManager::ViewManager( DisplayContext* context ) : context_( context ) , root_property_( new ViewControllerContainer ) , property_model_( new PropertyTreeModel( root_property_ )) , factory_( new PluginlibFactory<ViewController>( "rviz", "rviz::ViewController" )) , current_( NULL ) , render_panel_( NULL ) { property_model_->setDragDropClass( "view-controller" ); connect( property_model_, SIGNAL( configChanged() ), this, SIGNAL( configChanged() )); } ViewManager::~ViewManager() { delete property_model_; delete factory_; } void ViewManager::initialize() { setCurrent( create( "rviz/Orbit" ), false ); } void ViewManager::update( float wall_dt, float ros_dt ) { if( getCurrent() ) { getCurrent()->update( wall_dt, ros_dt ); } } ViewController* ViewManager::create( const QString& class_id ) { QString error; ViewController* view = factory_->make( class_id, &error ); if( !view ) { view = new FailedViewController( class_id, error ); } view->initialize( context_ ); return view; } ViewController* ViewManager::getCurrent() const { return current_; } void ViewManager::setCurrentFrom( ViewController* source_view ) { if( source_view == NULL ) { return; } ViewController* previous = getCurrent(); if( source_view != previous ) { ViewController* new_current = copy( source_view ); setCurrent( new_current, false ); Q_EMIT configChanged(); } } void ViewManager::onCurrentDestroyed( QObject* obj ) { if( obj == current_ ) { current_ = NULL; } } void ViewManager::setCurrent( ViewController* new_current, bool mimic_view ) { ViewController* previous = getCurrent(); if( previous ) { if( mimic_view ) { new_current->mimic( previous ); } else { new_current->transitionFrom( previous ); } disconnect( previous, SIGNAL( destroyed( QObject* )), this, SLOT( onCurrentDestroyed( QObject* ))); } new_current->setName( "Current View" ); connect( new_current, SIGNAL( destroyed( QObject* )), this, SLOT( onCurrentDestroyed( QObject* ))); current_ = new_current; root_property_->addChildToFront( new_current ); delete previous; if( render_panel_ ) { // This setViewController() can indirectly call // ViewManager::update(), so make sure getCurrent() will return the // new one by this point. render_panel_->setViewController( new_current ); } Q_EMIT currentChanged(); } void ViewManager::setCurrentViewControllerType( const QString& new_class_id ) { setCurrent( create( new_class_id ), true ); } void ViewManager::copyCurrentToList() { ViewController* current = getCurrent(); if( current ) { ViewController* new_copy = copy( current ); new_copy->setName( factory_->getClassName( new_copy->getClassId() )); root_property_->addChild( new_copy ); } } ViewController* ViewManager::getViewAt( int index ) const { if( index < 0 ) { index = 0; } return qobject_cast<ViewController*>( root_property_->childAt( index + 1 )); } int ViewManager::getNumViews() const { int count = root_property_->numChildren(); if( count <= 0 ) { return 0; } else { return count-1; } } void ViewManager::add( ViewController* view, int index ) { if( index < 0 ) { index = root_property_->numChildren(); } else { index++; } property_model_->getRoot()->addChild( view, index ); } ViewController* ViewManager::take( ViewController* view ) { for( int i = 0; i < getNumViews(); i++ ) { if( getViewAt( i ) == view ) { return qobject_cast<ViewController*>( root_property_->takeChildAt( i + 1 )); } } return NULL; } ViewController* ViewManager::takeAt( int index ) { if( index < 0 ) { return NULL; } return qobject_cast<ViewController*>( root_property_->takeChildAt( index + 1 )); } void ViewManager::load( const Config& config ) { Config current_config = config.mapGetChild( "Current" ); QString class_id; if( current_config.mapGetString( "Class", &class_id )) { ViewController* new_current = create( class_id ); new_current->load( current_config ); setCurrent( new_current, false ); } Config saved_views_config = config.mapGetChild( "Saved" ); root_property_->removeChildren( 1 ); int num_saved = saved_views_config.listLength(); for( int i = 0; i < num_saved; i++ ) { Config view_config = saved_views_config.listChildAt( i ); if( view_config.mapGetString( "Class", &class_id )) { ViewController* view = create( class_id ); view->load( view_config ); add( view ); } } } void ViewManager::save( Config config ) const { getCurrent()->save( config.mapMakeChild( "Current" )); Config saved_views_config = config.mapMakeChild( "Saved" ); for( int i = 0; i < getNumViews(); i++ ) { getViewAt( i )->save( saved_views_config.listAppendNew() ); } } ViewController* ViewManager::copy( ViewController* source ) { Config config; source->save( config ); ViewController* copy_of_source = create( source->getClassId() ); copy_of_source->load( config ); return copy_of_source; } void ViewManager::setRenderPanel( RenderPanel* render_panel ) { render_panel_ = render_panel; } Qt::ItemFlags ViewControllerContainer::getViewFlags( int column ) const { return Property::getViewFlags( column ) | Qt::ItemIsDropEnabled; } void ViewControllerContainer::addChild( Property* child, int index ) { if( index == 0 ) { index = 1; } Property::addChild( child, index ); } void ViewControllerContainer::addChildToFront( Property* child ) { Property::addChild( child, 0 ); } } // end namespace rviz <commit_msg>Correctly save new current view controller<commit_after>/* * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <sstream> #include "rviz/display_context.h" #include "rviz/failed_view_controller.h" #include "rviz/properties/enum_property.h" #include "rviz/properties/property_tree_model.h" #include "rviz/render_panel.h" #include "rviz/view_controller.h" #include "rviz/view_manager.h" namespace rviz { ViewManager::ViewManager( DisplayContext* context ) : context_( context ) , root_property_( new ViewControllerContainer ) , property_model_( new PropertyTreeModel( root_property_ )) , factory_( new PluginlibFactory<ViewController>( "rviz", "rviz::ViewController" )) , current_( NULL ) , render_panel_( NULL ) { property_model_->setDragDropClass( "view-controller" ); connect( property_model_, SIGNAL( configChanged() ), this, SIGNAL( configChanged() )); connect( this, SIGNAL( currentChanged() ), this, SIGNAL( configChanged() )); } ViewManager::~ViewManager() { delete property_model_; delete factory_; } void ViewManager::initialize() { setCurrent( create( "rviz/Orbit" ), false ); } void ViewManager::update( float wall_dt, float ros_dt ) { if( getCurrent() ) { getCurrent()->update( wall_dt, ros_dt ); } } ViewController* ViewManager::create( const QString& class_id ) { QString error; ViewController* view = factory_->make( class_id, &error ); if( !view ) { view = new FailedViewController( class_id, error ); } view->initialize( context_ ); return view; } ViewController* ViewManager::getCurrent() const { return current_; } void ViewManager::setCurrentFrom( ViewController* source_view ) { if( source_view == NULL ) { return; } ViewController* previous = getCurrent(); if( source_view != previous ) { ViewController* new_current = copy( source_view ); setCurrent( new_current, false ); Q_EMIT configChanged(); } } void ViewManager::onCurrentDestroyed( QObject* obj ) { if( obj == current_ ) { current_ = NULL; } } void ViewManager::setCurrent( ViewController* new_current, bool mimic_view ) { ViewController* previous = getCurrent(); if( previous ) { if( mimic_view ) { new_current->mimic( previous ); } else { new_current->transitionFrom( previous ); } disconnect( previous, SIGNAL( destroyed( QObject* )), this, SLOT( onCurrentDestroyed( QObject* ))); } new_current->setName( "Current View" ); connect( new_current, SIGNAL( destroyed( QObject* )), this, SLOT( onCurrentDestroyed( QObject* ))); current_ = new_current; root_property_->addChildToFront( new_current ); delete previous; if( render_panel_ ) { // This setViewController() can indirectly call // ViewManager::update(), so make sure getCurrent() will return the // new one by this point. render_panel_->setViewController( new_current ); } if (current_ != previous) Q_EMIT currentChanged(); } void ViewManager::setCurrentViewControllerType( const QString& new_class_id ) { setCurrent( create( new_class_id ), true ); } void ViewManager::copyCurrentToList() { ViewController* current = getCurrent(); if( current ) { ViewController* new_copy = copy( current ); new_copy->setName( factory_->getClassName( new_copy->getClassId() )); root_property_->addChild( new_copy ); } } ViewController* ViewManager::getViewAt( int index ) const { if( index < 0 ) { index = 0; } return qobject_cast<ViewController*>( root_property_->childAt( index + 1 )); } int ViewManager::getNumViews() const { int count = root_property_->numChildren(); if( count <= 0 ) { return 0; } else { return count-1; } } void ViewManager::add( ViewController* view, int index ) { if( index < 0 ) { index = root_property_->numChildren(); } else { index++; } property_model_->getRoot()->addChild( view, index ); } ViewController* ViewManager::take( ViewController* view ) { for( int i = 0; i < getNumViews(); i++ ) { if( getViewAt( i ) == view ) { return qobject_cast<ViewController*>( root_property_->takeChildAt( i + 1 )); } } return NULL; } ViewController* ViewManager::takeAt( int index ) { if( index < 0 ) { return NULL; } return qobject_cast<ViewController*>( root_property_->takeChildAt( index + 1 )); } void ViewManager::load( const Config& config ) { Config current_config = config.mapGetChild( "Current" ); QString class_id; if( current_config.mapGetString( "Class", &class_id )) { ViewController* new_current = create( class_id ); new_current->load( current_config ); setCurrent( new_current, false ); } Config saved_views_config = config.mapGetChild( "Saved" ); root_property_->removeChildren( 1 ); int num_saved = saved_views_config.listLength(); for( int i = 0; i < num_saved; i++ ) { Config view_config = saved_views_config.listChildAt( i ); if( view_config.mapGetString( "Class", &class_id )) { ViewController* view = create( class_id ); view->load( view_config ); add( view ); } } } void ViewManager::save( Config config ) const { getCurrent()->save( config.mapMakeChild( "Current" )); Config saved_views_config = config.mapMakeChild( "Saved" ); for( int i = 0; i < getNumViews(); i++ ) { getViewAt( i )->save( saved_views_config.listAppendNew() ); } } ViewController* ViewManager::copy( ViewController* source ) { Config config; source->save( config ); ViewController* copy_of_source = create( source->getClassId() ); copy_of_source->load( config ); return copy_of_source; } void ViewManager::setRenderPanel( RenderPanel* render_panel ) { render_panel_ = render_panel; } Qt::ItemFlags ViewControllerContainer::getViewFlags( int column ) const { return Property::getViewFlags( column ) | Qt::ItemIsDropEnabled; } void ViewControllerContainer::addChild( Property* child, int index ) { if( index == 0 ) { index = 1; } Property::addChild( child, index ); } void ViewControllerContainer::addChildToFront( Property* child ) { Property::addChild( child, 0 ); } } // end namespace rviz <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief img メイン関係 @author 平松邦仁 ([email protected]) */ //=====================================================================// #include <iostream> #include "img_main.hpp" #include "core/glcore.hpp" #include "widgets/widget_utils.hpp" namespace app { //-----------------------------------------------------------------// /*! @brief 初期化 */ //-----------------------------------------------------------------// void img_main::initialize() { gl::IGLcore* igl = gl::get_glcore(); using namespace gui; widget_director& wd = director_.at().widget_director_; { // 画像ファイル表示用フレーム widget::param wp(vtx::srect(30, 30, 256, 256)); widget_frame::param wp_; frame_ = wd.add_widget<widget_frame>(wp, wp_); } { // 画像ファイル表示イメージ widget::param wp(vtx::srect(0, 0, 256, 256), frame_); widget_image::param wp_; image_ = wd.add_widget<widget_image>(wp, wp_); image_->set_state(widget::state::CLIP_PARENTS); } { // 機能ツールパレット widget::param wp(vtx::srect(10, 10, 120, 300)); widget_frame::param wp_; tools_ = wd.add_widget<widget_frame>(wp, wp_); } { // ファイラー起動ボタン widget::param wp(vtx::srect(5, 5, 100, 40), tools_); widget_button::param wp_("file"); open_ = wd.add_widget<widget_button>(wp, wp_); } { // ファイラー本体 widget::param wp(vtx::srect(10, 30, 300, 200)); widget_filer::param wp_(igl->get_current_path()); filer_ = wd.add_widget<widget_filer>(wp, wp_); filer_->enable(false); } { // ダイアログ widget::param wp(vtx::srect(10, 30, 450, 200)); widget_dialog::param wp_; dialog_ = wd.add_widget<widget_dialog>(wp, wp_); dialog_->enable(false); } mobj_.initialize(); // プリファレンスの取得 sys::preference& pre = director_.at().preference_; if(filer_) { filer_->load(pre); frame_->load(pre); tools_->load(pre); } } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void img_main::update() { gl::IGLcore* igl = gl::get_glcore(); const vtx::spos& size = igl->get_size(); gui::widget_director& wd = director_.at().widget_director_; if(open_) { if(open_->get_selected()) { if(filer_) { bool f = filer_->get_state(gui::widget::state::ENABLE); filer_->enable(!f); } } } if(filer_) { if(filer_id_ != filer_->get_select_file_id()) { filer_id_ = filer_->get_select_file_id(); img::img_files& imf = wd.at_img_files(); if(!imf.load(filer_->get_file())) { dialog_->set_text("Can't decode image file:\n '" + filer_->get_file() + "'"); dialog_->enable(); } else { mobj_.destroy(); mobj_.initialize(); img_handle_ = mobj_.install(imf.get_image_if()); image_->at_local_param().mobj_ = mobj_; image_->at_local_param().mobj_handle_ = img_handle_; // imf.set_image_if(imf.get_image_if()); // imf.save("test.tga", "rle"); } } } // frame 内 image のサイズを設定 if(frame_ && image_) { vtx::spos ofs(frame_->get_local_param().plate_param_.frame_width_); image_->at_rect().org = ofs; image_->at_rect().size = frame_->get_rect().size - ofs * 2; } wd.update(); } //-----------------------------------------------------------------// /*! @brief レンダリング */ //-----------------------------------------------------------------// void img_main::render() { director_.at().widget_director_.service(); director_.at().widget_director_.render(); } //-----------------------------------------------------------------// /*! @brief 廃棄 */ //-----------------------------------------------------------------// void img_main::destroy() { sys::preference& pre = director_.at().preference_; if(filer_) { filer_->save(pre); frame_->save(pre); tools_->save(pre); } } } <commit_msg>画像フレームのリサイズ対応<commit_after>//=====================================================================// /*! @file @brief img メイン関係 @author 平松邦仁 ([email protected]) */ //=====================================================================// #include <iostream> #include "img_main.hpp" #include "core/glcore.hpp" #include "widgets/widget_utils.hpp" namespace app { //-----------------------------------------------------------------// /*! @brief 初期化 */ //-----------------------------------------------------------------// void img_main::initialize() { gl::IGLcore* igl = gl::get_glcore(); using namespace gui; widget_director& wd = director_.at().widget_director_; { // 画像ファイル表示用フレーム widget::param wp(vtx::srect(30, 30, 256, 256)); widget_frame::param wp_; frame_ = wd.add_widget<widget_frame>(wp, wp_); } { // 画像ファイル表示イメージ widget::param wp(vtx::srect(0, 0, 256, 256), frame_); widget_image::param wp_; image_ = wd.add_widget<widget_image>(wp, wp_); image_->set_state(widget::state::CLIP_PARENTS); image_->set_state(widget::state::RESIZE_ROOT); } { // 機能ツールパレット widget::param wp(vtx::srect(10, 10, 120, 300)); widget_frame::param wp_; tools_ = wd.add_widget<widget_frame>(wp, wp_); } { // ファイラー起動ボタン widget::param wp(vtx::srect(5, 5, 100, 40), tools_); widget_button::param wp_("file"); open_ = wd.add_widget<widget_button>(wp, wp_); } { // ファイラー本体 widget::param wp(vtx::srect(10, 30, 300, 200)); widget_filer::param wp_(igl->get_current_path()); filer_ = wd.add_widget<widget_filer>(wp, wp_); filer_->enable(false); } { // ダイアログ widget::param wp(vtx::srect(10, 30, 450, 200)); widget_dialog::param wp_; dialog_ = wd.add_widget<widget_dialog>(wp, wp_); dialog_->enable(false); } mobj_.initialize(); // プリファレンスの取得 sys::preference& pre = director_.at().preference_; if(filer_) { filer_->load(pre); frame_->load(pre); tools_->load(pre); } } //-----------------------------------------------------------------// /*! @brief アップデート */ //-----------------------------------------------------------------// void img_main::update() { gl::IGLcore* igl = gl::get_glcore(); const vtx::spos& size = igl->get_size(); gui::widget_director& wd = director_.at().widget_director_; if(open_) { if(open_->get_selected()) { if(filer_) { bool f = filer_->get_state(gui::widget::state::ENABLE); filer_->enable(!f); } } } if(filer_) { if(filer_id_ != filer_->get_select_file_id()) { filer_id_ = filer_->get_select_file_id(); img::img_files& imf = wd.at_img_files(); if(!imf.load(filer_->get_file())) { dialog_->set_text("Can't decode image file:\n '" + filer_->get_file() + "'"); dialog_->enable(); } else { mobj_.destroy(); mobj_.initialize(); img_handle_ = mobj_.install(imf.get_image_if()); image_->at_local_param().mobj_ = mobj_; image_->at_local_param().mobj_handle_ = img_handle_; // imf.set_image_if(imf.get_image_if()); // imf.save("test.tga", "rle"); } } } // frame 内 image のサイズを設定 if(frame_ && image_) { vtx::spos ofs(frame_->get_local_param().plate_param_.frame_width_); image_->at_rect().org = ofs; image_->at_rect().size = frame_->get_rect().size - ofs * 2; } wd.update(); } //-----------------------------------------------------------------// /*! @brief レンダリング */ //-----------------------------------------------------------------// void img_main::render() { director_.at().widget_director_.service(); director_.at().widget_director_.render(); } //-----------------------------------------------------------------// /*! @brief 廃棄 */ //-----------------------------------------------------------------// void img_main::destroy() { sys::preference& pre = director_.at().preference_; if(filer_) { filer_->save(pre); frame_->save(pre); tools_->save(pre); } } } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Mathematics (glm.g-truc.net) /// /// Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net) /// 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. /// /// @file glm/gtc/matrix_transform.hpp /// @date 2009-04-29 / 2011-05-16 /// @author Christophe Riccio /// /// @ref gtc_matrix_transform /// @see core (dependence) /// @see gtc_matrix_transform /// @see gtx_transform /// @see gtx_transform2 /////////////////////////////////////////////////////////////////////////////////// #ifndef glm_gtc_matrix_transform #define glm_gtc_matrix_transform // Dependency: #include "../glm.hpp" #if(defined(GLM_MESSAGES) && !defined(glm_ext)) # pragma message("GLM: GLM_GTC_matrix_transform extension included") #endif namespace glm{ namespace test{ bool main_gtc_matrix_transform(); }//namespace test namespace gtc{ /// GLM_GTC_matrix_transform extension: Add transformation matrices namespace matrix_transform { /// @addtogroup gtc_matrix_transform /// @{ /// Builds a translation 4 * 4 matrix created from a vector of 3 components. /// @see - gtc_matrix_transform /// @see - gtx_transform: /// - @link glm::gtx::transform::translate(T x, T y, T z) translate(T x, T y, T z) @endlink /// - @link glm::gtx::transform::translate(detail::tmat4x4<T> const & m, T x, T y, T z) translate(mat4x4<T> const & m, T x, T y, T z) @endlink template <typename T> detail::tmat4x4<T> translate( detail::tmat4x4<T> const & m, detail::tvec3<T> const & v); /// Builds a rotation 4 * 4 matrix created from an axis vector and an angle expressed in degrees. /// @see - gtc_matrix_transform /// @see - gtx_transform: /// - @link glm::gtx::transform::rotate(T angle, T x, T y, T z) rotate(T const & angle, T const & x, T const & y, T const & z) @endlink /// - @link glm::gtx::transform::rotate(detail::tmat4x4<T> const & m, T angle, T x, T y, T z) rotate(mat4x4<T> const & m, T const & angle, T const & x, T const & y, T const & z) @endlink template <typename T> detail::tmat4x4<T> rotate( detail::tmat4x4<T> const & m, T const & angle, detail::tvec3<T> const & v); /// Builds a scale 4 * 4 matrix created from 3 scalars. /// @see - gtc_matrix_transform /// @see - gtx_transform: /// - @link glm::gtx::transform::scale(T x, T y, T z) rotate(T const & angle, T const & x, T const & y, T const & z) @endlink /// - @link glm::gtx::transform::scale(detail::tmat4x4<T> const & m, T x, T y, T z) rotate(mat4x4<T> const & m, T const & angle, T const & x, T const & y, T const & z) @endlink template <typename T> detail::tmat4x4<T> scale( detail::tmat4x4<T> const & m, detail::tvec3<T> const & v); /// Creates a matrix for an orthographic parallel viewing volume. /// @see - gtc_matrix_transform: /// - @link glm::gtc::matrix_transform::ortho(T const & left, T const & right, T const & bottom, T const & top) ortho(T const & left, T const & right, T const & bottom, T const & top) @endlink template <typename T> detail::tmat4x4<T> ortho( T const & left, T const & right, T const & bottom, T const & top, T const & zNear, T const & zFar); /// Creates a matrix for projecting two-dimensional coordinates onto the screen. /// @see - gtc_matrix_transform: /// - @link glm::gtc::matrix_transform::ortho(T const & left, T const & right, T const & bottom, T const & top, T const & zNear, T const & zFar) ortho(T const & left, T const & right, T const & bottom, T const & top, T const & zNear, T const & zFar) @endlink template <typename T> detail::tmat4x4<T> ortho( T const & left, T const & right, T const & bottom, T const & top); /// Creates a frustum matrix. /// @see - gtc_matrix_transform template <typename T> detail::tmat4x4<T> frustum( T const & left, T const & right, T const & bottom, T const & top, T const & nearVal, T const & farVal); /// Creates a matrix for a symetric perspective-view frustum. /// @see - gtc_matrix_transform template <typename T> detail::tmat4x4<T> perspective( T const & fovy, T const & aspect, T const & zNear, T const & zFar); /// Builds a perspective projection matrix based on a field of view /// @see - gtc_matrix_transform template <typename valType> detail::tmat4x4<valType> perspectiveFov( valType const & fov, valType const & width, valType const & height, valType const & zNear, valType const & zFar); /// Creates a matrix for a symmetric perspective-view frustum with far plane at infinite . /// @see - gtc_matrix_transform template <typename T> detail::tmat4x4<T> infinitePerspective( T fovy, T aspect, T zNear); /// Creates a matrix for a symmetric perspective-view frustum with far plane at infinite for graphics hardware that doesn't support depth clamping. /// @see - gtc_matrix_transform template <typename T> detail::tmat4x4<T> tweakedInfinitePerspective( T fovy, T aspect, T zNear); /// Map the specified object coordinates (obj.x, obj.y, obj.z) into window coordinates. /// @see - gtc_matrix_transform template <typename T, typename U> detail::tvec3<T> project( detail::tvec3<T> const & obj, detail::tmat4x4<T> const & model, detail::tmat4x4<T> const & proj, detail::tvec4<U> const & viewport); /// Map the specified window coordinates (win.x, win.y, win.z) into object coordinates. /// @see - gtc_matrix_transform template <typename T, typename U> detail::tvec3<T> unProject( detail::tvec3<T> const & win, detail::tmat4x4<T> const & model, detail::tmat4x4<T> const & proj, detail::tvec4<U> const & viewport); /// Define a picking region /// @see - gtc_matrix_transform template <typename T, typename U> detail::tmat4x4<T> pickMatrix( detail::tvec2<T> const & center, detail::tvec2<T> const & delta, detail::tvec4<U> const & viewport); /// Build a look at view matrix. /// @see - gtc_matrix_transform: /// - @link frustum(T const & left, T const & right, T const & bottom, T const & top, T const & nearVal, T const & farVal) frustum(T const & left, T const & right, T const & bottom, T const & top, T const & nearVal, T const & farVal) @endlink /// @param eye Position of the camera /// @param center Position where the camera is looking at /// @param up Normalized up vector, how the camera is oriented. Typically (0, 0, 1) template <typename T> detail::tmat4x4<T> lookAt( detail::tvec3<T> const & eye, detail::tvec3<T> const & center, detail::tvec3<T> const & up); /// @} }//namespace matrix_transform }//namespace gtc }//namespace glm #include "matrix_transform.inl" namespace glm{using namespace gtc::matrix_transform;} #endif//glm_gtc_matrix_transform <commit_msg>Improved doxygens documentation<commit_after>/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Mathematics (glm.g-truc.net) /// /// Copyright (c) 2005 - 2011 G-Truc Creation (www.g-truc.net) /// 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. /// /// @ref gtc_matrix_transform /// @file glm/gtc/matrix_transform.hpp /// @date 2009-04-29 / 2011-05-16 /// @author Christophe Riccio /// /// @see core (dependence) /// @see gtx_transform /// @see gtx_transform2 /////////////////////////////////////////////////////////////////////////////////// #ifndef glm_gtc_matrix_transform #define glm_gtc_matrix_transform // Dependency: #include "../glm.hpp" #if(defined(GLM_MESSAGES) && !defined(glm_ext)) # pragma message("GLM: GLM_GTC_matrix_transform extension included") #endif namespace glm{ namespace test{ bool main_gtc_matrix_transform(); }//namespace test namespace gtc{ /// GLM_GTC_matrix_transform extension: Add transformation matrices namespace matrix_transform { /// @addtogroup gtc_matrix_transform /// @{ /// Builds a translation 4 * 4 matrix created from a vector of 3 components. /// @see - gtc_matrix_transform /// @see - gtx_transform: /// - @link glm::gtx::transform::translate(T x, T y, T z) translate(T x, T y, T z) @endlink /// - @link glm::gtx::transform::translate(detail::tmat4x4<T> const & m, T x, T y, T z) translate(mat4x4<T> const & m, T x, T y, T z) @endlink /// - @link glm::gtx::transform::translate(detail::tvec3<T> const & v) translate(vec3<T> const & v) @endlink template <typename T> detail::tmat4x4<T> translate( detail::tmat4x4<T> const & m, detail::tvec3<T> const & v); /// Builds a rotation 4 * 4 matrix created from an axis vector and an angle expressed in degrees. /// @see - gtc_matrix_transform /// @see - gtx_transform: /// - @link glm::gtx::transform::rotate(T angle, T x, T y, T z) rotate(T const & angle, T const & x, T const & y, T const & z) @endlink /// - @link glm::gtx::transform::rotate(detail::tmat4x4<T> const & m, T angle, T x, T y, T z) rotate(mat4x4<T> const & m, T const & angle, T const & x, T const & y, T const & z) @endlink /// - @link glm::gtx::transform::rotate(T angle, detail::tvec3<T> const & v) rotate(T const & angle, vec3<T> const & v) @endlink template <typename T> detail::tmat4x4<T> rotate( detail::tmat4x4<T> const & m, T const & angle, detail::tvec3<T> const & v); /// Builds a scale 4 * 4 matrix created from 3 scalars. /// @see - gtc_matrix_transform /// @see - gtx_transform: /// - @link glm::gtx::transform::scale(T x, T y, T z) scale(T const & x, T const & y, T const & z) @endlink /// - @link glm::gtx::transform::scale(detail::tmat4x4<T> const & m, T x, T y, T z) scale(mat4x4<T> const & m, T const & angle, T const & x, T const & y, T const & z) @endlink /// - @link glm::gtx::transform::scale(detail::tvec3<T> const & v) scale(vec3<T> const & v) @endlink template <typename T> detail::tmat4x4<T> scale( detail::tmat4x4<T> const & m, detail::tvec3<T> const & v); /// Creates a matrix for an orthographic parallel viewing volume. /// @see - gtc_matrix_transform: /// - @link glm::gtc::matrix_transform::ortho(T const & left, T const & right, T const & bottom, T const & top) ortho(T const & left, T const & right, T const & bottom, T const & top) @endlink template <typename T> detail::tmat4x4<T> ortho( T const & left, T const & right, T const & bottom, T const & top, T const & zNear, T const & zFar); /// Creates a matrix for projecting two-dimensional coordinates onto the screen. /// @see - gtc_matrix_transform: /// - @link glm::gtc::matrix_transform::ortho(T const & left, T const & right, T const & bottom, T const & top, T const & zNear, T const & zFar) ortho(T const & left, T const & right, T const & bottom, T const & top, T const & zNear, T const & zFar) @endlink template <typename T> detail::tmat4x4<T> ortho( T const & left, T const & right, T const & bottom, T const & top); /// Creates a frustum matrix. /// @see - gtc_matrix_transform template <typename T> detail::tmat4x4<T> frustum( T const & left, T const & right, T const & bottom, T const & top, T const & nearVal, T const & farVal); /// Creates a matrix for a symetric perspective-view frustum. /// @see - gtc_matrix_transform template <typename T> detail::tmat4x4<T> perspective( T const & fovy, T const & aspect, T const & zNear, T const & zFar); /// Builds a perspective projection matrix based on a field of view /// @see - gtc_matrix_transform template <typename valType> detail::tmat4x4<valType> perspectiveFov( valType const & fov, valType const & width, valType const & height, valType const & zNear, valType const & zFar); /// Creates a matrix for a symmetric perspective-view frustum with far plane at infinite . /// @see - gtc_matrix_transform template <typename T> detail::tmat4x4<T> infinitePerspective( T fovy, T aspect, T zNear); /// Creates a matrix for a symmetric perspective-view frustum with far plane at infinite for graphics hardware that doesn't support depth clamping. /// @see - gtc_matrix_transform template <typename T> detail::tmat4x4<T> tweakedInfinitePerspective( T fovy, T aspect, T zNear); /// Map the specified object coordinates (obj.x, obj.y, obj.z) into window coordinates. /// @see - gtc_matrix_transform template <typename T, typename U> detail::tvec3<T> project( detail::tvec3<T> const & obj, detail::tmat4x4<T> const & model, detail::tmat4x4<T> const & proj, detail::tvec4<U> const & viewport); /// Map the specified window coordinates (win.x, win.y, win.z) into object coordinates. /// @see - gtc_matrix_transform template <typename T, typename U> detail::tvec3<T> unProject( detail::tvec3<T> const & win, detail::tmat4x4<T> const & model, detail::tmat4x4<T> const & proj, detail::tvec4<U> const & viewport); /// Define a picking region /// @see - gtc_matrix_transform template <typename T, typename U> detail::tmat4x4<T> pickMatrix( detail::tvec2<T> const & center, detail::tvec2<T> const & delta, detail::tvec4<U> const & viewport); /// Build a look at view matrix. /// @see - gtc_matrix_transform: /// - @link frustum(T const & left, T const & right, T const & bottom, T const & top, T const & nearVal, T const & farVal) frustum(T const & left, T const & right, T const & bottom, T const & top, T const & nearVal, T const & farVal) @endlink /// @param eye Position of the camera /// @param center Position where the camera is looking at /// @param up Normalized up vector, how the camera is oriented. Typically (0, 0, 1) template <typename T> detail::tmat4x4<T> lookAt( detail::tvec3<T> const & eye, detail::tvec3<T> const & center, detail::tvec3<T> const & up); /// @} }//namespace matrix_transform }//namespace gtc }//namespace glm #include "matrix_transform.inl" namespace glm{using namespace gtc::matrix_transform;} #endif//glm_gtc_matrix_transform <|endoftext|>
<commit_before>/* * Copyright (C) 1999 Lars Knoll ([email protected]) * (C) 2004-2005 Allan Sandfeld Jensen ([email protected]) * Copyright (C) 2006, 2007 Nicholas Shanks ([email protected]) * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved. * Copyright (C) 2007 Alexey Proskuryakov <[email protected]> * Copyright (C) 2007, 2008 Eric Seidel <[email protected]> * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * Copyright (c) 2011, Code Aurora Forum. All rights reserved. * Copyright (C) Research In Motion Limited 2011. All rights reserved. * Copyright (C) 2013 Google Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "core/css/resolver/MatchedPropertiesCache.h" #include "core/css/StylePropertySet.h" #include "core/css/resolver/StyleResolverState.h" #include "core/rendering/style/RenderStyle.h" namespace blink { #if ENABLE(OILPAN) bool CachedMatchedPropertiesHashTraits::traceInCollection(Visitor* visitor, Member<CachedMatchedProperties>& cachedProperties, WTF::ShouldWeakPointersBeMarkedStrongly strongify) { // Only honor the cache's weakness semantics if the collection is traced // with WeakPointersActWeak. Otherwise just trace the cachedProperties // strongly, ie. call trace on it. if (cachedProperties && strongify == WTF::WeakPointersActWeak) { // A given cache entry is only kept alive if none of the MatchedProperties // in the CachedMatchedProperties value contain a dead "properties" field. // If there is a dead field the entire cache entry is removed. for (const auto& cachedProperties : cachedProperties->matchedProperties) { if (!visitor->isAlive(cachedProperties.properties)) { // For now report the cache entry as dead. This might not // be the final result if in a subsequent call for this entry, // the "properties" field has been marked via another path. return true; } } } // At this point none of the entries in the matchedProperties vector // had a dead "properties" field so trace CachedMatchedProperties strongly. visitor->trace(cachedProperties); return false; } #endif void CachedMatchedProperties::set(const RenderStyle* style, const RenderStyle* parentStyle, const MatchResult& matchResult) { matchedProperties.appendVector(matchResult.matchedProperties); ranges = matchResult.ranges; // Note that we don't cache the original RenderStyle instance. It may be further modified. // The RenderStyle in the cache is really just a holder for the substructures and never used as-is. this->renderStyle = RenderStyle::clone(style); this->parentRenderStyle = RenderStyle::clone(parentStyle); } void CachedMatchedProperties::clear() { matchedProperties.clear(); renderStyle = nullptr; parentRenderStyle = nullptr; } MatchedPropertiesCache::MatchedPropertiesCache() #if !ENABLE(OILPAN) : m_additionsSinceLastSweep(0) , m_sweepTimer(this, &MatchedPropertiesCache::sweep) #endif { } const CachedMatchedProperties* MatchedPropertiesCache::find(unsigned hash, const StyleResolverState& styleResolverState, const MatchResult& matchResult) { ASSERT(hash); Cache::iterator it = m_cache.find(hash); if (it == m_cache.end()) return 0; CachedMatchedProperties* cacheItem = it->value.get(); ASSERT(cacheItem); size_t size = matchResult.matchedProperties.size(); if (size != cacheItem->matchedProperties.size()) return 0; if (cacheItem->renderStyle->insideLink() != styleResolverState.style()->insideLink()) return 0; for (size_t i = 0; i < size; ++i) { if (matchResult.matchedProperties[i] != cacheItem->matchedProperties[i]) return 0; } if (cacheItem->ranges != matchResult.ranges) return 0; return cacheItem; } void MatchedPropertiesCache::add(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult) { #if !ENABLE(OILPAN) static const unsigned maxAdditionsBetweenSweeps = 100; if (++m_additionsSinceLastSweep >= maxAdditionsBetweenSweeps && !m_sweepTimer.isActive()) { static const unsigned sweepTimeInSeconds = 60; m_sweepTimer.startOneShot(sweepTimeInSeconds, FROM_HERE); } #endif ASSERT(hash); Cache::AddResult addResult = m_cache.add(hash, nullptr); if (addResult.isNewEntry) addResult.storedValue->value = adoptPtrWillBeNoop(new CachedMatchedProperties); CachedMatchedProperties* cacheItem = addResult.storedValue->value.get(); if (!addResult.isNewEntry) cacheItem->clear(); cacheItem->set(style, parentStyle, matchResult); } void MatchedPropertiesCache::clear() { m_cache.clear(); } void MatchedPropertiesCache::clearViewportDependent() { Vector<unsigned, 16> toRemove; for (const auto& cacheEntry : m_cache) { CachedMatchedProperties* cacheItem = cacheEntry.value.get(); if (cacheItem->renderStyle->hasViewportUnits()) toRemove.append(cacheEntry.key); } m_cache.removeAll(toRemove); } #if !ENABLE(OILPAN) void MatchedPropertiesCache::sweep(Timer<MatchedPropertiesCache>*) { // Look for cache entries containing a style declaration with a single ref and remove them. // This may happen when an element attribute mutation causes it to generate a new inlineStyle() // or presentationAttributeStyle(), potentially leaving this cache with the last ref on the old one. Vector<unsigned, 16> toRemove; for (const auto& cacheEntry : m_cache) { CachedMatchedProperties* cacheItem = cacheEntry.value.get(); Vector<MatchedProperties>& matchedProperties = cacheItem->matchedProperties; for (size_t i = 0; i < matchedProperties.size(); ++i) { if (matchedProperties[i].properties->hasOneRef()) { toRemove.append(cacheEntry.key); break; } } } m_cache.removeAll(toRemove); m_additionsSinceLastSweep = 0; } #endif bool MatchedPropertiesCache::isCacheable(const Element* element, const RenderStyle* style, const RenderStyle* parentStyle) { // FIXME: CSSPropertyWebkitWritingMode modifies state when applying to document element. We can't skip the applying by caching. if (element == element->document().documentElement() && element->document().writingModeSetOnDocumentElement()) return false; if (style->unique() || (style->styleType() != NOPSEUDO && parentStyle->unique())) return false; if (style->hasAppearance()) return false; if (style->zoom() != RenderStyle::initialZoom()) return false; if (style->writingMode() != RenderStyle::initialWritingMode()) return false; // The cache assumes static knowledge about which properties are inherited. if (parentStyle->hasExplicitlyInheritedProperties()) return false; return true; } void MatchedPropertiesCache::trace(Visitor* visitor) { #if ENABLE(OILPAN) visitor->trace(m_cache); #endif } } <commit_msg>Steer clear of g++ scoping bug in range-based for loop.<commit_after>/* * Copyright (C) 1999 Lars Knoll ([email protected]) * (C) 2004-2005 Allan Sandfeld Jensen ([email protected]) * Copyright (C) 2006, 2007 Nicholas Shanks ([email protected]) * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved. * Copyright (C) 2007 Alexey Proskuryakov <[email protected]> * Copyright (C) 2007, 2008 Eric Seidel <[email protected]> * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/) * Copyright (c) 2011, Code Aurora Forum. All rights reserved. * Copyright (C) Research In Motion Limited 2011. All rights reserved. * Copyright (C) 2013 Google Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "core/css/resolver/MatchedPropertiesCache.h" #include "core/css/StylePropertySet.h" #include "core/css/resolver/StyleResolverState.h" #include "core/rendering/style/RenderStyle.h" namespace blink { #if ENABLE(OILPAN) bool CachedMatchedPropertiesHashTraits::traceInCollection(Visitor* visitor, Member<CachedMatchedProperties>& cachedProperties, WTF::ShouldWeakPointersBeMarkedStrongly strongify) { // Only honor the cache's weakness semantics if the collection is traced // with WeakPointersActWeak. Otherwise just trace the cachedProperties // strongly, ie. call trace on it. if (cachedProperties && strongify == WTF::WeakPointersActWeak) { // A given cache entry is only kept alive if none of the MatchedProperties // in the CachedMatchedProperties value contain a dead "properties" field. // If there is a dead field the entire cache entry is removed. for (const auto& matchedProperties : cachedProperties->matchedProperties) { if (!visitor->isAlive(matchedProperties.properties)) { // For now report the cache entry as dead. This might not // be the final result if in a subsequent call for this entry, // the "properties" field has been marked via another path. return true; } } } // At this point none of the entries in the matchedProperties vector // had a dead "properties" field so trace CachedMatchedProperties strongly. visitor->trace(cachedProperties); return false; } #endif void CachedMatchedProperties::set(const RenderStyle* style, const RenderStyle* parentStyle, const MatchResult& matchResult) { matchedProperties.appendVector(matchResult.matchedProperties); ranges = matchResult.ranges; // Note that we don't cache the original RenderStyle instance. It may be further modified. // The RenderStyle in the cache is really just a holder for the substructures and never used as-is. this->renderStyle = RenderStyle::clone(style); this->parentRenderStyle = RenderStyle::clone(parentStyle); } void CachedMatchedProperties::clear() { matchedProperties.clear(); renderStyle = nullptr; parentRenderStyle = nullptr; } MatchedPropertiesCache::MatchedPropertiesCache() #if !ENABLE(OILPAN) : m_additionsSinceLastSweep(0) , m_sweepTimer(this, &MatchedPropertiesCache::sweep) #endif { } const CachedMatchedProperties* MatchedPropertiesCache::find(unsigned hash, const StyleResolverState& styleResolverState, const MatchResult& matchResult) { ASSERT(hash); Cache::iterator it = m_cache.find(hash); if (it == m_cache.end()) return 0; CachedMatchedProperties* cacheItem = it->value.get(); ASSERT(cacheItem); size_t size = matchResult.matchedProperties.size(); if (size != cacheItem->matchedProperties.size()) return 0; if (cacheItem->renderStyle->insideLink() != styleResolverState.style()->insideLink()) return 0; for (size_t i = 0; i < size; ++i) { if (matchResult.matchedProperties[i] != cacheItem->matchedProperties[i]) return 0; } if (cacheItem->ranges != matchResult.ranges) return 0; return cacheItem; } void MatchedPropertiesCache::add(const RenderStyle* style, const RenderStyle* parentStyle, unsigned hash, const MatchResult& matchResult) { #if !ENABLE(OILPAN) static const unsigned maxAdditionsBetweenSweeps = 100; if (++m_additionsSinceLastSweep >= maxAdditionsBetweenSweeps && !m_sweepTimer.isActive()) { static const unsigned sweepTimeInSeconds = 60; m_sweepTimer.startOneShot(sweepTimeInSeconds, FROM_HERE); } #endif ASSERT(hash); Cache::AddResult addResult = m_cache.add(hash, nullptr); if (addResult.isNewEntry) addResult.storedValue->value = adoptPtrWillBeNoop(new CachedMatchedProperties); CachedMatchedProperties* cacheItem = addResult.storedValue->value.get(); if (!addResult.isNewEntry) cacheItem->clear(); cacheItem->set(style, parentStyle, matchResult); } void MatchedPropertiesCache::clear() { m_cache.clear(); } void MatchedPropertiesCache::clearViewportDependent() { Vector<unsigned, 16> toRemove; for (const auto& cacheEntry : m_cache) { CachedMatchedProperties* cacheItem = cacheEntry.value.get(); if (cacheItem->renderStyle->hasViewportUnits()) toRemove.append(cacheEntry.key); } m_cache.removeAll(toRemove); } #if !ENABLE(OILPAN) void MatchedPropertiesCache::sweep(Timer<MatchedPropertiesCache>*) { // Look for cache entries containing a style declaration with a single ref and remove them. // This may happen when an element attribute mutation causes it to generate a new inlineStyle() // or presentationAttributeStyle(), potentially leaving this cache with the last ref on the old one. Vector<unsigned, 16> toRemove; for (const auto& cacheEntry : m_cache) { CachedMatchedProperties* cacheItem = cacheEntry.value.get(); Vector<MatchedProperties>& matchedProperties = cacheItem->matchedProperties; for (size_t i = 0; i < matchedProperties.size(); ++i) { if (matchedProperties[i].properties->hasOneRef()) { toRemove.append(cacheEntry.key); break; } } } m_cache.removeAll(toRemove); m_additionsSinceLastSweep = 0; } #endif bool MatchedPropertiesCache::isCacheable(const Element* element, const RenderStyle* style, const RenderStyle* parentStyle) { // FIXME: CSSPropertyWebkitWritingMode modifies state when applying to document element. We can't skip the applying by caching. if (element == element->document().documentElement() && element->document().writingModeSetOnDocumentElement()) return false; if (style->unique() || (style->styleType() != NOPSEUDO && parentStyle->unique())) return false; if (style->hasAppearance()) return false; if (style->zoom() != RenderStyle::initialZoom()) return false; if (style->writingMode() != RenderStyle::initialWritingMode()) return false; // The cache assumes static knowledge about which properties are inherited. if (parentStyle->hasExplicitlyInheritedProperties()) return false; return true; } void MatchedPropertiesCache::trace(Visitor* visitor) { #if ENABLE(OILPAN) visitor->trace(m_cache); #endif } } <|endoftext|>
<commit_before>/* * This file is part of QtZeitgeist. * * Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "QtZeitgeist/DataModel/DataSource" #include <QMetaType> #include <QDBusMetaType> namespace QtZeitgeist { namespace DataModel { class DataSourcePrivate { public : QString uniqueId; QString name; QString description; QList<Event> eventTemplates; bool running; QDateTime lastSeen; bool enabled; }; DataSource::DataSource(QObject *parent) : d(new DataSourcePrivate()) { Q_ASSERT(d); // Initialize the last seen time. d->lastSeen.setTime_t(0); } DataSource::DataSource(const DataSource & source, QObject *parent) : d(new DataSourcePrivate()) { Q_ASSERT(d); // Copy the source attribute's value. d->uniqueId = source.d->uniqueId; d->name = source.d->name; d->description = source.d->description; d->eventTemplates = source.d->eventTemplates; d->running = source.d->running; d->lastSeen = source.d->lastSeen; d->enabled = source.d->enabled; } DataSource::~DataSource() { delete d; } QString DataSource::uniqueId() const { return d->uniqueId; } QString DataSource::name() const { return d->name; } QString DataSource::description() const { return d->description; } QList<Event> DataSource::eventTemplates() const { return d->eventTemplates; } bool DataSource::running() const { return d->running; } QDateTime DataSource::lastSeen() const { return d->lastSeen; } bool DataSource::enabled() const { return d->enabled; } DataSource &DataSource::operator = (const DataSource & source) { // Copy the source attribute's value. if (this != &source) { d->uniqueId = source.d->uniqueId; d->name = source.d->name; d->description = source.d->description; d->eventTemplates = source.d->eventTemplates; d->running = source.d->running; d->lastSeen = source.d->lastSeen; d->enabled = source.d->enabled; } return *this; } QDBusArgument & operator << (QDBusArgument &argument, const DataSource &datasource) { argument.beginStructure(); argument << datasource.d->uniqueId << datasource.d->name << datasource.d->description << datasource.d->eventTemplates << datasource.d->running // Convert the QDateTime into msecs since epoch. << QString::number(datasource.d->lastSeen.toTime_t() * 1000) << datasource.d->enabled; argument.endStructure(); return argument; } const QDBusArgument & operator >> (const QDBusArgument &argument, DataSource &datasource) { argument.beginStructure(); QString lastSeenString; argument >> datasource.d->uniqueId >> datasource.d->name >> datasource.d->description >> datasource.d->eventTemplates >> datasource.d->running >> lastSeenString >> datasource.d->enabled; // Translate the last seen string datasource.d->lastSeen.setTime_t(0); datasource.d->lastSeen.addMSecs(lastSeenString.toLongLong()); argument.endStructure(); return argument; } }; }; <commit_msg>Fix marshalling of DataSources.<commit_after>/* * This file is part of QtZeitgeist. * * Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "QtZeitgeist/DataModel/DataSource" #include <QMetaType> #include <QDBusMetaType> namespace QtZeitgeist { namespace DataModel { class DataSourcePrivate { public : QString uniqueId; QString name; QString description; QList<Event> eventTemplates; bool running; QDateTime lastSeen; bool enabled; }; DataSource::DataSource(QObject *parent) : d(new DataSourcePrivate()) { Q_ASSERT(d); // Initialize the last seen time. d->lastSeen.setTime_t(0); } DataSource::DataSource(const DataSource & source, QObject *parent) : d(new DataSourcePrivate()) { Q_ASSERT(d); // Copy the source attribute's value. d->uniqueId = source.d->uniqueId; d->name = source.d->name; d->description = source.d->description; d->eventTemplates = source.d->eventTemplates; d->running = source.d->running; d->lastSeen = source.d->lastSeen; d->enabled = source.d->enabled; } DataSource::~DataSource() { delete d; } QString DataSource::uniqueId() const { return d->uniqueId; } QString DataSource::name() const { return d->name; } QString DataSource::description() const { return d->description; } QList<Event> DataSource::eventTemplates() const { return d->eventTemplates; } bool DataSource::running() const { return d->running; } QDateTime DataSource::lastSeen() const { return d->lastSeen; } bool DataSource::enabled() const { return d->enabled; } DataSource &DataSource::operator = (const DataSource & source) { // Copy the source attribute's value. if (this != &source) { d->uniqueId = source.d->uniqueId; d->name = source.d->name; d->description = source.d->description; d->eventTemplates = source.d->eventTemplates; d->running = source.d->running; d->lastSeen = source.d->lastSeen; d->enabled = source.d->enabled; } return *this; } QDBusArgument & operator << (QDBusArgument &argument, const DataSource &datasource) { argument.beginStructure(); // Convert the QDateTime into msecs since epoch. qint64 lastSeenMSecs = datasource.d->lastSeen.toTime_t() * 1000; argument << datasource.d->uniqueId << datasource.d->name << datasource.d->description << datasource.d->eventTemplates << datasource.d->running << lastSeenMSecs << datasource.d->enabled; argument.endStructure(); return argument; } const QDBusArgument & operator >> (const QDBusArgument &argument, DataSource &datasource) { argument.beginStructure(); qint64 lastSeenMSecs; argument >> datasource.d->uniqueId >> datasource.d->name >> datasource.d->description >> datasource.d->eventTemplates >> datasource.d->running >> lastSeenMSecs >> datasource.d->enabled; // Translate the last seen string datasource.d->lastSeen.setTime_t(0); datasource.d->lastSeen.addMSecs(lastSeenMSecs); argument.endStructure(); return argument; } }; }; <|endoftext|>
<commit_before>/* * Copyright (C) 2003 Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * 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 <cxxtools/function.h> #include <cxxtools/thread.h> #include <cxxtools/mutex.h> #include <cxxtools/condition.h> #include <iostream> #include <string> #include <unistd.h> cxxtools::Mutex coutMutex; cxxtools::Mutex conditionMutex; cxxtools::Condition running; #define PRINTLN(expr) \ do { \ cxxtools::MutexLock lock(coutMutex); \ std::cout << time(0) << ' ' << expr << std::endl; \ } while (false) class myDetachedThread : public cxxtools::DetachedThread { ~myDetachedThread(); protected: void run(); }; myDetachedThread::~myDetachedThread() { PRINTLN("myDetachedThread::~myDetachedThread() called"); } void myDetachedThread::run() { PRINTLN("myDetachedThread is starting"); cxxtools::MutexLock lock(conditionMutex); running.broadcast(); lock.unlock(); sleep(2); PRINTLN("myDetachedThread is ready"); } void someFunction() { PRINTLN("someFunction()"); sleep(1); PRINTLN("someFunction() ends"); } class AClass { std::string id; public: AClass(const std::string& id_) : id(id_) { } ~AClass() { PRINTLN("AClass::~AClass of object \"" << id << '"'); } void run() { PRINTLN("aFunction() of object \"" << id << '"'); sleep(1); PRINTLN("aFunction() of object \"" << id << "\" ends"); } }; int main() { try { cxxtools::MutexLock lock(conditionMutex); // detached threads are created on the heap. // They are deleted automatically when the thread ends. cxxtools::Thread* d = new myDetachedThread; d->create(); running.wait(lock); PRINTLN("myDetachedThread is running"); // run a function as a attached thread cxxtools::AttachedThread th( cxxtools::callable(someFunction) ); th.start(); // run a method of a object as a thread AClass aInstance("a instance"); AClass aInstance2("a instance 2"); cxxtools::AttachedThread aclassThread( cxxtools::callable(aInstance, &AClass::run) ); cxxtools::AttachedThread aclassThread2( cxxtools::callable(aInstance2, &AClass::run) ); aclassThread.start(); aclassThread2.start(); sleep(2); aclassThread.join(); aclassThread2.join(); // The detached thread is killed, if it does not come to an end before main. // The attached thread blocks the main-program, until it is ready. PRINTLN("main stops"); } catch (const std::exception& e) { std::cerr << "ERROR: " << e.what() << std::endl; } std::cout << "main stopped" << std::endl; } <commit_msg>use the right sleep-function in demo<commit_after>/* * Copyright (C) 2003 Tommi Maekitalo * * 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. * * As a special exception, you may use this file as part of a free * software library without restriction. Specifically, if other files * instantiate templates or use macros or inline functions from this * file, or you compile this file and link it with other files to * produce an executable, this file does not by itself cause the * resulting executable to be covered by the GNU General Public * License. This exception does not however invalidate any other * reasons why the executable file might be covered by the GNU Library * General Public License. * * 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 <cxxtools/function.h> #include <cxxtools/thread.h> #include <cxxtools/mutex.h> #include <cxxtools/condition.h> #include <iostream> #include <string> #include <unistd.h> cxxtools::Mutex coutMutex; cxxtools::Mutex conditionMutex; cxxtools::Condition running; #define PRINTLN(expr) \ do { \ cxxtools::MutexLock lock(coutMutex); \ std::cout << time(0) << ' ' << expr << std::endl; \ } while (false) class myDetachedThread : public cxxtools::DetachedThread { ~myDetachedThread(); protected: void run(); }; myDetachedThread::~myDetachedThread() { PRINTLN("myDetachedThread::~myDetachedThread() called"); } void myDetachedThread::run() { PRINTLN("myDetachedThread is starting"); cxxtools::MutexLock lock(conditionMutex); running.broadcast(); lock.unlock(); ::sleep(1); PRINTLN("myDetachedThread waits"); ::sleep(2); PRINTLN("myDetachedThread is ready"); } void someFunction() { PRINTLN("someFunction()"); ::sleep(1); PRINTLN("someFunction() ends"); } class AClass { std::string id; public: AClass(const std::string& id_) : id(id_) { } ~AClass() { PRINTLN("AClass::~AClass of object \"" << id << '"'); } void run() { PRINTLN("aFunction() of object \"" << id << '"'); ::sleep(1); PRINTLN("aFunction() of object \"" << id << "\" ends"); } }; int main() { try { cxxtools::MutexLock lock(conditionMutex); // detached threads are created on the heap. // They are deleted automatically when the thread ends. cxxtools::Thread* d = new myDetachedThread; d->create(); running.wait(lock); PRINTLN("myDetachedThread is running"); // run a function as a attached thread cxxtools::AttachedThread th( cxxtools::callable(someFunction) ); th.start(); // run a method of a object as a thread AClass aInstance("a instance"); AClass aInstance2("a instance 2"); cxxtools::AttachedThread aclassThread( cxxtools::callable(aInstance, &AClass::run) ); cxxtools::AttachedThread aclassThread2( cxxtools::callable(aInstance2, &AClass::run) ); aclassThread.start(); aclassThread2.start(); ::sleep(2); aclassThread.join(); aclassThread2.join(); // The detached thread is killed, if it does not come to an end before main. // The attached thread blocks the main-program, until it is ready. PRINTLN("main stops"); } catch (const std::exception& e) { std::cerr << "ERROR: " << e.what() << std::endl; } std::cout << "main stopped" << std::endl; } <|endoftext|>
<commit_before>#include "llvm/Pass.h" #include "llvm/IR/Function.h" #include "llvm/Support/raw_ostream.h" #include "llvm/IR/Instructions.h" #include "llvm/InstVisitor.h" using namespace llvm; namespace { struct CustomInstVisitor : public InstVisitor<CustomInstVisitor> { CustomInstVisitor() : InstVisitor() {} void visitStoreInst(StoreInst &i) { errs() << "Store Inst Found: " << i.getName() << '\n'; } void visitAllocaInst(AllocaInst &i) { errs() << "Allocate Inst Found: " << i.getName() << '\n'; } void visitInstruction(Instruction &i) { errs() << "Analyzing Instruction: " << i.getName() << '\n'; } }; struct NaivePass : public FunctionPass { static char ID; NaivePass() : FunctionPass(ID) {} virtual bool runOnFunction(Function &F) { CustomInstVisitor visitor; visitor.visit(F); return false; } }; char NaivePass::ID = 0; static RegisterPass<NaivePass> X("naive-reaching", "Naive Reaching Analysis", false, false); } <commit_msg>Gen and Kill Sets made<commit_after>#include "llvm/Pass.h" #include "llvm/IR/Function.h" #include "llvm/Support/raw_ostream.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/InstVisitor.h" #include <set> #include <list> using namespace llvm; namespace { class GenAndKillSets { public: std::set<StoreInst *> gen; std::set<StoreInst *> kill; }; class BBGenAndKillSets { public: BasicBlock *bb; std::set<StoreInst *> gen; std::set<StoreInst *> kill; BBGenAndKillSets(BasicBlock *val) { bb = val; } std::string genString() { std::string ret = "Gen Set of BB:" + bb->getName().str() + '\n'; for (std::set<StoreInst *>::iterator it = gen.begin(); it != gen.end(); it++) { StoreInst *inst = *it; ret += '\t' + inst->getPointerOperand()->getName().str() + '\n'; } return ret; } }; struct NaivePass : public FunctionPass { static char ID; NaivePass() : FunctionPass(ID) {} virtual bool runOnFunction(Function &F) { std::list<BBGenAndKillSets> listOfSets; for (Function::iterator f_it = F.begin(); f_it != F.end(); ++f_it) { BBGenAndKillSets bbSets = createBBGenAndKillSets(F, f_it); errs() << bbSets.genString(); } return false; } BBGenAndKillSets createBBGenAndKillSets(Function &F, BasicBlock *f_it) { BBGenAndKillSets bbSets(f_it); for (BasicBlock::iterator bb_it = f_it->begin(); bb_it != f_it->end(); bb_it++) { if (StoreInst *inst = dyn_cast<StoreInst>(bb_it)) { Value *var = inst->getPointerOperand(); GenAndKillSets sets; sets.gen.insert(inst); for (Function::iterator f2_it = F.begin(); f2_it != F.end(); ++f2_it) { for (BasicBlock::iterator bb2_it = f2_it->begin(); bb2_it != f2_it->end(); bb2_it++) { if (bb2_it == bb_it) { continue; } if (StoreInst *inst2 = dyn_cast<StoreInst>(bb2_it)) { if (inst2->getPointerOperand() == var) { sets.kill.insert(inst2); } } } } for (std::set<StoreInst *>::iterator gen = sets.gen.begin(); gen != sets.gen.end(); gen++) { bbSets.gen.insert(*gen); } for (std::set<StoreInst *>::iterator kill = sets.kill.begin(); kill != sets.kill.end(); kill++) { bbSets.kill.insert(*kill); } } } return bbSets; } }; char NaivePass::ID = 0; static RegisterPass<NaivePass> X("naive-reaching", "Naive Reaching Analysis", false, false); } <|endoftext|>
<commit_before>/* * Copyright (c) 2019 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 "test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.h" #include <utility> #include "absl/memory/memory.h" #include "test/pc/e2e/analyzer/video/quality_analyzing_video_decoder.h" #include "test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.h" #include "test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.h" namespace webrtc { namespace webrtc_pc_e2e { namespace { // Intercepts generated frames and passes them also to video quality analyzer // and into video frame writer, if the last one is provided. class InterceptingFrameGenerator : public test::FrameGenerator { public: InterceptingFrameGenerator(std::string stream_label, std::unique_ptr<test::FrameGenerator> delegate, VideoQualityAnalyzerInterface* analyzer, test::VideoFrameWriter* video_writer) : stream_label_(std::move(stream_label)), delegate_(std::move(delegate)), analyzer_(analyzer), video_writer_(video_writer) { RTC_DCHECK(analyzer_); } ~InterceptingFrameGenerator() override = default; VideoFrame* NextFrame() override { VideoFrame* frame = delegate_->NextFrame(); uint16_t frame_id = analyzer_->OnFrameCaptured(stream_label_, *frame); frame->set_id(frame_id); if (video_writer_) { bool result = video_writer_->WriteFrame(*frame); RTC_CHECK(result) << "Failed to write frame"; } return frame; } void ChangeResolution(size_t width, size_t height) override { delegate_->ChangeResolution(width, height); } private: std::string stream_label_; std::unique_ptr<test::FrameGenerator> delegate_; VideoQualityAnalyzerInterface* analyzer_; test::VideoFrameWriter* video_writer_; }; // Implements the video sink, that forwards rendered frames to the video quality // analyzer and to the video frame writer, if the last one is provided. class AnalyzingVideoSink : public rtc::VideoSinkInterface<VideoFrame> { public: AnalyzingVideoSink(VideoQualityAnalyzerInterface* analyzer, test::VideoFrameWriter* video_writer) : analyzer_(analyzer), video_writer_(video_writer) { RTC_DCHECK(analyzer_); } ~AnalyzingVideoSink() override = default; void OnFrame(const VideoFrame& frame) override { if (IsDummyFrameBuffer(frame.video_frame_buffer()->ToI420())) { // This is dummy frame, so we don't need to process it further. return; } analyzer_->OnFrameRendered(frame); if (video_writer_) { bool result = video_writer_->WriteFrame(frame); RTC_CHECK(result) << "Failed to write frame"; } } void OnDiscardedFrame() override {} private: VideoQualityAnalyzerInterface* analyzer_; test::VideoFrameWriter* video_writer_; }; } // namespace VideoQualityAnalyzerInjectionHelper::VideoQualityAnalyzerInjectionHelper( std::unique_ptr<VideoQualityAnalyzerInterface> analyzer, EncodedImageDataInjector* injector, EncodedImageDataExtractor* extractor) : analyzer_(std::move(analyzer)), injector_(injector), extractor_(extractor), encoding_entities_id_generator_(absl::make_unique<IntIdGenerator>(1)) { RTC_DCHECK(injector_); RTC_DCHECK(extractor_); } VideoQualityAnalyzerInjectionHelper::~VideoQualityAnalyzerInjectionHelper() = default; std::unique_ptr<VideoEncoderFactory> VideoQualityAnalyzerInjectionHelper::WrapVideoEncoderFactory( std::unique_ptr<VideoEncoderFactory> delegate, double bitrate_multiplier, std::map<std::string, absl::optional<int>> stream_required_spatial_index) const { return absl::make_unique<QualityAnalyzingVideoEncoderFactory>( std::move(delegate), bitrate_multiplier, std::move(stream_required_spatial_index), encoding_entities_id_generator_.get(), injector_, analyzer_.get()); } std::unique_ptr<VideoDecoderFactory> VideoQualityAnalyzerInjectionHelper::WrapVideoDecoderFactory( std::unique_ptr<VideoDecoderFactory> delegate) const { return absl::make_unique<QualityAnalyzingVideoDecoderFactory>( std::move(delegate), encoding_entities_id_generator_.get(), extractor_, analyzer_.get()); } std::unique_ptr<test::FrameGenerator> VideoQualityAnalyzerInjectionHelper::WrapFrameGenerator( std::string stream_label, std::unique_ptr<test::FrameGenerator> delegate, test::VideoFrameWriter* writer) const { return absl::make_unique<InterceptingFrameGenerator>( std::move(stream_label), std::move(delegate), analyzer_.get(), writer); } std::unique_ptr<rtc::VideoSinkInterface<VideoFrame>> VideoQualityAnalyzerInjectionHelper::CreateVideoSink( test::VideoFrameWriter* writer) const { return absl::make_unique<AnalyzingVideoSink>(analyzer_.get(), writer); } void VideoQualityAnalyzerInjectionHelper::Start(std::string test_case_name, int max_threads_count) { analyzer_->Start(std::move(test_case_name), max_threads_count); } void VideoQualityAnalyzerInjectionHelper::OnStatsReports( const std::string& pc_label, const StatsReports& stats_reports) { analyzer_->OnStatsReports(pc_label, stats_reports); } void VideoQualityAnalyzerInjectionHelper::Stop() { analyzer_->Stop(); } } // namespace webrtc_pc_e2e } // namespace webrtc <commit_msg>Refactor video analyzer injection helper<commit_after>/* * Copyright (c) 2019 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 "test/pc/e2e/analyzer/video/video_quality_analyzer_injection_helper.h" #include <utility> #include "absl/memory/memory.h" #include "test/pc/e2e/analyzer/video/quality_analyzing_video_decoder.h" #include "test/pc/e2e/analyzer/video/quality_analyzing_video_encoder.h" #include "test/pc/e2e/analyzer/video/simulcast_dummy_buffer_helper.h" namespace webrtc { namespace webrtc_pc_e2e { namespace { class VideoFrameInterceptor { public: virtual ~VideoFrameInterceptor() = default; // Performs desired actions with video frame. It may change video frame. virtual void OnVideoFrame(VideoFrame* frame) = 0; }; class VideoAnalyzerCapturingInterceptor : public VideoFrameInterceptor { public: VideoAnalyzerCapturingInterceptor(std::string stream_label, VideoQualityAnalyzerInterface* analyzer) : stream_label_(std::move(stream_label)), analyzer_(analyzer) { RTC_DCHECK(analyzer_); } ~VideoAnalyzerCapturingInterceptor() override = default; void OnVideoFrame(VideoFrame* frame) override { uint16_t frame_id = analyzer_->OnFrameCaptured(stream_label_, *frame); frame->set_id(frame_id); } private: const std::string stream_label_; VideoQualityAnalyzerInterface* analyzer_; }; class VideoWriterInterceptor : public VideoFrameInterceptor { public: VideoWriterInterceptor(test::VideoFrameWriter* video_writer) : video_writer_(video_writer) {} ~VideoWriterInterceptor() override = default; void OnVideoFrame(VideoFrame* frame) override { bool result = video_writer_->WriteFrame(*frame); RTC_CHECK(result) << "Failed to write frame"; } private: test::VideoFrameWriter* video_writer_; }; // Intercepts generated frames and passes them also to video quality analyzer // and into video frame writer, if the last one is provided. class InterceptingFrameGenerator : public test::FrameGenerator { public: InterceptingFrameGenerator( std::unique_ptr<test::FrameGenerator> delegate, std::vector<std::unique_ptr<VideoFrameInterceptor>> interceptors) : delegate_(std::move(delegate)), interceptors_(std::move(interceptors)) {} ~InterceptingFrameGenerator() override = default; VideoFrame* NextFrame() override { VideoFrame* frame = delegate_->NextFrame(); for (auto& interceptor : interceptors_) { interceptor->OnVideoFrame(frame); } return frame; } void ChangeResolution(size_t width, size_t height) override { delegate_->ChangeResolution(width, height); } private: std::unique_ptr<test::FrameGenerator> delegate_; std::vector<std::unique_ptr<VideoFrameInterceptor>> interceptors_; }; // Implements the video sink, that forwards rendered frames to the video quality // analyzer and to the video frame writer, if the last one is provided. class AnalyzingVideoSink : public rtc::VideoSinkInterface<VideoFrame> { public: AnalyzingVideoSink(VideoQualityAnalyzerInterface* analyzer, test::VideoFrameWriter* video_writer) : analyzer_(analyzer), video_writer_(video_writer) { RTC_DCHECK(analyzer_); } ~AnalyzingVideoSink() override = default; void OnFrame(const VideoFrame& frame) override { if (IsDummyFrameBuffer(frame.video_frame_buffer()->ToI420())) { // This is dummy frame, so we don't need to process it further. return; } analyzer_->OnFrameRendered(frame); if (video_writer_) { bool result = video_writer_->WriteFrame(frame); RTC_CHECK(result) << "Failed to write frame"; } } void OnDiscardedFrame() override {} private: VideoQualityAnalyzerInterface* analyzer_; test::VideoFrameWriter* video_writer_; }; } // namespace VideoQualityAnalyzerInjectionHelper::VideoQualityAnalyzerInjectionHelper( std::unique_ptr<VideoQualityAnalyzerInterface> analyzer, EncodedImageDataInjector* injector, EncodedImageDataExtractor* extractor) : analyzer_(std::move(analyzer)), injector_(injector), extractor_(extractor), encoding_entities_id_generator_(absl::make_unique<IntIdGenerator>(1)) { RTC_DCHECK(injector_); RTC_DCHECK(extractor_); } VideoQualityAnalyzerInjectionHelper::~VideoQualityAnalyzerInjectionHelper() = default; std::unique_ptr<VideoEncoderFactory> VideoQualityAnalyzerInjectionHelper::WrapVideoEncoderFactory( std::unique_ptr<VideoEncoderFactory> delegate, double bitrate_multiplier, std::map<std::string, absl::optional<int>> stream_required_spatial_index) const { return absl::make_unique<QualityAnalyzingVideoEncoderFactory>( std::move(delegate), bitrate_multiplier, std::move(stream_required_spatial_index), encoding_entities_id_generator_.get(), injector_, analyzer_.get()); } std::unique_ptr<VideoDecoderFactory> VideoQualityAnalyzerInjectionHelper::WrapVideoDecoderFactory( std::unique_ptr<VideoDecoderFactory> delegate) const { return absl::make_unique<QualityAnalyzingVideoDecoderFactory>( std::move(delegate), encoding_entities_id_generator_.get(), extractor_, analyzer_.get()); } std::unique_ptr<test::FrameGenerator> VideoQualityAnalyzerInjectionHelper::WrapFrameGenerator( std::string stream_label, std::unique_ptr<test::FrameGenerator> delegate, test::VideoFrameWriter* writer) const { std::vector<std::unique_ptr<VideoFrameInterceptor>> interceptors; interceptors.push_back(absl::make_unique<VideoAnalyzerCapturingInterceptor>( std::move(stream_label), analyzer_.get())); if (writer) { interceptors.push_back(absl::make_unique<VideoWriterInterceptor>(writer)); } return absl::make_unique<InterceptingFrameGenerator>(std::move(delegate), std::move(interceptors)); } std::unique_ptr<rtc::VideoSinkInterface<VideoFrame>> VideoQualityAnalyzerInjectionHelper::CreateVideoSink( test::VideoFrameWriter* writer) const { return absl::make_unique<AnalyzingVideoSink>(analyzer_.get(), writer); } void VideoQualityAnalyzerInjectionHelper::Start(std::string test_case_name, int max_threads_count) { analyzer_->Start(std::move(test_case_name), max_threads_count); } void VideoQualityAnalyzerInjectionHelper::OnStatsReports( const std::string& pc_label, const StatsReports& stats_reports) { analyzer_->OnStatsReports(pc_label, stats_reports); } void VideoQualityAnalyzerInjectionHelper::Stop() { analyzer_->Stop(); } } // namespace webrtc_pc_e2e } // namespace webrtc <|endoftext|>
<commit_before>// @(#)root/gui:$Name: $:$Id: TRootContextMenu.cxx,v 1.4 2002/04/04 17:32:14 rdm Exp $ // Author: Fons Rademakers 12/02/98 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TRootContextMenu // // // // This class provides an interface to context sensitive popup menus. // // These menus pop up when the user hits the right mouse button, and // // are destroyed when the menu pops downs. // // The picture below shows a canvas with a pop-up menu. // // // //Begin_Html <img src="gif/hsumMenu.gif"> End_Html // // // // The picture below shows a canvas with a pop-up menu and a dialog box.// // // //Begin_Html <img src="gif/hsumDialog.gif"> End_Html // // // ////////////////////////////////////////////////////////////////////////// #include "TRootContextMenu.h" #include "TROOT.h" #include "TGClient.h" #include "TList.h" #include "TContextMenu.h" #include "TMethod.h" #include "TMethodArg.h" #include "TClass.h" #include "TVirtualX.h" #include "TCanvas.h" #include "TDataMember.h" #include "TToggle.h" #include "TRootDialog.h" #include "TDataType.h" #include "TCanvas.h" #include "TBrowser.h" #include "TRootCanvas.h" #include "TRootBrowser.h" #include "TClassMenuItem.h" enum { kToggleStart = 1000, // first id of toggle menu items kToggleListStart = 2000, // first id of toggle list menu items kUserFunctionStart = 3000 // first id of user added functions/methods, etc... }; ClassImp(TRootContextMenu) //______________________________________________________________________________ TRootContextMenu::TRootContextMenu(TContextMenu *c, const char *) : TGPopupMenu(gClient->GetRoot()), TContextMenuImp(c) { // Create context menu. fDialog = 0; fCleanup = new TList; // Context menu handles its own messages Associate(this); } //______________________________________________________________________________ TRootContextMenu::~TRootContextMenu() { // Delete a context menu. delete fDialog; if (fCleanup) fCleanup->Delete(); delete fCleanup; } //______________________________________________________________________________ void TRootContextMenu::DisplayPopup(Int_t x, Int_t y) { // Display context popup menu for currently selected object. // delete menu items releated to previous object and reset menu size if (fEntryList) fEntryList->Delete(); if (fCleanup) fCleanup->Delete(); fHeight = 6; fWidth = 8; // delete previous dialog if (fDialog) { delete fDialog; fDialog = 0; } // add menu items to popup menu CreateMenu(fContextMenu->GetSelectedObject()); int xx, yy, topx = 0, topy = 0; UInt_t w, h; if (fContextMenu->GetSelectedCanvas()) gVirtualX->GetGeometry(fContextMenu->GetSelectedCanvas()->GetCanvasID(), topx, topy, w, h); xx = topx + x + 1; yy = topy + y + 1; PlaceMenu(xx, yy, kFALSE, kTRUE); } //______________________________________________________________________________ void TRootContextMenu::CreateMenu(TObject *object) { // Create the context menu depending on the selected object. int entry = 0, toggle = kToggleStart, togglelist = kToggleListStart; int userfunction = kUserFunctionStart; // Add a title AddLabel(fContextMenu->CreatePopupTitle(object)); AddSeparator(); // Get list of menu items from the selected object's class TList *menuItemList = object->IsA()->GetMenuList(); TClassMenuItem *menuItem; TIter nextItem(menuItemList); while ((menuItem = (TClassMenuItem*) nextItem())) { switch (menuItem->GetType()) { case TClassMenuItem::kPopupSeparator: AddSeparator(); break; case TClassMenuItem::kPopupStandardList: { // Standard list of class methods. Rebuild from scratch. // Get linked list of objects menu items (i.e. member functions // with the token *MENU in their comment fields. TList *methodList = new TList; object->IsA()->GetMenuItems(methodList); TMethod *method; TClass *classPtr = 0; TIter next(methodList); while ((method = (TMethod*) next())) { if (classPtr != method->GetClass()) { AddSeparator(); classPtr = method->GetClass(); } TDataMember *m; EMenuItemKind menuKind = method->IsMenuItem(); switch (menuKind) { case kMenuDialog: AddEntry(method->GetName(), entry++, method); break; case kMenuSubMenu: if ((m = method->FindDataMember())) { if (m->GetterMethod()) { TGPopupMenu *r = new TGPopupMenu(gClient->GetRoot()); AddPopup(method->GetName(), r); fCleanup->Add(r); TIter nxt(m->GetOptions()); TOptionListItem *it; while ((it = (TOptionListItem*) nxt())) { char *name = it->fOptName; Long_t val = it->fValue; TToggle *t = new TToggle; t->SetToggledObject(object, method); t->SetOnValue(val); fCleanup->Add(t); r->AddSeparator(); r->AddEntry(name, togglelist++, t); if (t->GetState()) r->CheckEntry(togglelist-1); } } else { AddEntry(method->GetName(), entry++, method); } } break; case kMenuToggle: { TToggle *t = new TToggle; t->SetToggledObject(object, method); t->SetOnValue(1); fCleanup->Add(t); AddEntry(method->GetName(), toggle++, t); if (t->GetState()) CheckEntry(toggle-1); } break; default: break; } } delete methodList; } break; case TClassMenuItem::kPopupUserFunction: { if (menuItem->IsToggle()) { if (object) { TMethod* method = object->IsA()->GetMethodWithPrototype(menuItem->GetFunctionName(),menuItem->GetArgs()); TToggle *t = new TToggle; t->SetToggledObject(object, method); t->SetOnValue(1); fCleanup->Add(t); AddEntry(method->GetName(), toggle++, t); if (t->GetState()) CheckEntry(toggle-1); } else { Warning("Dialog","Cannot use toggle for a global function"); } } else { const char* menuItemTitle = menuItem->GetTitle(); if (strlen(menuItemTitle)==0) menuItemTitle = menuItem->GetFunctionName(); AddEntry(menuItemTitle,userfunction++,menuItem); } } break; default: break; } } } //______________________________________________________________________________ void TRootContextMenu::Dialog(TObject *object, TMethod *method) { // Create dialog object with OK and Cancel buttons. This dialog // prompts for the arguments of "method". Dialog(object,(TFunction*)method); } //______________________________________________________________________________ void TRootContextMenu::Dialog(TObject *object, TFunction *function) { // Create dialog object with OK and Cancel buttons. This dialog // prompts for the arguments of "function". // function may be a global function or a method Int_t selfobjpos; if (!function) return; // Position, if it exists, of the argument that correspond to the object itself if (fContextMenu->GetSelectedMenuItem()) selfobjpos = fContextMenu->GetSelectedMenuItem()->GetSelfObjectPos(); else selfobjpos = -1; const TGWindow *w; if (fContextMenu->GetSelectedCanvas()) { TCanvas *c = (TCanvas *) fContextMenu->GetSelectedCanvas(); // Embedded canvas has no canvasimp that is a TGFrame if (c->GetCanvasImp()->IsA()->InheritsFrom(TGFrame::Class())) w = (TRootCanvas *) c->GetCanvasImp(); else w = gClient->GetRoot(); } else if (fContextMenu->GetBrowser()) { TBrowser *b = (TBrowser *) fContextMenu->GetBrowser(); w = (TRootBrowser *) b->GetBrowserImp(); } else w = gClient->GetRoot(); fDialog = new TRootDialog(this, w, fContextMenu->CreateDialogTitle(object, function)); // iterate through all arguments and create apropriate input-data objects: // inputlines, option menus... TMethodArg *argument = 0; TIter next(function->GetListOfMethodArgs()); Int_t argpos = 0; while ((argument = (TMethodArg *) next())) { // Do not input argument for self object if (selfobjpos != argpos) { Text_t *argname = fContextMenu->CreateArgumentTitle(argument); const Text_t *type = argument->GetTypeName(); TDataType *datatype = gROOT->GetType(type); const Text_t *charstar = "char*"; Text_t basictype[32]; if (datatype) { strcpy(basictype, datatype->GetTypeName()); } else { TClass *cl = gROOT->GetClass(type); if (strncmp(type, "enum", 4) && (cl && !(cl->Property() & kIsEnum))) Warning("Dialog", "data type is not basic type, assuming (int)"); strcpy(basictype, "int"); } if (strchr(argname, '*')) { strcat(basictype, "*"); type = charstar; } TDataMember *m = argument->GetDataMember(); if (m && m->GetterMethod(object->IsA())) { // Get the current value and form it as a text: Text_t val[256]; if (!strncmp(basictype, "char*", 5)) { Text_t *tdefval; m->GetterMethod()->Execute(object, "", &tdefval); strncpy(val, tdefval, 255); } else if (!strncmp(basictype, "float", 5) || !strncmp(basictype, "double", 6)) { Double_t ddefval; m->GetterMethod()->Execute(object, "", ddefval); sprintf(val, "%g", ddefval); } else if (!strncmp(basictype, "char", 4) || !strncmp(basictype, "int", 3) || !strncmp(basictype, "long", 4) || !strncmp(basictype, "short", 5)) { Long_t ldefval; m->GetterMethod()->Execute(object, "", ldefval); sprintf(val, "%li", ldefval); } // Find out whether we have options ... TList *opt; if ((opt = m->GetOptions())) { Warning("Dialog", "option menu not yet implemented", opt); #if 0 TMotifOptionMenu *o= new TMotifOptionMenu(argname); TIter nextopt(opt); TOptionListItem *it = 0; while ((it = (TOptionListItem*) nextopt())) { Text_t *name = it->fOptName; Text_t *label = it->fOptLabel; Long_t value = it->fValue; if (value != -9999) { Text_t val[256]; sprintf(val, "%li", value); o->AddItem(name, val); }else o->AddItem(name, label); } o->SetData(val); fDialog->Add(o); #endif } else { // we haven't got options - textfield ... fDialog->Add(argname, val, type); } } else { // if m not found ... char val[256] = ""; const char *tval = argument->GetDefault(); if (tval) strncpy(val, tval, 255); fDialog->Add(argname, val, type); } } argpos++; } fDialog->Popup(); } //______________________________________________________________________________ Bool_t TRootContextMenu::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2) { // Handle context menu messages. switch (GET_MSG(msg)) { case kC_COMMAND: switch (GET_SUBMSG(msg)) { case kCM_MENU: if (parm1 < kToggleStart) { TMethod *m = (TMethod *) parm2; GetContextMenu()->Action(m); } else if (parm1 >= kToggleStart && parm1 < kToggleListStart) { TToggle *t = (TToggle *) parm2; GetContextMenu()->Action(t); } else if (parm1 >= kToggleListStart && parm1<kUserFunctionStart) { TToggle *t = (TToggle *) parm2; if (t->GetState() == 0) t->SetState(1); } else { TClassMenuItem* mi = (TClassMenuItem*)parm2; GetContextMenu()->Action(mi); } break; case kCM_BUTTON: if (parm1 == 1) { const char *args = fDialog->GetParameters(); GetContextMenu()->Execute((char *)args); delete fDialog; fDialog = 0; } if (parm1 == 2) { const char *args = fDialog->GetParameters(); GetContextMenu()->Execute((char *)args); } if (parm1 == 3) { delete fDialog; fDialog = 0; } break; default: break; } break; case kC_TEXTENTRY: switch (GET_SUBMSG(msg)) { case kTE_ENTER: { const char *args = fDialog->GetParameters(); GetContextMenu()->Execute((char *)args); delete fDialog; fDialog = 0; } break; default: break; } break; default: break; } return kTRUE; } <commit_msg>Fix from Bertrand in TRootContextMenu constructor<commit_after>// @(#)root/gui:$Name: $:$Id: TRootContextMenu.cxx,v 1.5 2002/06/09 08:26:15 brun Exp $ // Author: Fons Rademakers 12/02/98 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TRootContextMenu // // // // This class provides an interface to context sensitive popup menus. // // These menus pop up when the user hits the right mouse button, and // // are destroyed when the menu pops downs. // // The picture below shows a canvas with a pop-up menu. // // // //Begin_Html <img src="gif/hsumMenu.gif"> End_Html // // // // The picture below shows a canvas with a pop-up menu and a dialog box.// // // //Begin_Html <img src="gif/hsumDialog.gif"> End_Html // // // ////////////////////////////////////////////////////////////////////////// #include "TRootContextMenu.h" #include "TROOT.h" #include "TGClient.h" #include "TList.h" #include "TContextMenu.h" #include "TMethod.h" #include "TMethodArg.h" #include "TClass.h" #include "TVirtualX.h" #include "TCanvas.h" #include "TDataMember.h" #include "TToggle.h" #include "TRootDialog.h" #include "TDataType.h" #include "TCanvas.h" #include "TBrowser.h" #include "TRootCanvas.h" #include "TRootBrowser.h" #include "TClassMenuItem.h" enum { kToggleStart = 1000, // first id of toggle menu items kToggleListStart = 2000, // first id of toggle list menu items kUserFunctionStart = 3000 // first id of user added functions/methods, etc... }; ClassImp(TRootContextMenu) //______________________________________________________________________________ TRootContextMenu::TRootContextMenu(TContextMenu *c, const char *) : TGPopupMenu(gClient->GetRoot()), TContextMenuImp(c) { // Create context menu. fDialog = 0; fCleanup = new TList; // Context menu handles its own messages Associate(this); } //______________________________________________________________________________ TRootContextMenu::~TRootContextMenu() { // Delete a context menu. delete fDialog; if (fCleanup) fCleanup->Delete(); delete fCleanup; } //______________________________________________________________________________ void TRootContextMenu::DisplayPopup(Int_t x, Int_t y) { // Display context popup menu for currently selected object. // delete menu items releated to previous object and reset menu size if (fEntryList) fEntryList->Delete(); if (fCleanup) fCleanup->Delete(); fMenuHeight = 6; fMenuWidth = 8; // delete previous dialog if (fDialog) { delete fDialog; fDialog = 0; } // add menu items to popup menu CreateMenu(fContextMenu->GetSelectedObject()); int xx, yy, topx = 0, topy = 0; UInt_t w, h; if (fContextMenu->GetSelectedCanvas()) gVirtualX->GetGeometry(fContextMenu->GetSelectedCanvas()->GetCanvasID(), topx, topy, w, h); xx = topx + x + 1; yy = topy + y + 1; PlaceMenu(xx, yy, kFALSE, kTRUE); } //______________________________________________________________________________ void TRootContextMenu::CreateMenu(TObject *object) { // Create the context menu depending on the selected object. int entry = 0, toggle = kToggleStart, togglelist = kToggleListStart; int userfunction = kUserFunctionStart; // Add a title AddLabel(fContextMenu->CreatePopupTitle(object)); AddSeparator(); // Get list of menu items from the selected object's class TList *menuItemList = object->IsA()->GetMenuList(); TClassMenuItem *menuItem; TIter nextItem(menuItemList); while ((menuItem = (TClassMenuItem*) nextItem())) { switch (menuItem->GetType()) { case TClassMenuItem::kPopupSeparator: AddSeparator(); break; case TClassMenuItem::kPopupStandardList: { // Standard list of class methods. Rebuild from scratch. // Get linked list of objects menu items (i.e. member functions // with the token *MENU in their comment fields. TList *methodList = new TList; object->IsA()->GetMenuItems(methodList); TMethod *method; TClass *classPtr = 0; TIter next(methodList); while ((method = (TMethod*) next())) { if (classPtr != method->GetClass()) { AddSeparator(); classPtr = method->GetClass(); } TDataMember *m; EMenuItemKind menuKind = method->IsMenuItem(); switch (menuKind) { case kMenuDialog: AddEntry(method->GetName(), entry++, method); break; case kMenuSubMenu: if ((m = method->FindDataMember())) { if (m->GetterMethod()) { TGPopupMenu *r = new TGPopupMenu(gClient->GetRoot()); AddPopup(method->GetName(), r); fCleanup->Add(r); TIter nxt(m->GetOptions()); TOptionListItem *it; while ((it = (TOptionListItem*) nxt())) { char *name = it->fOptName; Long_t val = it->fValue; TToggle *t = new TToggle; t->SetToggledObject(object, method); t->SetOnValue(val); fCleanup->Add(t); r->AddSeparator(); r->AddEntry(name, togglelist++, t); if (t->GetState()) r->CheckEntry(togglelist-1); } } else { AddEntry(method->GetName(), entry++, method); } } break; case kMenuToggle: { TToggle *t = new TToggle; t->SetToggledObject(object, method); t->SetOnValue(1); fCleanup->Add(t); AddEntry(method->GetName(), toggle++, t); if (t->GetState()) CheckEntry(toggle-1); } break; default: break; } } delete methodList; } break; case TClassMenuItem::kPopupUserFunction: { if (menuItem->IsToggle()) { if (object) { TMethod* method = object->IsA()->GetMethodWithPrototype(menuItem->GetFunctionName(),menuItem->GetArgs()); TToggle *t = new TToggle; t->SetToggledObject(object, method); t->SetOnValue(1); fCleanup->Add(t); AddEntry(method->GetName(), toggle++, t); if (t->GetState()) CheckEntry(toggle-1); } else { Warning("Dialog","Cannot use toggle for a global function"); } } else { const char* menuItemTitle = menuItem->GetTitle(); if (strlen(menuItemTitle)==0) menuItemTitle = menuItem->GetFunctionName(); AddEntry(menuItemTitle,userfunction++,menuItem); } } break; default: break; } } } //______________________________________________________________________________ void TRootContextMenu::Dialog(TObject *object, TMethod *method) { // Create dialog object with OK and Cancel buttons. This dialog // prompts for the arguments of "method". Dialog(object,(TFunction*)method); } //______________________________________________________________________________ void TRootContextMenu::Dialog(TObject *object, TFunction *function) { // Create dialog object with OK and Cancel buttons. This dialog // prompts for the arguments of "function". // function may be a global function or a method Int_t selfobjpos; if (!function) return; // Position, if it exists, of the argument that correspond to the object itself if (fContextMenu->GetSelectedMenuItem()) selfobjpos = fContextMenu->GetSelectedMenuItem()->GetSelfObjectPos(); else selfobjpos = -1; const TGWindow *w; if (fContextMenu->GetSelectedCanvas()) { TCanvas *c = (TCanvas *) fContextMenu->GetSelectedCanvas(); // Embedded canvas has no canvasimp that is a TGFrame if (c->GetCanvasImp()->IsA()->InheritsFrom(TGFrame::Class())) w = (TRootCanvas *) c->GetCanvasImp(); else w = gClient->GetRoot(); } else if (fContextMenu->GetBrowser()) { TBrowser *b = (TBrowser *) fContextMenu->GetBrowser(); w = (TRootBrowser *) b->GetBrowserImp(); } else w = gClient->GetRoot(); fDialog = new TRootDialog(this, w, fContextMenu->CreateDialogTitle(object, function)); // iterate through all arguments and create apropriate input-data objects: // inputlines, option menus... TMethodArg *argument = 0; TIter next(function->GetListOfMethodArgs()); Int_t argpos = 0; while ((argument = (TMethodArg *) next())) { // Do not input argument for self object if (selfobjpos != argpos) { Text_t *argname = fContextMenu->CreateArgumentTitle(argument); const Text_t *type = argument->GetTypeName(); TDataType *datatype = gROOT->GetType(type); const Text_t *charstar = "char*"; Text_t basictype[32]; if (datatype) { strcpy(basictype, datatype->GetTypeName()); } else { TClass *cl = gROOT->GetClass(type); if (strncmp(type, "enum", 4) && (cl && !(cl->Property() & kIsEnum))) Warning("Dialog", "data type is not basic type, assuming (int)"); strcpy(basictype, "int"); } if (strchr(argname, '*')) { strcat(basictype, "*"); type = charstar; } TDataMember *m = argument->GetDataMember(); if (m && m->GetterMethod(object->IsA())) { // Get the current value and form it as a text: Text_t val[256]; if (!strncmp(basictype, "char*", 5)) { Text_t *tdefval; m->GetterMethod()->Execute(object, "", &tdefval); strncpy(val, tdefval, 255); } else if (!strncmp(basictype, "float", 5) || !strncmp(basictype, "double", 6)) { Double_t ddefval; m->GetterMethod()->Execute(object, "", ddefval); sprintf(val, "%g", ddefval); } else if (!strncmp(basictype, "char", 4) || !strncmp(basictype, "int", 3) || !strncmp(basictype, "long", 4) || !strncmp(basictype, "short", 5)) { Long_t ldefval; m->GetterMethod()->Execute(object, "", ldefval); sprintf(val, "%li", ldefval); } // Find out whether we have options ... TList *opt; if ((opt = m->GetOptions())) { Warning("Dialog", "option menu not yet implemented", opt); #if 0 TMotifOptionMenu *o= new TMotifOptionMenu(argname); TIter nextopt(opt); TOptionListItem *it = 0; while ((it = (TOptionListItem*) nextopt())) { Text_t *name = it->fOptName; Text_t *label = it->fOptLabel; Long_t value = it->fValue; if (value != -9999) { Text_t val[256]; sprintf(val, "%li", value); o->AddItem(name, val); }else o->AddItem(name, label); } o->SetData(val); fDialog->Add(o); #endif } else { // we haven't got options - textfield ... fDialog->Add(argname, val, type); } } else { // if m not found ... char val[256] = ""; const char *tval = argument->GetDefault(); if (tval) strncpy(val, tval, 255); fDialog->Add(argname, val, type); } } argpos++; } fDialog->Popup(); } //______________________________________________________________________________ Bool_t TRootContextMenu::ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2) { // Handle context menu messages. switch (GET_MSG(msg)) { case kC_COMMAND: switch (GET_SUBMSG(msg)) { case kCM_MENU: if (parm1 < kToggleStart) { TMethod *m = (TMethod *) parm2; GetContextMenu()->Action(m); } else if (parm1 >= kToggleStart && parm1 < kToggleListStart) { TToggle *t = (TToggle *) parm2; GetContextMenu()->Action(t); } else if (parm1 >= kToggleListStart && parm1<kUserFunctionStart) { TToggle *t = (TToggle *) parm2; if (t->GetState() == 0) t->SetState(1); } else { TClassMenuItem* mi = (TClassMenuItem*)parm2; GetContextMenu()->Action(mi); } break; case kCM_BUTTON: if (parm1 == 1) { const char *args = fDialog->GetParameters(); GetContextMenu()->Execute((char *)args); delete fDialog; fDialog = 0; } if (parm1 == 2) { const char *args = fDialog->GetParameters(); GetContextMenu()->Execute((char *)args); } if (parm1 == 3) { delete fDialog; fDialog = 0; } break; default: break; } break; case kC_TEXTENTRY: switch (GET_SUBMSG(msg)) { case kTE_ENTER: { const char *args = fDialog->GetParameters(); GetContextMenu()->Execute((char *)args); delete fDialog; fDialog = 0; } break; default: break; } break; default: break; } return kTRUE; } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkPyCommand.h" namespace itk { PyCommand::PyCommand() { this->m_Object = nullptr; } PyCommand::~PyCommand() { if (this->m_Object) { Py_DECREF(this->m_Object); } this->m_Object = nullptr; } void PyCommand::SetCommandCallable(PyObject *o) { if (o != this->m_Object) { if (this->m_Object) { // get rid of our reference Py_DECREF(this->m_Object); } // store the new object this->m_Object = o; if (this->m_Object) { // take out reference (so that the calling code doesn't // have to keep a binding to the callable around) Py_INCREF(this->m_Object); } } } PyObject * PyCommand::GetCommandCallable() { return this->m_Object; } void PyCommand::Execute(Object *, const EventObject&) { this->PyExecute(); } void PyCommand::Execute(const Object*, const EventObject&) { this->PyExecute(); } void PyCommand::PyExecute() { // make sure that the CommandCallable is in fact callable if (!PyCallable_Check(this->m_Object)) { // we throw a standard ITK exception: this makes it possible for // our standard Swig exception handling logic to take this // through to the invoking Python process itkExceptionMacro(<<"CommandCallable is not a callable Python object, " <<"or it has not been set."); } else { PyObject *result = PyEval_CallObject(this->m_Object, (PyObject *)nullptr); if (result) { Py_DECREF(result); } else { // there was a Python error. Clear the error by printing to stdout PyErr_Print(); // make sure the invoking Python code knows there was a problem // by raising an exception itkExceptionMacro(<<"There was an error executing the " <<"CommandCallable."); } } } } // namespace itk <commit_msg>STYLE: Apply ITK Style Guidelines to itkPyCommand.cxx<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 "itkPyCommand.h" namespace itk { PyCommand::PyCommand() { this->m_Object = nullptr; } PyCommand::~PyCommand() { if (this->m_Object) { Py_DECREF(this->m_Object); } this->m_Object = nullptr; } void PyCommand::SetCommandCallable(PyObject *o) { if (o != this->m_Object) { if (this->m_Object) { // get rid of our reference Py_DECREF(this->m_Object); } // store the new object this->m_Object = o; if (this->m_Object) { // take out reference (so that the calling code doesn't // have to keep a binding to the callable around) Py_INCREF(this->m_Object); } } } PyObject * PyCommand::GetCommandCallable() { return this->m_Object; } void PyCommand::Execute(Object *, const EventObject&) { this->PyExecute(); } void PyCommand::Execute(const Object*, const EventObject&) { this->PyExecute(); } void PyCommand::PyExecute() { // make sure that the CommandCallable is in fact callable if (!PyCallable_Check(this->m_Object)) { // we throw a standard ITK exception: this makes it possible for // our standard Swig exception handling logic to take this // through to the invoking Python process itkExceptionMacro(<<"CommandCallable is not a callable Python object, " <<"or it has not been set."); } else { PyObject *result = PyEval_CallObject(this->m_Object, (PyObject *)nullptr); if (result) { Py_DECREF(result); } else { // there was a Python error. Clear the error by printing to stdout PyErr_Print(); // make sure the invoking Python code knows there was a problem // by raising an exception itkExceptionMacro(<<"There was an error executing the " <<"CommandCallable."); } } } } // end namespace itk <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.3 2000/02/06 07:47:30 rahulj * Year 2K copyright swat. * * Revision 1.2 2000/02/04 01:49:28 aruna1 * TreeWalker and NodeIterator changes * * Revision 1.1.1.1 1999/11/09 01:09:01 twl * Initial checkin * * Revision 1.3 1999/11/08 20:44:20 rahul * Swat for adding in Product name and CVS comment log variable. * */ #ifndef DOM_NodeIterator_HEADER_GUARD_ #define DOM_NodeIterator_HEADER_GUARD_ #include "DOM_NodeFilter.hpp" #include "DOM_Node.hpp" class NodeIteratorImpl; class CDOM_EXPORT DOM_NodeIterator { public: // Constants for whatToShow... DOM_NodeIterator (); DOM_NodeIterator (NodeIteratorImpl* impl); DOM_NodeIterator(const DOM_NodeIterator &other); DOM_NodeIterator & operator = (const DOM_NodeIterator &other); DOM_NodeIterator & operator = (const DOM_NullPtr *val); ~DOM_NodeIterator(); bool operator == (const DOM_NodeIterator & other)const; bool operator == (const DOM_NullPtr *other) const; bool operator != (const DOM_NodeIterator & other) const; bool operator != (const DOM_NullPtr * other) const; unsigned long getWhatToShow(); DOM_NodeFilter* getFilter(); DOM_Node nextNode(); DOM_Node previousNode(); void detach(); /** Get the expandEntity reference flag. */ bool getExpandEntityReferences(); private: NodeIteratorImpl* fImpl; }; #endif <commit_msg>Added API docs<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * $Log$ * Revision 1.4 2000/02/10 23:38:05 abagchi * Added API docs * * Revision 1.3 2000/02/06 07:47:30 rahulj * Year 2K copyright swat. * * Revision 1.2 2000/02/04 01:49:28 aruna1 * TreeWalker and NodeIterator changes * * Revision 1.3 1999/11/08 20:44:20 rahul * Swat for adding in Product name and CVS comment log variable. * * Revision 1.1.1.1 1999/11/09 01:09:01 twl * Initial checkin * */ #ifndef DOM_NodeIterator_HEADER_GUARD_ #define DOM_NodeIterator_HEADER_GUARD_ #include "DOM_NodeFilter.hpp" #include "DOM_Node.hpp" class NodeIteratorImpl; /** * NodeIterators are used to step through a set of nodes, e.g. the set of nodes in a * NodeList, the document subtree governed by a particular node, the results of a * query, or any other set of nodes. The set of nodes to be iterated is determined by * the implementation of the NodeIterator. DOM Level 2 specifies a single * NodeIterator implementation for document-order traversal of a document subtree. * Instances of these iterators are created by calling * <code>DocumentTraversal.createNodeIterator()</code>. */ class CDOM_EXPORT DOM_NodeIterator { public: /** @name Constructors */ //@{ /** * Default constructor */ DOM_NodeIterator (); /** * Copy constructor * @param other The object to be copied */ DOM_NodeIterator(const DOM_NodeIterator &other); //@} /** @name Assignment operators */ /** * Assignment operator * @param other The object to be copied through assignment */ DOM_NodeIterator & operator = (const DOM_NodeIterator &other); /** * Assignment operator * * This overloaded variant is provided for * the sole purpose of setting a DOM_Node reference variable to * zero. Nulling out a reference variable in this way will decrement * the reference count on the underlying Node object that the variable * formerly referenced. This effect is normally obtained when reference * variable goes out of scope, but zeroing them can be useful for * global instances, or for local instances that will remain in scope * for an extended time, when the storage belonging to the underlying * node needs to be reclaimed. * @param val Only a value of 0, or null, is allowed. */ DOM_NodeIterator & operator = (const DOM_NullPtr *val); //@} /** @name Destructor */ /** * Destructor */ //@{ ~DOM_NodeIterator(); //@} /** @name Equality operators */ //@{ /** * Test whether this NodeIterator reference refers to the same underlying * node iterator as the other reference object. This does not * compare the contents of two different objects. * * @param other The value to be compared * @return Returns true if the underlying node iterator is same */ bool operator == (const DOM_NodeIterator & other)const; /** * Use this comparison operator to test whether a Node Iterator reference * is null. * * @param other The value to be compared, which must be 0 or null. * @return Returns true if the node iterator is null */ bool operator == (const DOM_NullPtr *other) const; //@} /** @name Inequality operators */ //@{ /** * Test whether this NodeIterator reference refers to the same underlying * node iterator as the other reference object. This does not * compare the contents of two different objects. * * @param other The value to be compared * @return Returns true if the underlying node iterator is different */ bool operator != (const DOM_NodeIterator & other) const; /** * Use this comparison operator to test whether a Node Iterator reference * is null. * * @param other The value to be compared, which must be 0 or null. * @return Returns true if the node iterator is NOT null */ bool operator != (const DOM_NullPtr * other) const; //@} /** @name Get Functions */ //@{ /** * Returns the value of <code>whatToShow</code> * This attribute determines which node types are presented via the * iterator. The available set of constants is defined in the Filters * interface. */ unsigned long getWhatToShow(); /** * Get the <code>expandEntity</code> reference flag. * The value of this flag determines whether the children of entity * reference nodes are visible to the iterator. If false, they will be skipped * over. * * To produce a view of the document that has entity references * expanded and does not expose the entity reference node itself, use * the <code>whatToShow</code> flags to hide the entity reference node and set * <code>expandEntityReferences</code> to true when creating the iterator. To * produce a view of the document that has entity reference nodes but * no entity expansion, use the <code>whatToShow</code> flags to show the entity * reference node and set <code>expandEntityReferences</code> to false. */ bool getExpandEntityReferences(); /** * Get the filter used to screen nodes. */ DOM_NodeFilter* getFilter(); //@} /** @name Iterator Methods */ //@{ /** * Returns the next node in the set and advances the position of the * iterator in the set. After a NodeIterator is created, the first call to * <code>nextNode()</code> returns the first node in the set. * @return Returns the next node in the set */ DOM_Node nextNode(); /** * Returns the previous node in the set and moves the position of the * iterator backwards in the set. * @return Returns the previous node in the set */ DOM_Node previousNode(); /** * Detaches the iterator from the set which it iterated over, releasing any * computational resources and placing the iterator in the INVALID state. * After detach has been invoked, calls to nextNode or previousNode * will raise the exception <code>INVALID_STATE_ERR</code>. */ void detach(); //@} private: NodeIteratorImpl* fImpl; protected: DOM_NodeIterator (NodeIteratorImpl* impl); }; #endif <|endoftext|>
<commit_before>#include <windows.h> #include <tchar.h> #include <time.h> HWND hMainWnd = NULL; HANDLE hMutex = NULL; HANDLE hSemaphore = NULL; HANDLE phThreads[2] = { 0 }; BOOL bStopTherads = FALSE; int arrQueue[65536] = { 0 }; int nQueueSize = 0; TCHAR szText[256] = { 0 }; // // Helper's functions // void AddQueueItem(int iNumber) { WaitForSingleObject(hMutex, INFINITE); arrQueue[nQueueSize++] = iNumber; ReleaseMutex(hMutex); ReleaseSemaphore(hSemaphore, 1, NULL); } BOOL GetQueueItem(int* pNumber, DWORD dwMilliseconds) { DWORD dwResult = WaitForSingleObject(hSemaphore, dwMilliseconds); if (dwResult == WAIT_OBJECT_0) { WaitForSingleObject(hMutex, INFINITE); *pNumber = arrQueue[0]; for (int i = 1; i < nQueueSize; ++i) arrQueue[i - 1] = arrQueue[i]; nQueueSize--; ReleaseMutex(hMutex); return TRUE; } return FALSE; } // // Thread procedures // DWORD WINAPI GenThreadProc(LPVOID lpParameter) { while (!bStopTherads) { AddQueueItem(rand() % 100); Sleep(250 + rand() % 500); } return 0; } DWORD WINAPI ReadThreadProc(LPVOID lpParameter) { while (!bStopTherads) { int iNumber = 0; if (GetQueueItem(&iNumber, 500)) { _stprintf_s(szText, TEXT("Number: %i, Count: %i"), iNumber, nQueueSize); InvalidateRect(hMainWnd, 0, TRUE); Sleep(500); } else { _stprintf_s(szText, TEXT("Number is not Exists")); InvalidateRect(hMainWnd, 0, TRUE); } } return 0; } // // WindowProc - procedure for main window // LRESULT CALLBACK WindowProc(HWND hWnd, UINT uiMsg, WPARAM wParam, LPARAM lParam) { switch (uiMsg) { case WM_CREATE: hMutex = CreateMutex(NULL, FALSE, NULL); hSemaphore = CreateSemaphore(0, 0, LONG_MAX, 0); CreateThread(NULL, 0, GenThreadProc, NULL, 0, NULL); CreateThread(NULL, 0, ReadThreadProc, NULL, 0, NULL); break; case WM_DESTROY: bStopTherads = TRUE; WaitForMultipleObjects(2, phThreads, TRUE, INFINITE); CloseHandle(hSemaphore); CloseHandle(hMutex); PostQuitMessage(0); break; case WM_PAINT: { RECT rc = { 0 }; GetClientRect(hWnd, &rc); PAINTSTRUCT ps = { 0 }; HDC hdc = BeginPaint(hWnd, &ps); DrawText(hdc, szText, -1, &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE); EndPaint(hWnd, &ps); return 0; } // WM_PAINT } return DefWindowProc(hWnd, uiMsg, wParam, lParam); } // // WinMain - entry point // int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow) { srand((unsigned int)time(0)); WNDCLASSEX wcx = { 0 }; wcx.cbSize = sizeof(WNDCLASSEX); wcx.style = CS_HREDRAW | CS_VREDRAW; wcx.lpfnWndProc = WindowProc; wcx.hInstance = hInstance; wcx.hIcon = LoadIcon(NULL, IDI_INFORMATION); wcx.hCursor = LoadCursor(NULL, IDC_ARROW); wcx.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcx.lpszClassName = TEXT("SomeClassName"); if (RegisterClassEx(&wcx) == 0) return 1; hMainWnd = CreateWindowEx(0, TEXT("SomeClassName"), TEXT("ProgWin: Threads testing"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, 0); if (NULL == hMainWnd) return 2; ShowWindow(hMainWnd, nCmdShow); UpdateWindow(hMainWnd); MSG msg = { 0 }; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; }<commit_msg>semaphore bugfix<commit_after>#include <windows.h> #include <tchar.h> #include <time.h> HWND hMainWnd = NULL; HANDLE hMutex = NULL; HANDLE hSemaphore = NULL; HANDLE phThreads[2] = { 0 }; BOOL bStopTherads = FALSE; int arrQueue[65536] = { 0 }; int nQueueSize = 0; TCHAR szText[256] = { 0 }; // // Helper's functions // void AddQueueItem(int iNumber) { WaitForSingleObject(hMutex, INFINITE); arrQueue[nQueueSize++] = iNumber; ReleaseMutex(hMutex); ReleaseSemaphore(hSemaphore, 1, NULL); } BOOL GetQueueItem(int* pNumber, DWORD dwMilliseconds) { DWORD dwResult = WaitForSingleObject(hSemaphore, dwMilliseconds); if (dwResult == WAIT_OBJECT_0) { WaitForSingleObject(hMutex, INFINITE); *pNumber = arrQueue[0]; for (int i = 1; i < nQueueSize; ++i) arrQueue[i - 1] = arrQueue[i]; nQueueSize--; ReleaseMutex(hMutex); return TRUE; } return FALSE; } // // Thread procedures // DWORD WINAPI GenThreadProc(LPVOID lpParameter) { while (!bStopTherads) { AddQueueItem(rand() % 100); Sleep(250 + rand() % 500); } return 0; } DWORD WINAPI ReadThreadProc(LPVOID lpParameter) { while (!bStopTherads) { int iNumber = 0; if (GetQueueItem(&iNumber, 500)) { _stprintf_s(szText, TEXT("Number: %i, Count: %i"), iNumber, nQueueSize); InvalidateRect(hMainWnd, 0, TRUE); Sleep(500); } else { _stprintf_s(szText, TEXT("Number is not Exists")); InvalidateRect(hMainWnd, 0, TRUE); } } return 0; } // // WindowProc - procedure for main window // LRESULT CALLBACK WindowProc(HWND hWnd, UINT uiMsg, WPARAM wParam, LPARAM lParam) { switch (uiMsg) { case WM_CREATE: hMutex = CreateMutex(NULL, FALSE, NULL); hSemaphore = CreateSemaphore(0, 0, LONG_MAX, 0); phThreads[0] = CreateThread(NULL, 0, GenThreadProc, NULL, 0, NULL); phThreads[1] = CreateThread(NULL, 0, ReadThreadProc, NULL, 0, NULL); break; case WM_DESTROY: bStopTherads = TRUE; WaitForMultipleObjects(2, phThreads, TRUE, INFINITE); CloseHandle(hSemaphore); CloseHandle(hMutex); PostQuitMessage(0); break; case WM_PAINT: { RECT rc = { 0 }; GetClientRect(hWnd, &rc); PAINTSTRUCT ps = { 0 }; HDC hdc = BeginPaint(hWnd, &ps); DrawText(hdc, szText, -1, &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE); EndPaint(hWnd, &ps); return 0; } // WM_PAINT } return DefWindowProc(hWnd, uiMsg, wParam, lParam); } // // WinMain - entry point // int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow) { srand((unsigned int)time(0)); WNDCLASSEX wcx = { 0 }; wcx.cbSize = sizeof(WNDCLASSEX); wcx.style = CS_HREDRAW | CS_VREDRAW; wcx.lpfnWndProc = WindowProc; wcx.hInstance = hInstance; wcx.hIcon = LoadIcon(NULL, IDI_INFORMATION); wcx.hCursor = LoadCursor(NULL, IDC_ARROW); wcx.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcx.lpszClassName = TEXT("SomeClassName"); if (RegisterClassEx(&wcx) == 0) return 1; hMainWnd = CreateWindowEx(0, TEXT("SomeClassName"), TEXT("ProgWin: Threads testing"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, 0); if (NULL == hMainWnd) return 2; ShowWindow(hMainWnd, nCmdShow); UpdateWindow(hMainWnd); MSG msg = { 0 }; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return 0; }<|endoftext|>
<commit_before>//---------------------------------------------------------------------------// //! //! \file Utility_TetrahedronHelpers.cpp //! \author Alex Robinson, Eli Moll //! \brief Tetrahedron helper functions //! //---------------------------------------------------------------------------// // Std Lib Includes #include <math.h> // Trilinos Includes #include <Teuchos_ScalarTraits.hpp> // FRENSIE Includes #include "Utility_TetrahedronHelpers.hpp" #include "Utility_ContractException.hpp" #include <moab/Matrix3.hpp> namespace Utility{ // Calculate the volume of a tetrahedron double calculateTetrahedronVolume( const double vertex_a[3], const double vertex_b[3], const double vertex_c[3], const double vertex_d[3] ) { double a1 = vertex_a[0] - vertex_d[0]; double a2 = vertex_a[1] - vertex_d[1]; double a3 = vertex_a[2] - vertex_d[2]; double b1 = vertex_b[0] - vertex_d[0]; double b2 = vertex_b[1] - vertex_d[1]; double b3 = vertex_b[2] - vertex_d[2]; double c1 = vertex_c[0] - vertex_d[0]; double c2 = vertex_c[1] - vertex_d[1]; double c3 = vertex_c[2] - vertex_d[2]; double volume = fabs( a1*(b2*c3-b3*c2) + a2*(b3*c1-b1*c3) + a3*(b1*c2-b2*c1) )/6.0; testPostcondition( !Teuchos::ScalarTraits<double>::isnaninf( volume ) ); testPostcondition( volume > 0.0 ); return volume; } // Calculate the Barycentric Transform Matrix double* calculateBarycentricTransformMatrix( const double vertex_a[3], const double vertex_b[3], const double vertex_c[3], const double vertex_d[3] ) { double t1 = 1.0;//vertex_a[0] - vertex_d[0]; double t2 = 1.0;//vertex_b[0] - vertex_d[0]; double t3 = 1.0;//vertex_c[0] - vertex_d[0]; double t4 = 1.0;//vertex_a[1] - vertex_d[1]; double t5 = 1.0;//vertex_b[1] - vertex_d[1]; double t6 = 1.0;//vertex_c[1] - vertex_d[1]; double t7 = 1.0;//vertex_a[2] - vertex_d[2]; double t8 = 1.0;//vertex_b[2] - vertex_d[2]; double t9 = 1.0;//vertex_c[2] - vertex_d[2]; //double t[9] = { t1, t2, t3, t4, t5, t6, t7, t8, t9 }; moab::Matrix3 T( t1, t2, t3, t4, t5, t6, t7, t8, t9 ); const double* tarray = T.array(); return tarray; } } // end Utility namespace //---------------------------------------------------------------------------// // end Utility_TetrahedronHelpers.cpp //---------------------------------------------------------------------------// <commit_msg>Matrix3 still returning zeros<commit_after>//---------------------------------------------------------------------------// //! //! \file Utility_TetrahedronHelpers.cpp //! \author Alex Robinson, Eli Moll //! \brief Tetrahedron helper functions //! //---------------------------------------------------------------------------// // Std Lib Includes #include <math.h> // Trilinos Includes #include <Teuchos_ScalarTraits.hpp> // FRENSIE Includes #include "Utility_TetrahedronHelpers.hpp" #include "Utility_ContractException.hpp" #include <moab/Matrix3.hpp> namespace Utility{ // Calculate the volume of a tetrahedron double calculateTetrahedronVolume( const double vertex_a[3], const double vertex_b[3], const double vertex_c[3], const double vertex_d[3] ) { double a1 = vertex_a[0] - vertex_d[0]; double a2 = vertex_a[1] - vertex_d[1]; double a3 = vertex_a[2] - vertex_d[2]; double b1 = vertex_b[0] - vertex_d[0]; double b2 = vertex_b[1] - vertex_d[1]; double b3 = vertex_b[2] - vertex_d[2]; double c1 = vertex_c[0] - vertex_d[0]; double c2 = vertex_c[1] - vertex_d[1]; double c3 = vertex_c[2] - vertex_d[2]; double volume = fabs( a1*(b2*c3-b3*c2) + a2*(b3*c1-b1*c3) + a3*(b1*c2-b2*c1) )/6.0; testPostcondition( !Teuchos::ScalarTraits<double>::isnaninf( volume ) ); testPostcondition( volume > 0.0 ); return volume; } // Calculate the Barycentric Transform Matrix double* calculateBarycentricTransformMatrix( const double vertex_a[3], const double vertex_b[3], const double vertex_c[3], const double vertex_d[3] ) { double t1 = 1.0;//vertex_a[0] - vertex_d[0]; double t2 = 1.0;//vertex_b[0] - vertex_d[0]; double t3 = 1.0;//vertex_c[0] - vertex_d[0]; double t4 = 1.0;//vertex_a[1] - vertex_d[1]; double t5 = 1.0;//vertex_b[1] - vertex_d[1]; double t6 = 1.0;//vertex_c[1] - vertex_d[1]; double t7 = 1.0;//vertex_a[2] - vertex_d[2]; double t8 = 1.0;//vertex_b[2] - vertex_d[2]; double t9 = 1.0;//vertex_c[2] - vertex_d[2]; //double t[9] = { t1, t2, t3, t4, t5, t6, t7, t8, t9 }; moab::Matrix3 T( t1, t2, t3, t4, t5, t6, t7, t8, t9 ); double* tarray = T.array(); return tarray; } } // end Utility namespace //---------------------------------------------------------------------------// // end Utility_TetrahedronHelpers.cpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>// -*- mode: c++; coding: utf-8 -*- #pragma once #include <sstream> #include <boost/program_options.hpp> inline std::string flags_into_string( const boost::program_options::options_description& desc, const boost::program_options::variables_map& vm) { std::ostringstream oss; oss.precision(16); for (const auto shared_ptr_opt: desc.options()) { std::string long_name(shared_ptr_opt.get()->long_name()); boost::any value(vm[long_name].value()); if (!vm.count(long_name)) {continue;} if (value.type() == typeid(std::string) && boost::any_cast<std::string>(value).empty()) { oss << '#'; } oss << long_name << " = "; if (value.type() == typeid(int)) { oss << boost::any_cast<int>(value); } else if (value.type() == typeid(unsigned int)) { oss << boost::any_cast<unsigned int>(value); } else if (value.type() == typeid(size_t)) { oss << boost::any_cast<size_t>(value); } else if (value.type() == typeid(double)) { oss << boost::any_cast<double>(value); } else if (value.type() == typeid(bool)) { oss << boost::any_cast<bool>(value); } else if (value.type() == typeid(std::string)) { oss << boost::any_cast<std::string>(value); } else { oss << boost::any_cast<unsigned long>(value); } oss << '\n'; } return oss.str(); } <commit_msg>Put flags_into_string() into namespace wtl<commit_after>// -*- mode: c++; coding: utf-8 -*- #pragma once #include <sstream> #include <boost/program_options.hpp> /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// namespace wtl { /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// inline std::string flags_into_string( const boost::program_options::options_description& desc, const boost::program_options::variables_map& vm) { std::ostringstream oss; oss.precision(16); for (const auto shared_ptr_opt: desc.options()) { std::string long_name(shared_ptr_opt.get()->long_name()); boost::any value(vm[long_name].value()); if (!vm.count(long_name)) {continue;} if (value.type() == typeid(std::string) && boost::any_cast<std::string>(value).empty()) { oss << '#'; } oss << long_name << " = "; if (value.type() == typeid(int)) { oss << boost::any_cast<int>(value); } else if (value.type() == typeid(unsigned int)) { oss << boost::any_cast<unsigned int>(value); } else if (value.type() == typeid(size_t)) { oss << boost::any_cast<size_t>(value); } else if (value.type() == typeid(double)) { oss << boost::any_cast<double>(value); } else if (value.type() == typeid(bool)) { oss << boost::any_cast<bool>(value); } else if (value.type() == typeid(std::string)) { oss << boost::any_cast<std::string>(value); } else { oss << boost::any_cast<unsigned long>(value); } oss << '\n'; } return oss.str(); } /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// } // namespace wtl /////////1/////////2/////////3/////////4/////////5/////////6/////////7///////// <|endoftext|>
<commit_before>#pragma once #include "system/Config.hpp" #include "Common.hpp" #include <thread> /** \brief Performs system basic operations such as directory creation, timing, threading, file picking. \ingroup System */ class System { public: /** The file picker mode. */ enum class Picker { Load, ///< Load an existing file. Directory, ///< open or create a directory. Save ///< Save to a new or existing file. }; /** Present a filesystem document picker to the user, using native controls. \param mode the type of item to ask to the user (load, save, directory) \param startDir the initial directory when the picker is opened \param outPath the path to the item selected by the user \param extensions (optional) the extensions allowed, separated by "," or ";" \return true if the user picked an item, false if cancelled. */ static bool showPicker(Picker mode, const std::string & startDir, std::string & outPath, const std::string & extensions = ""); /** Create a directory. \param directory the path to the directory to create \return true if the creation is successful. \note If the directory already exists, it will fail. \warning This function will not create intermediate directories. */ static bool createDirectory(const std::string & directory); /** Notify the user by sending a 'Bell' signal. */ static void ping(); /** Return the current value of a time counter. \return the current counter value, in seconds. */ static double time(); /** Obtain a YYYY_MM_DD_HH_MM_SS timestamp of the current time. \return the string representation */ static std::string timestamp(); /** Multi-threaded for-loop. \param low lower (included) bound \param high higher (excluded) bound \param func the function to execute at each iteration, will receive the index of the element as a unique argument. Signature: void func(size_t i) \note For now only an increment by one is supported. */ template<typename ThreadFunc> static void forParallel(size_t low, size_t high, ThreadFunc func) { // Make sure the loop is increasing. if(high < low) { const size_t temp = low; low = high; high = temp; } // Prepare the threads pool. const size_t count = size_t(std::max(std::thread::hardware_concurrency(), unsigned(1))); std::vector<std::thread> threads; threads.reserve(count); // Compute the span of each thread. size_t span = size_t(std::round((float(high) - float(low)) / float(count))); span = std::max(size_t(1), span); // Helper to execute the function passed on a subset of the total interval. auto launchThread = [&func](size_t a, size_t b) { for(size_t i = a; i < b; ++i) { func(i); } }; for(size_t tid = 0; tid < count; ++tid) { // For each thread, call the same lambda with different bounds as arguments. const size_t threadLow = tid * span; size_t threadHigh = (tid == count - 1) ? high : ((tid + 1) * span); threads.emplace_back(launchThread, threadLow, threadHigh); } // Wait for all threads to finish. std::for_each(threads.begin(), threads.end(), [](std::thread & x) { x.join(); }); } #ifdef _WIN32 /** Convert a string to the system representation. \param str a UTF8 standard string \return the corresponding system string */ static WCHAR * widen(const std::string & str); /** Convert a string from the system representation. \param str a system string \return the corresponding UTF8 standard string */ static std::string narrow(WCHAR * str); #else /** Convert a string to the system representation. \param str a UTF8 standard string \return the corresponding system string */ static const char * widen(const std::string & str); /** Convert a string from the system representation. \param str a system string \return the corresponding UTF8 standard string */ static std::string narrow(char * str); #endif }; <commit_msg>System: fix thread count computation.<commit_after>#pragma once #include "system/Config.hpp" #include "Common.hpp" #include <thread> /** \brief Performs system basic operations such as directory creation, timing, threading, file picking. \ingroup System */ class System { public: /** The file picker mode. */ enum class Picker { Load, ///< Load an existing file. Directory, ///< open or create a directory. Save ///< Save to a new or existing file. }; /** Present a filesystem document picker to the user, using native controls. \param mode the type of item to ask to the user (load, save, directory) \param startDir the initial directory when the picker is opened \param outPath the path to the item selected by the user \param extensions (optional) the extensions allowed, separated by "," or ";" \return true if the user picked an item, false if cancelled. */ static bool showPicker(Picker mode, const std::string & startDir, std::string & outPath, const std::string & extensions = ""); /** Create a directory. \param directory the path to the directory to create \return true if the creation is successful. \note If the directory already exists, it will fail. \warning This function will not create intermediate directories. */ static bool createDirectory(const std::string & directory); /** Notify the user by sending a 'Bell' signal. */ static void ping(); /** Return the current value of a time counter. \return the current counter value, in seconds. */ static double time(); /** Obtain a YYYY_MM_DD_HH_MM_SS timestamp of the current time. \return the string representation */ static std::string timestamp(); /** Multi-threaded for-loop. \param low lower (included) bound \param high higher (excluded) bound \param func the function to execute at each iteration, will receive the index of the element as a unique argument. Signature: void func(size_t i) \note For now only an increment by one is supported. */ template<typename ThreadFunc> static void forParallel(size_t low, size_t high, ThreadFunc func) { // Make sure the loop is increasing. if(high < low) { const size_t temp = low; low = high; high = temp; } // Prepare the threads pool. // Always leave one thread free. const size_t count = size_t(std::max(int(std::thread::hardware_concurrency())-1, 1)); std::vector<std::thread> threads; threads.reserve(count); // Compute the span of each thread. const size_t span = std::max(size_t(1), (high - low) / count); // Helper to execute the function passed on a subset of the total interval. auto launchThread = [&func](size_t a, size_t b) { for(size_t i = a; i < b; ++i) { func(i); } }; for(size_t tid = 0; tid < count; ++tid) { // For each thread, call the same lambda with different bounds as arguments. const size_t threadLow = tid * span; const size_t threadHigh = tid == (count-1) ? high : ((tid + 1) * span); threads.emplace_back(launchThread, threadLow, threadHigh); } // Wait for all threads to finish. std::for_each(threads.begin(), threads.end(), [](std::thread & x) { x.join(); }); } #ifdef _WIN32 /** Convert a string to the system representation. \param str a UTF8 standard string \return the corresponding system string */ static WCHAR * widen(const std::string & str); /** Convert a string from the system representation. \param str a system string \return the corresponding UTF8 standard string */ static std::string narrow(WCHAR * str); #else /** Convert a string to the system representation. \param str a UTF8 standard string \return the corresponding system string */ static const char * widen(const std::string & str); /** Convert a string from the system representation. \param str a system string \return the corresponding UTF8 standard string */ static std::string narrow(char * str); #endif }; <|endoftext|>
<commit_before>/* * NiceConnection.cpp * * Created on: Mar 8, 2012 * Author: pedro */ #include <glib.h> #include <nice/nice.h> #include "NiceConnection.h" #include "WebRtcConnection.h" #include "SdpInfo.h" namespace erizo { guint stream_id; GSList* lcands; int streamsGathered; int rec, sen; int length; int components = 2; uint32_t ssrc = 55543; boost::mutex writeMutex, gatherMutex, stateMutex, selectedMutex; void cb_nice_recv(NiceAgent* agent, guint stream_id, guint component_id, guint len, gchar* buf, gpointer user_data) { boost::mutex::scoped_lock lock(writeMutex); // printf( "cb_nice_recv len %u id %u\n",len, stream_id ); NiceConnection* nicecon = (NiceConnection*) user_data; nicecon->getWebRtcConnection()->receiveNiceData((char*) buf, (int) len, (NiceConnection*) user_data); } void cb_candidate_gathering_done(NiceAgent *agent, guint stream_id, gpointer user_data) { boost::mutex::scoped_lock lock(gatherMutex); NiceConnection *conn = (NiceConnection*) user_data; //printf("ConnState %u\n",conn->state); // ... Wait until the signal candidate-gathering-done is fired ... int currentCompId = 1; lcands = nice_agent_get_local_candidates(agent, stream_id, currentCompId++); NiceCandidate *cand; GSList* iterator; // printf("gathering done %u\n",stream_id); //printf("Candidates---------------------------------------------------->\n"); while (lcands != NULL) { for (iterator = lcands; iterator; iterator = iterator->next) { char address[100]; cand = (NiceCandidate*) iterator->data; nice_address_to_string(&cand->addr, address); // printf("foundation %s\n", cand->foundation); // printf("compid %u\n", cand->component_id); // printf("stream_id %u\n", cand->stream_id); // printf("priority %u\n", cand->priority); // printf("username %s\n", cand->username); // printf("password %s\n", cand->password); CandidateInfo cand_info; cand_info.componentId = cand->component_id; cand_info.foundation = cand->foundation; cand_info.priority = cand->priority; cand_info.hostAddress = std::string(address); cand_info.hostPort = nice_address_get_port(&cand->addr); cand_info.mediaType = conn->mediaType; /* * NICE_CANDIDATE_TYPE_HOST, * NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE, * NICE_CANDIDATE_TYPE_PEER_REFLEXIVE, * NICE_CANDIDATE_TYPE_RELAYED, */ switch (cand->type) { case NICE_CANDIDATE_TYPE_HOST: cand_info.hostType = HOST; break; case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE: cand_info.hostType = SRLFX; break; case NICE_CANDIDATE_TYPE_PEER_REFLEXIVE: cand_info.hostType = PRFLX; break; case NICE_CANDIDATE_TYPE_RELAYED: printf("WARNING TURN NOT IMPLEMENTED YET\n"); cand_info.hostType = RELAY; break; default: break; } cand_info.netProtocol = "udp"; cand_info.transProtocol = std::string(*conn->transportName); //cand_info.username = std::string(cand->username); if (cand->username) cand_info.username = std::string(cand->username); else cand_info.username = std::string("(null)"); if (cand->password) cand_info.password = std::string(cand->password); else cand_info.password = std::string("(null)"); conn->localCandidates->push_back(cand_info); } lcands = nice_agent_get_local_candidates(agent, stream_id, currentCompId++); } printf("candidate_gathering done, size %u\n", conn->localCandidates->size()); conn->iceState = NiceConnection::CANDIDATES_GATHERED; } void cb_component_state_changed(void) { boost::mutex::scoped_lock lock(stateMutex); printf("cb_component_state_changed\n"); } void cb_new_selected_pair(NiceAgent *agent, guint stream_id, guint component_id, gchar *lfoundation, gchar *rfoundation, gpointer user_data) { printf( "cb_new_selected_pair for stream %u, comp %u, lfound %s, rfound %s OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO\n", stream_id, component_id, lfoundation, rfoundation); boost::mutex::scoped_lock lock(selectedMutex); NiceConnection *conn = (NiceConnection*) user_data; conn->iceState = NiceConnection::READY; printf( "cb_new_selected_pair for stream %u, comp %u, lfound %s, rfound %s OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO\n", stream_id, component_id, lfoundation, rfoundation); } NiceConnection::NiceConnection(MediaType med, const std::string &transport_name) { agent_ = NULL; loop_ = NULL; mediaType = med; localCandidates = new std::vector<CandidateInfo>(); transportName = new std::string(transport_name); } NiceConnection::~NiceConnection() { if (iceState != FINISHED) this->close(); if (agent_) g_object_unref(agent_); if (localCandidates) delete localCandidates; if (transportName) delete transportName; } void NiceConnection::join() { m_Thread_.join(); } void NiceConnection::start() { m_Thread_ = boost::thread(&NiceConnection::init, this); } void NiceConnection::close() { if (agent_ != NULL) nice_agent_remove_stream(agent_, 1); if (loop_ != NULL) g_main_loop_quit(loop_); iceState = FINISHED; } int NiceConnection::sendData(void *buf, int len) { int val = -1; if (iceState == READY) { val = nice_agent_send(agent_, 1, 1, len, (char*) buf); } return val; } WebRtcConnection* NiceConnection::getWebRtcConnection() { return conn_; } void NiceConnection::init() { streamsGathered = 0; iceState = INITIAL; g_type_init(); g_thread_init(NULL); loop_ = g_main_loop_new(NULL, FALSE); // nice_debug_enable( TRUE ); // Create a nice agent agent_ = nice_agent_new(g_main_loop_get_context(loop_), NICE_COMPATIBILITY_GOOGLE); NiceAddress* naddr = nice_address_new(); nice_address_set_from_string(naddr, "138.4.4.141"); nice_agent_add_local_address(agent_, naddr); GValue val = { 0 }, val2 = { 0 }; g_value_init(&val, G_TYPE_STRING); g_value_set_string(&val, "173.194.70.126"); g_object_set_property(G_OBJECT( agent_ ), "stun-server", &val); g_value_init(&val2, G_TYPE_UINT); g_value_set_uint(&val2, 19302); g_object_set_property(G_OBJECT( agent_ ), "stun-server-port", &val2); // Connect the signals g_signal_connect( G_OBJECT( agent_ ), "candidate-gathering-done", G_CALLBACK( cb_candidate_gathering_done ), this); g_signal_connect( G_OBJECT( agent_ ), "component-state-changed", G_CALLBACK( cb_component_state_changed ), NULL); g_signal_connect( G_OBJECT( agent_ ), "new-selected-pair", G_CALLBACK( cb_new_selected_pair ), this); // Create a new stream and start gathering candidates int res = nice_agent_add_stream(agent_, 1); // Set Port Range ----> If this doesn't work when linking the file libnice.sym has to be modified to include this call // nice_agent_set_port_range(agent_, (guint)1, (guint)1, (guint)51000, (guint)52000); nice_agent_gather_candidates(agent_, 1); nice_agent_attach_recv(agent_, 1, 1, g_main_loop_get_context(loop_), cb_nice_recv, this); // Attach to the component to receive the data g_main_loop_run(loop_); } bool NiceConnection::setRemoteCandidates( std::vector<CandidateInfo> &candidates) { GSList* candList = NULL; for (unsigned int it = 0; it < candidates.size(); it++) { NiceCandidateType nice_cand_type; CandidateInfo cinfo = candidates[it]; if (cinfo.mediaType != this->mediaType || this->transportName->compare(cinfo.transProtocol)) continue; switch (cinfo.hostType) { case HOST: nice_cand_type = NICE_CANDIDATE_TYPE_HOST; break; case SRLFX: nice_cand_type = NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE; break; case PRFLX: nice_cand_type = NICE_CANDIDATE_TYPE_PEER_REFLEXIVE; break; case RELAY: nice_cand_type = NICE_CANDIDATE_TYPE_RELAYED; break; default: nice_cand_type = NICE_CANDIDATE_TYPE_HOST; break; } NiceCandidate* thecandidate = nice_candidate_new(nice_cand_type); NiceAddress* naddr = nice_address_new(); nice_address_set_from_string(naddr, cinfo.hostAddress.c_str()); nice_address_set_port(naddr, cinfo.hostPort); thecandidate->addr = *naddr; char* uname = (char*) malloc(cinfo.username.size()); char* pass = (char*) malloc(cinfo.password.size()); sprintf(thecandidate->foundation, "%s", cinfo.foundation.c_str()); sprintf(uname, "%s", cinfo.username.c_str()); sprintf(pass, "%s", cinfo.password.c_str()); thecandidate->username = uname; thecandidate->password = pass; thecandidate->stream_id = (guint) 1; thecandidate->component_id = cinfo.componentId; thecandidate->priority = cinfo.priority; thecandidate->transport = NICE_CANDIDATE_TRANSPORT_UDP; candList = g_slist_append(candList, thecandidate); } nice_agent_set_remote_candidates(agent_, (guint) 1, 1, candList); printf("Candidates SET \n"); iceState = CANDIDATES_RECEIVED; return true; } void NiceConnection::setWebRtcConnection(WebRtcConnection* connection) { this->conn_ = connection; } } /* namespace erizo */ <commit_msg>Fixed, ipv6 candidates are not included anymore due to problems with webRTC implementation<commit_after>/* * NiceConnection.cpp * * Created on: Mar 8, 2012 * Author: pedro */ #include <glib.h> #include <nice/nice.h> #include "NiceConnection.h" #include "WebRtcConnection.h" #include "SdpInfo.h" namespace erizo { guint stream_id; GSList* lcands; int streamsGathered; int rec, sen; int length; int components = 2; uint32_t ssrc = 55543; boost::mutex writeMutex, gatherMutex, stateMutex, selectedMutex; void cb_nice_recv(NiceAgent* agent, guint stream_id, guint component_id, guint len, gchar* buf, gpointer user_data) { boost::mutex::scoped_lock lock(writeMutex); // printf( "cb_nice_recv len %u id %u\n",len, stream_id ); NiceConnection* nicecon = (NiceConnection*) user_data; nicecon->getWebRtcConnection()->receiveNiceData((char*) buf, (int) len, (NiceConnection*) user_data); } void cb_candidate_gathering_done(NiceAgent *agent, guint stream_id, gpointer user_data) { boost::mutex::scoped_lock lock(gatherMutex); NiceConnection *conn = (NiceConnection*) user_data; //printf("ConnState %u\n",conn->state); // ... Wait until the signal candidate-gathering-done is fired ... int currentCompId = 1; lcands = nice_agent_get_local_candidates(agent, stream_id, currentCompId++); NiceCandidate *cand; GSList* iterator; // printf("gathering done %u\n",stream_id); //printf("Candidates---------------------------------------------------->\n"); while (lcands != NULL) { for (iterator = lcands; iterator; iterator = iterator->next) { char address[40]; cand = (NiceCandidate*) iterator->data; nice_address_to_string(&cand->addr, address); if (strstr(address, ":")!=NULL){ printf("Ignoring IPV6 candidate\n"); continue; } // printf("foundation %s\n", cand->foundation); // printf("compid %u\n", cand->component_id); // printf("stream_id %u\n", cand->stream_id); // printf("priority %u\n", cand->priority); // printf("username %s\n", cand->username); // printf("password %s\n", cand->password); CandidateInfo cand_info; cand_info.componentId = cand->component_id; cand_info.foundation = cand->foundation; cand_info.priority = cand->priority; cand_info.hostAddress = std::string(address); cand_info.hostPort = nice_address_get_port(&cand->addr); cand_info.mediaType = conn->mediaType; /* * NICE_CANDIDATE_TYPE_HOST, * NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE, * NICE_CANDIDATE_TYPE_PEER_REFLEXIVE, * NICE_CANDIDATE_TYPE_RELAYED, */ switch (cand->type) { case NICE_CANDIDATE_TYPE_HOST: cand_info.hostType = HOST; break; case NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE: cand_info.hostType = SRLFX; break; case NICE_CANDIDATE_TYPE_PEER_REFLEXIVE: cand_info.hostType = PRFLX; break; case NICE_CANDIDATE_TYPE_RELAYED: printf("WARNING TURN NOT IMPLEMENTED YET\n"); cand_info.hostType = RELAY; break; default: break; } cand_info.netProtocol = "udp"; cand_info.transProtocol = std::string(*conn->transportName); //cand_info.username = std::string(cand->username); if (cand->username) cand_info.username = std::string(cand->username); else cand_info.username = std::string("(null)"); if (cand->password) cand_info.password = std::string(cand->password); else cand_info.password = std::string("(null)"); conn->localCandidates->push_back(cand_info); } lcands = nice_agent_get_local_candidates(agent, stream_id, currentCompId++); } printf("candidate_gathering done, size %u\n", conn->localCandidates->size()); conn->iceState = NiceConnection::CANDIDATES_GATHERED; } void cb_component_state_changed(void) { boost::mutex::scoped_lock lock(stateMutex); printf("cb_component_state_changed\n"); } void cb_new_selected_pair(NiceAgent *agent, guint stream_id, guint component_id, gchar *lfoundation, gchar *rfoundation, gpointer user_data) { printf( "cb_new_selected_pair for stream %u, comp %u, lfound %s, rfound %s OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO\n", stream_id, component_id, lfoundation, rfoundation); boost::mutex::scoped_lock lock(selectedMutex); NiceConnection *conn = (NiceConnection*) user_data; conn->iceState = NiceConnection::READY; printf( "cb_new_selected_pair for stream %u, comp %u, lfound %s, rfound %s OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO\n", stream_id, component_id, lfoundation, rfoundation); } NiceConnection::NiceConnection(MediaType med, const std::string &transport_name) { agent_ = NULL; loop_ = NULL; mediaType = med; localCandidates = new std::vector<CandidateInfo>(); transportName = new std::string(transport_name); } NiceConnection::~NiceConnection() { if (iceState != FINISHED) this->close(); if (agent_) g_object_unref(agent_); if (localCandidates) delete localCandidates; if (transportName) delete transportName; } void NiceConnection::join() { m_Thread_.join(); } void NiceConnection::start() { m_Thread_ = boost::thread(&NiceConnection::init, this); } void NiceConnection::close() { if (agent_ != NULL) nice_agent_remove_stream(agent_, 1); if (loop_ != NULL) g_main_loop_quit(loop_); iceState = FINISHED; } int NiceConnection::sendData(void *buf, int len) { int val = -1; if (iceState == READY) { val = nice_agent_send(agent_, 1, 1, len, (char*) buf); } return val; } WebRtcConnection* NiceConnection::getWebRtcConnection() { return conn_; } void NiceConnection::init() { streamsGathered = 0; iceState = INITIAL; g_type_init(); g_thread_init(NULL); loop_ = g_main_loop_new(NULL, FALSE); // nice_debug_enable( TRUE ); // Create a nice agent agent_ = nice_agent_new(g_main_loop_get_context(loop_), NICE_COMPATIBILITY_GOOGLE); // NiceAddress* naddr = nice_address_new(); // nice_address_set_from_string(naddr, "138.4.4.141"); // nice_agent_add_local_address(agent_, naddr); GValue val = { 0 }, val2 = { 0 }; g_value_init(&val, G_TYPE_STRING); g_value_set_string(&val, "173.194.70.126"); g_object_set_property(G_OBJECT( agent_ ), "stun-server", &val); g_value_init(&val2, G_TYPE_UINT); g_value_set_uint(&val2, 19302); g_object_set_property(G_OBJECT( agent_ ), "stun-server-port", &val2); // Connect the signals g_signal_connect( G_OBJECT( agent_ ), "candidate-gathering-done", G_CALLBACK( cb_candidate_gathering_done ), this); g_signal_connect( G_OBJECT( agent_ ), "component-state-changed", G_CALLBACK( cb_component_state_changed ), NULL); g_signal_connect( G_OBJECT( agent_ ), "new-selected-pair", G_CALLBACK( cb_new_selected_pair ), this); // Create a new stream and start gathering candidates int res = nice_agent_add_stream(agent_, 1); // Set Port Range ----> If this doesn't work when linking the file libnice.sym has to be modified to include this call // nice_agent_set_port_range(agent_, (guint)1, (guint)1, (guint)51000, (guint)52000); nice_agent_gather_candidates(agent_, 1); nice_agent_attach_recv(agent_, 1, 1, g_main_loop_get_context(loop_), cb_nice_recv, this); // Attach to the component to receive the data g_main_loop_run(loop_); } bool NiceConnection::setRemoteCandidates( std::vector<CandidateInfo> &candidates) { GSList* candList = NULL; for (unsigned int it = 0; it < candidates.size(); it++) { NiceCandidateType nice_cand_type; CandidateInfo cinfo = candidates[it]; if (cinfo.mediaType != this->mediaType || this->transportName->compare(cinfo.transProtocol)) continue; switch (cinfo.hostType) { case HOST: nice_cand_type = NICE_CANDIDATE_TYPE_HOST; break; case SRLFX: nice_cand_type = NICE_CANDIDATE_TYPE_SERVER_REFLEXIVE; break; case PRFLX: nice_cand_type = NICE_CANDIDATE_TYPE_PEER_REFLEXIVE; break; case RELAY: nice_cand_type = NICE_CANDIDATE_TYPE_RELAYED; break; default: nice_cand_type = NICE_CANDIDATE_TYPE_HOST; break; } NiceCandidate* thecandidate = nice_candidate_new(nice_cand_type); NiceAddress* naddr = nice_address_new(); nice_address_set_from_string(naddr, cinfo.hostAddress.c_str()); nice_address_set_port(naddr, cinfo.hostPort); thecandidate->addr = *naddr; char* uname = (char*) malloc(cinfo.username.size()); char* pass = (char*) malloc(cinfo.password.size()); sprintf(thecandidate->foundation, "%s", cinfo.foundation.c_str()); sprintf(uname, "%s", cinfo.username.c_str()); sprintf(pass, "%s", cinfo.password.c_str()); thecandidate->username = uname; thecandidate->password = pass; thecandidate->stream_id = (guint) 1; thecandidate->component_id = cinfo.componentId; thecandidate->priority = cinfo.priority; thecandidate->transport = NICE_CANDIDATE_TRANSPORT_UDP; candList = g_slist_append(candList, thecandidate); } nice_agent_set_remote_candidates(agent_, (guint) 1, 1, candList); printf("Candidates SET \n"); iceState = CANDIDATES_RECEIVED; return true; } void NiceConnection::setWebRtcConnection(WebRtcConnection* connection) { this->conn_ = connection; } } /* namespace erizo */ <|endoftext|>
<commit_before> /* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <boost/bind.hpp> #include "libtorrent/invariant_check.hpp" #include "libtorrent/connection_queue.hpp" namespace libtorrent { connection_queue::connection_queue(io_service& ios): m_next_ticket(0) , m_num_connecting(0) , m_half_open_limit(0) , m_timer(ios) #ifndef NDEBUG , m_in_timeout_function(false) #endif {} bool connection_queue::free_slots() const { return m_num_connecting < m_half_open_limit || m_half_open_limit <= 0; } void connection_queue::enqueue(boost::function<void(int)> const& on_connect , boost::function<void()> const& on_timeout , time_duration timeout) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; m_queue.push_back(entry()); entry& e = m_queue.back(); e.on_connect = on_connect; e.on_timeout = on_timeout; e.ticket = m_next_ticket; e.timeout = timeout; ++m_next_ticket; try_connect(); } void connection_queue::done(int ticket) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; std::list<entry>::iterator i = std::find_if(m_queue.begin() , m_queue.end(), boost::bind(&entry::ticket, _1) == ticket); if (i == m_queue.end()) { // this might not be here in case on_timeout calls remove return; } if (i->connecting) --m_num_connecting; m_queue.erase(i); try_connect(); } void connection_queue::limit(int limit) { m_half_open_limit = limit; } int connection_queue::limit() const { return m_half_open_limit; } #ifndef NDEBUG void connection_queue::check_invariant() const { int num_connecting = 0; for (std::list<entry>::const_iterator i = m_queue.begin(); i != m_queue.end(); ++i) { if (i->connecting) ++num_connecting; } assert(num_connecting == m_num_connecting); } #endif void connection_queue::try_connect() { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; if (!free_slots() || m_queue.empty()) return; std::list<entry>::iterator i = std::find_if(m_queue.begin() , m_queue.end(), boost::bind(&entry::connecting, _1) == false); while (i != m_queue.end()) { assert(i->connecting == false); ptime expire = time_now() + i->timeout; if (m_num_connecting == 0) { m_timer.expires_at(expire); m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1)); } i->connecting = true; ++m_num_connecting; i->expires = expire; INVARIANT_CHECK; entry& ent = *i; ++i; try { ent.on_connect(ent.ticket); } catch (std::exception&) {} if (!free_slots()) break; i = std::find_if(i, m_queue.end(), boost::bind(&entry::connecting, _1) == false); } } #ifndef NDEBUG struct function_guard { function_guard(bool& v): val(v) { assert(!val); val = true; } ~function_guard() { val = false; } bool& val; }; #endif void connection_queue::on_timeout(asio::error_code const& e) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; #ifndef NDEBUG function_guard guard_(m_in_timeout_function); #endif assert(!e || e == asio::error::operation_aborted); if (e) return; ptime next_expire = max_time(); ptime now = time_now(); for (std::list<entry>::iterator i = m_queue.begin(); !m_queue.empty() && i != m_queue.end();) { if (i->connecting && i->expires < now) { boost::function<void()> on_timeout = i->on_timeout; m_queue.erase(i++); --m_num_connecting; try { on_timeout(); } catch (std::exception&) {} continue; } if (i->expires < next_expire) next_expire = i->expires; ++i; } if (next_expire < max_time()) { m_timer.expires_at(next_expire); m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1)); } try_connect(); } } <commit_msg>fixed potential dead-lock in connection queue<commit_after> /* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <boost/bind.hpp> #include "libtorrent/invariant_check.hpp" #include "libtorrent/connection_queue.hpp" namespace libtorrent { connection_queue::connection_queue(io_service& ios): m_next_ticket(0) , m_num_connecting(0) , m_half_open_limit(0) , m_timer(ios) #ifndef NDEBUG , m_in_timeout_function(false) #endif {} bool connection_queue::free_slots() const { return m_num_connecting < m_half_open_limit || m_half_open_limit <= 0; } void connection_queue::enqueue(boost::function<void(int)> const& on_connect , boost::function<void()> const& on_timeout , time_duration timeout) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; m_queue.push_back(entry()); entry& e = m_queue.back(); e.on_connect = on_connect; e.on_timeout = on_timeout; e.ticket = m_next_ticket; e.timeout = timeout; ++m_next_ticket; try_connect(); } void connection_queue::done(int ticket) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; std::list<entry>::iterator i = std::find_if(m_queue.begin() , m_queue.end(), boost::bind(&entry::ticket, _1) == ticket); if (i == m_queue.end()) { // this might not be here in case on_timeout calls remove return; } if (i->connecting) --m_num_connecting; m_queue.erase(i); try_connect(); } void connection_queue::limit(int limit) { m_half_open_limit = limit; } int connection_queue::limit() const { return m_half_open_limit; } #ifndef NDEBUG void connection_queue::check_invariant() const { int num_connecting = 0; for (std::list<entry>::const_iterator i = m_queue.begin(); i != m_queue.end(); ++i) { if (i->connecting) ++num_connecting; } assert(num_connecting == m_num_connecting); } #endif void connection_queue::try_connect() { INVARIANT_CHECK; if (!free_slots() || m_queue.empty()) return; std::list<entry>::iterator i = std::find_if(m_queue.begin() , m_queue.end(), boost::bind(&entry::connecting, _1) == false); while (i != m_queue.end()) { assert(i->connecting == false); ptime expire = time_now() + i->timeout; if (m_num_connecting == 0) { m_timer.expires_at(expire); m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1)); } i->connecting = true; ++m_num_connecting; i->expires = expire; INVARIANT_CHECK; entry& ent = *i; ++i; try { ent.on_connect(ent.ticket); } catch (std::exception&) {} if (!free_slots()) break; i = std::find_if(i, m_queue.end(), boost::bind(&entry::connecting, _1) == false); } } #ifndef NDEBUG struct function_guard { function_guard(bool& v): val(v) { assert(!val); val = true; } ~function_guard() { val = false; } bool& val; }; #endif void connection_queue::on_timeout(asio::error_code const& e) { mutex_t::scoped_lock l(m_mutex); INVARIANT_CHECK; #ifndef NDEBUG function_guard guard_(m_in_timeout_function); #endif assert(!e || e == asio::error::operation_aborted); if (e) return; ptime next_expire = max_time(); ptime now = time_now(); std::list<entry> timed_out; for (std::list<entry>::iterator i = m_queue.begin(); !m_queue.empty() && i != m_queue.end();) { if (i->connecting && i->expires < now) { std::list<entry>::iterator j = i; ++i; timed_out.splice(timed_out.end(), m_queue, j, i); --m_num_connecting; continue; } if (i->expires < next_expire) next_expire = i->expires; ++i; } // we don't want to call the timeout callback while we're locked // since that is a recepie for dead-locks l.unlock(); for (std::list<entry>::iterator i = timed_out.begin() , end(timed_out.end()); i != end; ++i) { try { i->on_timeout(); } catch (std::exception&) {} } l.lock(); if (next_expire < max_time()) { m_timer.expires_at(next_expire); m_timer.async_wait(boost::bind(&connection_queue::on_timeout, this, _1)); } try_connect(); } } <|endoftext|>
<commit_before>//===--- AndroidTidyModule.cpp - clang-tidy--------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "../ClangTidy.h" #include "../ClangTidyModule.h" #include "../ClangTidyModuleRegistry.h" #include "CloexecAccept4Check.h" #include "CloexecAcceptCheck.h" #include "CloexecCreatCheck.h" #include "CloexecEpollCreate1Check.h" #include "CloexecEpollCreateCheck.h" #include "CloexecDupCheck.h" #include "CloexecFopenCheck.h" #include "CloexecInotifyInit1Check.h" #include "CloexecInotifyInitCheck.h" #include "CloexecMemfdCreateCheck.h" #include "CloexecOpenCheck.h" #include "CloexecSocketCheck.h" using namespace clang::ast_matchers; namespace clang { namespace tidy { namespace android { /// This module is for Android specific checks. class AndroidModule : public ClangTidyModule { public: void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { CheckFactories.registerCheck<CloexecAccept4Check>("android-cloexec-accept4"); CheckFactories.registerCheck<CloexecAcceptCheck>("android-cloexec-accept"); CheckFactories.registerCheck<CloexecCreatCheck>("android-cloexec-creat"); CheckFactories.registerCheck<CloexecEpollCreate1Check>( "android-cloexec-epoll-create1"); CheckFactories.registerCheck<CloexecEpollCreateCheck>( "android-cloexec-epoll-create"); CheckFactories.registerCheck<CloexecDupCheck>("android-cloexec-dup"); CheckFactories.registerCheck<CloexecFopenCheck>("android-cloexec-fopen"); CheckFactories.registerCheck<CloexecInotifyInitCheck>( "android-cloexec-inotify-init"); CheckFactories.registerCheck<CloexecInotifyInit1Check>( "android-cloexec-inotify-init1"); CheckFactories.registerCheck<CloexecMemfdCreateCheck>( "android-cloexec-memfd-create"); CheckFactories.registerCheck<CloexecOpenCheck>("android-cloexec-open"); CheckFactories.registerCheck<CloexecSocketCheck>("android-cloexec-socket"); } }; // Register the AndroidTidyModule using this statically initialized variable. static ClangTidyModuleRegistry::Add<AndroidModule> X("android-module", "Adds Android platform checks."); } // namespace android // This anchor is used to force the linker to link in the generated object file // and thus register the AndroidModule. volatile int AndroidModuleAnchorSource = 0; } // namespace tidy } // namespace clang <commit_msg>[clang-tidy] Sort includes; NFC<commit_after>//===--- AndroidTidyModule.cpp - clang-tidy--------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "../ClangTidy.h" #include "../ClangTidyModule.h" #include "../ClangTidyModuleRegistry.h" #include "CloexecAccept4Check.h" #include "CloexecAcceptCheck.h" #include "CloexecCreatCheck.h" #include "CloexecDupCheck.h" #include "CloexecEpollCreate1Check.h" #include "CloexecEpollCreateCheck.h" #include "CloexecFopenCheck.h" #include "CloexecInotifyInit1Check.h" #include "CloexecInotifyInitCheck.h" #include "CloexecMemfdCreateCheck.h" #include "CloexecOpenCheck.h" #include "CloexecSocketCheck.h" using namespace clang::ast_matchers; namespace clang { namespace tidy { namespace android { /// This module is for Android specific checks. class AndroidModule : public ClangTidyModule { public: void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { CheckFactories.registerCheck<CloexecAccept4Check>("android-cloexec-accept4"); CheckFactories.registerCheck<CloexecAcceptCheck>("android-cloexec-accept"); CheckFactories.registerCheck<CloexecCreatCheck>("android-cloexec-creat"); CheckFactories.registerCheck<CloexecEpollCreate1Check>( "android-cloexec-epoll-create1"); CheckFactories.registerCheck<CloexecEpollCreateCheck>( "android-cloexec-epoll-create"); CheckFactories.registerCheck<CloexecDupCheck>("android-cloexec-dup"); CheckFactories.registerCheck<CloexecFopenCheck>("android-cloexec-fopen"); CheckFactories.registerCheck<CloexecInotifyInitCheck>( "android-cloexec-inotify-init"); CheckFactories.registerCheck<CloexecInotifyInit1Check>( "android-cloexec-inotify-init1"); CheckFactories.registerCheck<CloexecMemfdCreateCheck>( "android-cloexec-memfd-create"); CheckFactories.registerCheck<CloexecOpenCheck>("android-cloexec-open"); CheckFactories.registerCheck<CloexecSocketCheck>("android-cloexec-socket"); } }; // Register the AndroidTidyModule using this statically initialized variable. static ClangTidyModuleRegistry::Add<AndroidModule> X("android-module", "Adds Android platform checks."); } // namespace android // This anchor is used to force the linker to link in the generated object file // and thus register the AndroidModule. volatile int AndroidModuleAnchorSource = 0; } // namespace tidy } // namespace clang <|endoftext|>
<commit_before>/* * Copyright 2019 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/private/SkMacros.h" #include "src/core/SkArenaAlloc.h" #include "src/core/SkColorSpacePriv.h" #include "src/core/SkColorSpaceXformSteps.h" #include "src/core/SkCoreBlitters.h" #include "src/core/SkLRUCache.h" #include "src/core/SkVM.h" namespace { enum class Coverage { Full, UniformA8, MaskA8, MaskLCD16, Mask3D }; SK_BEGIN_REQUIRE_DENSE; struct Key { SkColorType colorType; SkAlphaType alphaType; Coverage coverage; SkBlendMode blendMode; SkShader* shader; SkColorFilter* colorFilter; Key withCoverage(Coverage c) const { Key k = *this; k.coverage = c; return k; } }; SK_END_REQUIRE_DENSE; static bool operator==(const Key& x, const Key& y) { return x.colorType == y.colorType && x.alphaType == y.alphaType && x.coverage == y.coverage && x.blendMode == y.blendMode && x.shader == y.shader && x.colorFilter == y.colorFilter; } static SkLRUCache<Key, skvm::Program>* try_acquire_program_cache() { #if defined(SK_BUILD_FOR_IOS) && defined(__arm) // Some troublemaker build configurations (so far {Flutter,G3}/iOS/armv7) don't // support thread_local. We could use an SkSpinlock and tryAcquire()/release(), or... return nullptr; // ... we could just not cache programs on those platforms. #else thread_local static auto* cache = new SkLRUCache<Key, skvm::Program>{8}; return cache; #endif } static void release_program_cache() { } struct Uniforms { uint32_t paint_color; uint8_t coverage; // Used when Coverage::UniformA8. }; struct Builder : public skvm::Builder { //using namespace skvm; struct Color { skvm::I32 r,g,b,a; }; skvm::I32 inv(skvm::I32 x) { return sub(splat(255), x); } // TODO: provide this in skvm::Builder, with a custom NEON impl. skvm::I32 div255(skvm::I32 v) { // This should be a bit-perfect version of (v+127)/255, // implemented as (v + ((v+128)>>8) + 128)>>8. skvm::I32 v128 = add(v, splat(128)); return shr(add(v128, shr(v128, 8)), 8); } skvm::I32 mix(skvm::I32 x, skvm::I32 y, skvm::I32 t) { return div255(add(mul(x, inv(t)), mul(y, t ))); } Color unpack_8888(skvm::I32 rgba) { return { extract(rgba, 0, splat(0xff)), extract(rgba, 8, splat(0xff)), extract(rgba, 16, splat(0xff)), extract(rgba, 24, splat(0xff)), }; } skvm::I32 pack_8888(Color c) { return pack(pack(c.r, c.g, 8), pack(c.b, c.a, 8), 16); } Color unpack_565(skvm::I32 bgr) { // N.B. kRGB_565_SkColorType is named confusingly; // blue is in the low bits and red the high. skvm::I32 r = extract(bgr, 11, splat(0b011'111)), g = extract(bgr, 5, splat(0b111'111)), b = extract(bgr, 0, splat(0b011'111)); return { // Scale 565 up to 888. bit_or(shl(r, 3), shr(r, 2)), bit_or(shl(g, 2), shr(g, 4)), bit_or(shl(b, 3), shr(b, 2)), splat(0xff), }; } skvm::I32 pack_565(Color c) { skvm::I32 r = div255(mul(c.r, splat(31))), g = div255(mul(c.g, splat(63))), b = div255(mul(c.b, splat(31))); return pack(pack(b, g,5), r,11); } // TODO: add native min/max ops to skvm::Builder skvm::I32 min(skvm::I32 x, skvm::I32 y) { return select(lt(x,y), x,y); } skvm::I32 max(skvm::I32 x, skvm::I32 y) { return select(gt(x,y), x,y); } static bool CanBuild(const Key& key) { // These checks parallel the TODOs in Builder::Builder(). if (key.shader) { return false; } if (key.colorFilter) { return false; } switch (key.colorType) { default: return false; case kRGB_565_SkColorType: break; case kRGBA_8888_SkColorType: break; case kBGRA_8888_SkColorType: break; } if (key.alphaType == kUnpremul_SkAlphaType) { return false; } switch (key.blendMode) { default: return false; case SkBlendMode::kSrc: break; case SkBlendMode::kSrcOver: break; } return true; } explicit Builder(const Key& key) { #define TODO SkUNREACHABLE SkASSERT(CanBuild(key)); skvm::Arg uniforms = uniform(), dst_ptr = arg(SkColorTypeBytesPerPixel(key.colorType)); // When coverage is MaskA8 or MaskLCD16 there will be one more mask varying, // and when coverage is Mask3D there will be three more mask varyings. // When there's no shader and no color filter, the source color is the paint color. if (key.shader) { TODO; } if (key.colorFilter) { TODO; } Color src = unpack_8888(uniform32(uniforms, offsetof(Uniforms, paint_color))); // Load up the destination color. Color dst; switch (key.colorType) { default: TODO; case kRGB_565_SkColorType: dst = unpack_565 (load16(dst_ptr)); break; case kRGBA_8888_SkColorType: dst = unpack_8888(load32(dst_ptr)); break; case kBGRA_8888_SkColorType: dst = unpack_8888(load32(dst_ptr)); std::swap(dst.r, dst.b); break; } // When a destination is tagged opaque, we may assume it both starts and stays fully // opaque, ignoring any math that disagrees. So anything involving force_opaque is // optional, and sometimes helps cut a small amount of work in these programs. const bool force_opaque = true && key.alphaType == kOpaque_SkAlphaType; if (force_opaque) { dst.a = splat(0xff); } // We'd need to premul dst after loading and unpremul before storing. if (key.alphaType == kUnpremul_SkAlphaType) { TODO; } // Blend src and dst. switch (key.blendMode) { default: TODO; case SkBlendMode::kSrc: break; case SkBlendMode::kSrcOver: { src.r = add(src.r, div255(mul(dst.r, inv(src.a)))); src.g = add(src.g, div255(mul(dst.g, inv(src.a)))); src.b = add(src.b, div255(mul(dst.b, inv(src.a)))); src.a = add(src.a, div255(mul(dst.a, inv(src.a)))); } break; } // Lerp with coverage if needed. bool apply_coverage = true; Color cov; switch (key.coverage) { case Coverage::Full: apply_coverage = false; break; case Coverage::UniformA8: cov.r = cov.g = cov.b = cov.a = uniform8(uniforms, offsetof(Uniforms, coverage)); break; case Coverage::MaskA8: cov.r = cov.g = cov.b = cov.a = load8(varying<uint8_t>()); break; case Coverage::MaskLCD16: cov = unpack_565(load16(varying<uint16_t>())); cov.a = select(lt(src.a, dst.a), min(cov.r, min(cov.g,cov.b)) , max(cov.r, max(cov.g,cov.b))); break; case Coverage::Mask3D: TODO; } if (apply_coverage) { src.r = mix(dst.r, src.r, cov.r); src.g = mix(dst.g, src.g, cov.g); src.b = mix(dst.b, src.b, cov.b); src.a = mix(dst.a, src.a, cov.a); } if (force_opaque) { src.a = splat(0xff); } // Store back to the destination. switch (key.colorType) { default: SkUNREACHABLE; case kRGB_565_SkColorType: store16(dst_ptr, pack_565(src)); break; case kBGRA_8888_SkColorType: std::swap(src.r, src.b); // fallthrough case kRGBA_8888_SkColorType: store32(dst_ptr, pack_8888(src)); break; } #undef TODO } }; class Blitter final : public SkBlitter { public: bool ok = false; Blitter(const SkPixmap& device, const SkPaint& paint) : fDevice(device) , fKey { device.colorType(), device.alphaType(), Coverage::Full, paint.getBlendMode(), paint.getShader(), paint.getColorFilter(), } { SkColor4f color = paint.getColor4f(); SkColorSpaceXformSteps{sk_srgb_singleton(), kUnpremul_SkAlphaType, device.colorSpace(), kUnpremul_SkAlphaType}.apply(color.vec()); if (color.fitsInBytes() && Builder::CanBuild(fKey)) { fUniforms.paint_color = color.premul().toBytes_RGBA(); ok = true; } } ~Blitter() override { if (SkLRUCache<Key, skvm::Program>* cache = try_acquire_program_cache()) { auto cache_program = [&](skvm::Program&& program, Coverage coverage) { if (!program.empty()) { Key key = fKey.withCoverage(coverage); if (skvm::Program* found = cache->find(key)) { *found = std::move(program); } else { cache->insert(key, std::move(program)); } } }; cache_program(std::move(fBlitH), Coverage::Full); cache_program(std::move(fBlitAntiH), Coverage::UniformA8); cache_program(std::move(fBlitMaskA8), Coverage::MaskA8); cache_program(std::move(fBlitMaskLCD16), Coverage::MaskLCD16); release_program_cache(); } } private: SkPixmap fDevice; // TODO: can this be const&? const Key fKey; Uniforms fUniforms; skvm::Program fBlitH, fBlitAntiH, fBlitMaskA8, fBlitMaskLCD16; skvm::Program buildProgram(Coverage coverage) { Key key = fKey.withCoverage(coverage); { skvm::Program p; if (SkLRUCache<Key, skvm::Program>* cache = try_acquire_program_cache()) { if (skvm::Program* found = cache->find(key)) { p = std::move(*found); } release_program_cache(); } if (!p.empty()) { return p; } } #if 0 static std::atomic<int> done{0}; if (0 == done++) { atexit([]{ SkDebugf("%d calls to done\n", done.load()); }); } #endif return Builder{key}.done(); } void blitH(int x, int y, int w) override { if (fBlitH.empty()) { fBlitH = this->buildProgram(Coverage::Full); } fBlitH.eval(w, &fUniforms, fDevice.addr(x,y)); } void blitAntiH(int x, int y, const SkAlpha cov[], const int16_t runs[]) override { if (fBlitAntiH.empty()) { fBlitAntiH = this->buildProgram(Coverage::UniformA8); } for (int16_t run = *runs; run > 0; run = *runs) { fUniforms.coverage = *cov; fBlitAntiH.eval(run, &fUniforms, fDevice.addr(x,y)); x += run; runs += run; cov += run; } } void blitMask(const SkMask& mask, const SkIRect& clip) override { if (mask.fFormat == SkMask::kBW_Format) { // TODO: native BW masks? return SkBlitter::blitMask(mask, clip); } const skvm::Program* program = nullptr; switch (mask.fFormat) { default: SkUNREACHABLE; // ARGB and SDF masks shouldn't make it here. case SkMask::k3D_Format: // TODO: the mul and add 3D mask planes too case SkMask::kA8_Format: if (fBlitMaskA8.empty()) { fBlitMaskA8 = this->buildProgram(Coverage::MaskA8); } program = &fBlitMaskA8; break; case SkMask::kLCD16_Format: if (fBlitMaskLCD16.empty()) { fBlitMaskLCD16 = this->buildProgram(Coverage::MaskLCD16); } program = &fBlitMaskLCD16; break; } SkASSERT(program); if (program) { for (int y = clip.top(); y < clip.bottom(); y++) { program->eval(clip.width(), &fUniforms, fDevice.addr(clip.left(), y), mask.getAddr(clip.left(), y)); } } } }; } // namespace SkBlitter* SkCreateSkVMBlitter(const SkPixmap& device, const SkPaint& paint, const SkMatrix& ctm, SkArenaAlloc* alloc) { auto blitter = alloc->make<Blitter>(device, paint); return blitter->ok ? blitter : nullptr; } <commit_msg>Only use thread_local on aarch64 iOS build variants.<commit_after>/* * Copyright 2019 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/private/SkMacros.h" #include "src/core/SkArenaAlloc.h" #include "src/core/SkColorSpacePriv.h" #include "src/core/SkColorSpaceXformSteps.h" #include "src/core/SkCoreBlitters.h" #include "src/core/SkLRUCache.h" #include "src/core/SkVM.h" namespace { enum class Coverage { Full, UniformA8, MaskA8, MaskLCD16, Mask3D }; SK_BEGIN_REQUIRE_DENSE; struct Key { SkColorType colorType; SkAlphaType alphaType; Coverage coverage; SkBlendMode blendMode; SkShader* shader; SkColorFilter* colorFilter; Key withCoverage(Coverage c) const { Key k = *this; k.coverage = c; return k; } }; SK_END_REQUIRE_DENSE; static bool operator==(const Key& x, const Key& y) { return x.colorType == y.colorType && x.alphaType == y.alphaType && x.coverage == y.coverage && x.blendMode == y.blendMode && x.shader == y.shader && x.colorFilter == y.colorFilter; } static SkLRUCache<Key, skvm::Program>* try_acquire_program_cache() { #if defined(SK_BUILD_FOR_IOS) // iOS doesn't support thread_local on versions less than 9.0. pthread // based fallbacks must be used there. We could also use an SkSpinlock // and tryAcquire()/release(), or... return nullptr; // ... we could just not cache programs on those platforms. #else thread_local static auto* cache = new SkLRUCache<Key, skvm::Program>{8}; return cache; #endif } static void release_program_cache() { } struct Uniforms { uint32_t paint_color; uint8_t coverage; // Used when Coverage::UniformA8. }; struct Builder : public skvm::Builder { //using namespace skvm; struct Color { skvm::I32 r,g,b,a; }; skvm::I32 inv(skvm::I32 x) { return sub(splat(255), x); } // TODO: provide this in skvm::Builder, with a custom NEON impl. skvm::I32 div255(skvm::I32 v) { // This should be a bit-perfect version of (v+127)/255, // implemented as (v + ((v+128)>>8) + 128)>>8. skvm::I32 v128 = add(v, splat(128)); return shr(add(v128, shr(v128, 8)), 8); } skvm::I32 mix(skvm::I32 x, skvm::I32 y, skvm::I32 t) { return div255(add(mul(x, inv(t)), mul(y, t ))); } Color unpack_8888(skvm::I32 rgba) { return { extract(rgba, 0, splat(0xff)), extract(rgba, 8, splat(0xff)), extract(rgba, 16, splat(0xff)), extract(rgba, 24, splat(0xff)), }; } skvm::I32 pack_8888(Color c) { return pack(pack(c.r, c.g, 8), pack(c.b, c.a, 8), 16); } Color unpack_565(skvm::I32 bgr) { // N.B. kRGB_565_SkColorType is named confusingly; // blue is in the low bits and red the high. skvm::I32 r = extract(bgr, 11, splat(0b011'111)), g = extract(bgr, 5, splat(0b111'111)), b = extract(bgr, 0, splat(0b011'111)); return { // Scale 565 up to 888. bit_or(shl(r, 3), shr(r, 2)), bit_or(shl(g, 2), shr(g, 4)), bit_or(shl(b, 3), shr(b, 2)), splat(0xff), }; } skvm::I32 pack_565(Color c) { skvm::I32 r = div255(mul(c.r, splat(31))), g = div255(mul(c.g, splat(63))), b = div255(mul(c.b, splat(31))); return pack(pack(b, g,5), r,11); } // TODO: add native min/max ops to skvm::Builder skvm::I32 min(skvm::I32 x, skvm::I32 y) { return select(lt(x,y), x,y); } skvm::I32 max(skvm::I32 x, skvm::I32 y) { return select(gt(x,y), x,y); } static bool CanBuild(const Key& key) { // These checks parallel the TODOs in Builder::Builder(). if (key.shader) { return false; } if (key.colorFilter) { return false; } switch (key.colorType) { default: return false; case kRGB_565_SkColorType: break; case kRGBA_8888_SkColorType: break; case kBGRA_8888_SkColorType: break; } if (key.alphaType == kUnpremul_SkAlphaType) { return false; } switch (key.blendMode) { default: return false; case SkBlendMode::kSrc: break; case SkBlendMode::kSrcOver: break; } return true; } explicit Builder(const Key& key) { #define TODO SkUNREACHABLE SkASSERT(CanBuild(key)); skvm::Arg uniforms = uniform(), dst_ptr = arg(SkColorTypeBytesPerPixel(key.colorType)); // When coverage is MaskA8 or MaskLCD16 there will be one more mask varying, // and when coverage is Mask3D there will be three more mask varyings. // When there's no shader and no color filter, the source color is the paint color. if (key.shader) { TODO; } if (key.colorFilter) { TODO; } Color src = unpack_8888(uniform32(uniforms, offsetof(Uniforms, paint_color))); // Load up the destination color. Color dst; switch (key.colorType) { default: TODO; case kRGB_565_SkColorType: dst = unpack_565 (load16(dst_ptr)); break; case kRGBA_8888_SkColorType: dst = unpack_8888(load32(dst_ptr)); break; case kBGRA_8888_SkColorType: dst = unpack_8888(load32(dst_ptr)); std::swap(dst.r, dst.b); break; } // When a destination is tagged opaque, we may assume it both starts and stays fully // opaque, ignoring any math that disagrees. So anything involving force_opaque is // optional, and sometimes helps cut a small amount of work in these programs. const bool force_opaque = true && key.alphaType == kOpaque_SkAlphaType; if (force_opaque) { dst.a = splat(0xff); } // We'd need to premul dst after loading and unpremul before storing. if (key.alphaType == kUnpremul_SkAlphaType) { TODO; } // Blend src and dst. switch (key.blendMode) { default: TODO; case SkBlendMode::kSrc: break; case SkBlendMode::kSrcOver: { src.r = add(src.r, div255(mul(dst.r, inv(src.a)))); src.g = add(src.g, div255(mul(dst.g, inv(src.a)))); src.b = add(src.b, div255(mul(dst.b, inv(src.a)))); src.a = add(src.a, div255(mul(dst.a, inv(src.a)))); } break; } // Lerp with coverage if needed. bool apply_coverage = true; Color cov; switch (key.coverage) { case Coverage::Full: apply_coverage = false; break; case Coverage::UniformA8: cov.r = cov.g = cov.b = cov.a = uniform8(uniforms, offsetof(Uniforms, coverage)); break; case Coverage::MaskA8: cov.r = cov.g = cov.b = cov.a = load8(varying<uint8_t>()); break; case Coverage::MaskLCD16: cov = unpack_565(load16(varying<uint16_t>())); cov.a = select(lt(src.a, dst.a), min(cov.r, min(cov.g,cov.b)) , max(cov.r, max(cov.g,cov.b))); break; case Coverage::Mask3D: TODO; } if (apply_coverage) { src.r = mix(dst.r, src.r, cov.r); src.g = mix(dst.g, src.g, cov.g); src.b = mix(dst.b, src.b, cov.b); src.a = mix(dst.a, src.a, cov.a); } if (force_opaque) { src.a = splat(0xff); } // Store back to the destination. switch (key.colorType) { default: SkUNREACHABLE; case kRGB_565_SkColorType: store16(dst_ptr, pack_565(src)); break; case kBGRA_8888_SkColorType: std::swap(src.r, src.b); // fallthrough case kRGBA_8888_SkColorType: store32(dst_ptr, pack_8888(src)); break; } #undef TODO } }; class Blitter final : public SkBlitter { public: bool ok = false; Blitter(const SkPixmap& device, const SkPaint& paint) : fDevice(device) , fKey { device.colorType(), device.alphaType(), Coverage::Full, paint.getBlendMode(), paint.getShader(), paint.getColorFilter(), } { SkColor4f color = paint.getColor4f(); SkColorSpaceXformSteps{sk_srgb_singleton(), kUnpremul_SkAlphaType, device.colorSpace(), kUnpremul_SkAlphaType}.apply(color.vec()); if (color.fitsInBytes() && Builder::CanBuild(fKey)) { fUniforms.paint_color = color.premul().toBytes_RGBA(); ok = true; } } ~Blitter() override { if (SkLRUCache<Key, skvm::Program>* cache = try_acquire_program_cache()) { auto cache_program = [&](skvm::Program&& program, Coverage coverage) { if (!program.empty()) { Key key = fKey.withCoverage(coverage); if (skvm::Program* found = cache->find(key)) { *found = std::move(program); } else { cache->insert(key, std::move(program)); } } }; cache_program(std::move(fBlitH), Coverage::Full); cache_program(std::move(fBlitAntiH), Coverage::UniformA8); cache_program(std::move(fBlitMaskA8), Coverage::MaskA8); cache_program(std::move(fBlitMaskLCD16), Coverage::MaskLCD16); release_program_cache(); } } private: SkPixmap fDevice; // TODO: can this be const&? const Key fKey; Uniforms fUniforms; skvm::Program fBlitH, fBlitAntiH, fBlitMaskA8, fBlitMaskLCD16; skvm::Program buildProgram(Coverage coverage) { Key key = fKey.withCoverage(coverage); { skvm::Program p; if (SkLRUCache<Key, skvm::Program>* cache = try_acquire_program_cache()) { if (skvm::Program* found = cache->find(key)) { p = std::move(*found); } release_program_cache(); } if (!p.empty()) { return p; } } #if 0 static std::atomic<int> done{0}; if (0 == done++) { atexit([]{ SkDebugf("%d calls to done\n", done.load()); }); } #endif return Builder{key}.done(); } void blitH(int x, int y, int w) override { if (fBlitH.empty()) { fBlitH = this->buildProgram(Coverage::Full); } fBlitH.eval(w, &fUniforms, fDevice.addr(x,y)); } void blitAntiH(int x, int y, const SkAlpha cov[], const int16_t runs[]) override { if (fBlitAntiH.empty()) { fBlitAntiH = this->buildProgram(Coverage::UniformA8); } for (int16_t run = *runs; run > 0; run = *runs) { fUniforms.coverage = *cov; fBlitAntiH.eval(run, &fUniforms, fDevice.addr(x,y)); x += run; runs += run; cov += run; } } void blitMask(const SkMask& mask, const SkIRect& clip) override { if (mask.fFormat == SkMask::kBW_Format) { // TODO: native BW masks? return SkBlitter::blitMask(mask, clip); } const skvm::Program* program = nullptr; switch (mask.fFormat) { default: SkUNREACHABLE; // ARGB and SDF masks shouldn't make it here. case SkMask::k3D_Format: // TODO: the mul and add 3D mask planes too case SkMask::kA8_Format: if (fBlitMaskA8.empty()) { fBlitMaskA8 = this->buildProgram(Coverage::MaskA8); } program = &fBlitMaskA8; break; case SkMask::kLCD16_Format: if (fBlitMaskLCD16.empty()) { fBlitMaskLCD16 = this->buildProgram(Coverage::MaskLCD16); } program = &fBlitMaskLCD16; break; } SkASSERT(program); if (program) { for (int y = clip.top(); y < clip.bottom(); y++) { program->eval(clip.width(), &fUniforms, fDevice.addr(clip.left(), y), mask.getAddr(clip.left(), y)); } } } }; } // namespace SkBlitter* SkCreateSkVMBlitter(const SkPixmap& device, const SkPaint& paint, const SkMatrix& ctm, SkArenaAlloc* alloc) { auto blitter = alloc->make<Blitter>(device, paint); return blitter->ok ? blitter : nullptr; } <|endoftext|>
<commit_before>// This file is part of Poseidon. // Copyleft 2022, LH_Mouse. All wrongs reserved. #ifndef POSEIDON_CORE_CHARBUF_256_ #define POSEIDON_CORE_CHARBUF_256_ #include "../fwd.hpp" namespace poseidon { // This class provides 256-byte storage for temporary use. class charbuf_256 { private: char m_data[256]; public: // Initializes a null-terminated string of zero characters. explicit charbuf_256() noexcept { this->m_data[0] = 0; } public: // Swaps two buffers. charbuf_256& swap(charbuf_256& other) noexcept { char temp[256]; ::std::memcpy(temp, other.m_data, sizeof(temp)); ::std::memcpy(other.m_data, this->m_data, sizeof(temp)); ::std::memcpy(this->m_data, temp, sizeof(temp)); return *this; } // Performs 3-way comparison of two buffers. int compare(const charbuf_256& other) const noexcept { return ::std::strcmp(this->m_data, other.m_data); } int compare(const char* other) const noexcept { return ::std::strcmp(this->m_data, other); } // Returns a pointer to internal storage so a buffer can be passed as // an argument for `char*`. constexpr operator const char*() const noexcept { return this->m_data; } operator char*() noexcept { return this->m_data; } }; inline void swap(charbuf_256& lhs, charbuf_256& rhs) noexcept { lhs.swap(rhs); } inline bool operator==(const charbuf_256& lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) == 0; } inline bool operator==(const char* lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) == 0; } inline bool operator==(const charbuf_256& lhs, const char* rhs) noexcept { return ::std::strcmp(lhs, rhs) == 0; } inline bool operator!=(const charbuf_256& lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) != 0; } inline bool operator!=(const char* lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) != 0; } inline bool operator!=(const charbuf_256& lhs, const char* rhs) noexcept { return ::std::strcmp(lhs, rhs) != 0; } inline bool operator<(const charbuf_256& lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) < 0; } inline bool operator<(const char* lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) < 0; } inline bool operator<(const charbuf_256& lhs, const char* rhs) noexcept { return ::std::strcmp(lhs, rhs) < 0; } inline bool operator>(const charbuf_256& lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) > 0; } inline bool operator>(const char* lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) > 0; } inline bool operator>(const charbuf_256& lhs, const char* rhs) noexcept { return ::std::strcmp(lhs, rhs) > 0; } inline bool operator<=(const charbuf_256& lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) <= 0; } inline bool operator<=(const char* lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) <= 0; } inline bool operator<=(const charbuf_256& lhs, const char* rhs) noexcept { return ::std::strcmp(lhs, rhs) <= 0; } inline bool operator>=(const charbuf_256& lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) >= 0; } inline bool operator>=(const char* lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) >= 0; } inline bool operator>=(const charbuf_256& lhs, const char* rhs) noexcept { return ::std::strcmp(lhs, rhs) >= 0; } } // namespace poseidon #endif <commit_msg>charbuf_256: Fix indention<commit_after>// This file is part of Poseidon. // Copyleft 2022, LH_Mouse. All wrongs reserved. #ifndef POSEIDON_CORE_CHARBUF_256_ #define POSEIDON_CORE_CHARBUF_256_ #include "../fwd.hpp" namespace poseidon { // This class provides 256-byte storage for temporary use. class charbuf_256 { private: char m_data[256]; public: // Initializes a null-terminated string of zero characters. explicit charbuf_256() noexcept { this->m_data[0] = 0; } public: // Swaps two buffers. charbuf_256& swap(charbuf_256& other) noexcept { char temp[256]; ::std::memcpy(temp, other.m_data, sizeof(temp)); ::std::memcpy(other.m_data, this->m_data, sizeof(temp)); ::std::memcpy(this->m_data, temp, sizeof(temp)); return *this; } // Performs 3-way comparison of two buffers. int compare(const charbuf_256& other) const noexcept { return ::std::strcmp(this->m_data, other.m_data); } int compare(const char* other) const noexcept { return ::std::strcmp(this->m_data, other); } // Returns a pointer to internal storage so a buffer can be passed as // an argument for `char*`. constexpr operator const char*() const noexcept { return this->m_data; } operator char*() noexcept { return this->m_data; } }; inline void swap(charbuf_256& lhs, charbuf_256& rhs) noexcept { lhs.swap(rhs); } inline bool operator==(const charbuf_256& lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) == 0; } inline bool operator==(const char* lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) == 0; } inline bool operator==(const charbuf_256& lhs, const char* rhs) noexcept { return ::std::strcmp(lhs, rhs) == 0; } inline bool operator!=(const charbuf_256& lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) != 0; } inline bool operator!=(const char* lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) != 0; } inline bool operator!=(const charbuf_256& lhs, const char* rhs) noexcept { return ::std::strcmp(lhs, rhs) != 0; } inline bool operator<(const charbuf_256& lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) < 0; } inline bool operator<(const char* lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) < 0; } inline bool operator<(const charbuf_256& lhs, const char* rhs) noexcept { return ::std::strcmp(lhs, rhs) < 0; } inline bool operator>(const charbuf_256& lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) > 0; } inline bool operator>(const char* lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) > 0; } inline bool operator>(const charbuf_256& lhs, const char* rhs) noexcept { return ::std::strcmp(lhs, rhs) > 0; } inline bool operator<=(const charbuf_256& lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) <= 0; } inline bool operator<=(const char* lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) <= 0; } inline bool operator<=(const charbuf_256& lhs, const char* rhs) noexcept { return ::std::strcmp(lhs, rhs) <= 0; } inline bool operator>=(const charbuf_256& lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) >= 0; } inline bool operator>=(const char* lhs, const charbuf_256& rhs) noexcept { return ::std::strcmp(lhs, rhs) >= 0; } inline bool operator>=(const charbuf_256& lhs, const char* rhs) noexcept { return ::std::strcmp(lhs, rhs) >= 0; } } // namespace poseidon #endif <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include <osl/diagnose.h> #include <osl/thread.h> #include <rtl/strbuf.hxx> #include "provprox.hxx" #include <com/sun/star/lang/XInitialization.hpp> using namespace com::sun::star::lang; using namespace com::sun::star::ucb; using namespace com::sun::star::uno; //========================================================================= //========================================================================= // // UcbContentProviderProxyFactory Implementation. // //========================================================================= //========================================================================= UcbContentProviderProxyFactory::UcbContentProviderProxyFactory( const Reference< XMultiServiceFactory >& rxSMgr ) : m_xSMgr( rxSMgr ) { } //========================================================================= // virtual UcbContentProviderProxyFactory::~UcbContentProviderProxyFactory() { } //========================================================================= // // XInterface methods. // //========================================================================= XINTERFACE_IMPL_3( UcbContentProviderProxyFactory, XTypeProvider, XServiceInfo, XContentProviderFactory ); //========================================================================= // // XTypeProvider methods. // //========================================================================= XTYPEPROVIDER_IMPL_3( UcbContentProviderProxyFactory, XTypeProvider, XServiceInfo, XContentProviderFactory ); //========================================================================= // // XServiceInfo methods. // //========================================================================= XSERVICEINFO_IMPL_1( UcbContentProviderProxyFactory, OUString( "com.sun.star.comp.ucb.UcbContentProviderProxyFactory" ), OUString( PROVIDER_FACTORY_SERVICE_NAME ) ); //========================================================================= // // Service factory implementation. // //========================================================================= ONE_INSTANCE_SERVICE_FACTORY_IMPL( UcbContentProviderProxyFactory ); //========================================================================= // // XContentProviderFactory methods. // //========================================================================= // virtual Reference< XContentProvider > SAL_CALL UcbContentProviderProxyFactory::createContentProvider( const OUString& Service ) throw( RuntimeException ) { return Reference< XContentProvider >( new UcbContentProviderProxy( m_xSMgr, Service ) ); } //========================================================================= //========================================================================= // // UcbContentProviderProxy Implementation. // //========================================================================= //========================================================================= UcbContentProviderProxy::UcbContentProviderProxy( const Reference< XMultiServiceFactory >& rxSMgr, const OUString& Service ) : m_aService( Service ), m_bReplace( sal_False ), m_bRegister( sal_False ), m_xSMgr( rxSMgr ) { } //========================================================================= // virtual UcbContentProviderProxy::~UcbContentProviderProxy() { } //========================================================================= // // XInterface methods. // //========================================================================= XINTERFACE_COMMON_IMPL( UcbContentProviderProxy ); //============================================================================ // virtual Any SAL_CALL UcbContentProviderProxy::queryInterface( const Type & rType ) throw ( RuntimeException ) { Any aRet = cppu::queryInterface( rType, static_cast< XTypeProvider * >( this ), static_cast< XServiceInfo * >( this ), static_cast< XContentProvider * >( this ), static_cast< XParameterizedContentProvider * >( this ), static_cast< XContentProviderSupplier * >( this ) ); if ( !aRet.hasValue() ) aRet = OWeakObject::queryInterface( rType ); if ( !aRet.hasValue() ) { // Get original provider an forward the call... osl::Guard< osl::Mutex > aGuard( m_aMutex ); Reference< XContentProvider > xProvider = getContentProvider(); if ( xProvider.is() ) aRet = xProvider->queryInterface( rType ); } return aRet; } //========================================================================= // // XTypeProvider methods. // //========================================================================= XTYPEPROVIDER_COMMON_IMPL( UcbContentProviderProxy ); //========================================================================= Sequence< Type > SAL_CALL UcbContentProviderProxy::getTypes() \ throw( RuntimeException ) { // Get original provider an forward the call... osl::Guard< osl::Mutex > aGuard( m_aMutex ); Reference< XTypeProvider > xProvider( getContentProvider(), UNO_QUERY ); if ( xProvider.is() ) { return xProvider->getTypes(); } else { static cppu::OTypeCollection collection( CPPU_TYPE_REF( XTypeProvider ), CPPU_TYPE_REF( XServiceInfo ), CPPU_TYPE_REF( XContentProvider ), CPPU_TYPE_REF( XParameterizedContentProvider ), CPPU_TYPE_REF( XContentProviderSupplier ) ); return collection.getTypes(); } } //========================================================================= // // XServiceInfo methods. // //========================================================================= XSERVICEINFO_NOFACTORY_IMPL_1( UcbContentProviderProxy, OUString( "com.sun.star.comp.ucb.UcbContentProviderProxy" ), OUString( PROVIDER_PROXY_SERVICE_NAME ) ); //========================================================================= // // XContentProvider methods. // //========================================================================= // virtual Reference< XContent > SAL_CALL UcbContentProviderProxy::queryContent( const Reference< XContentIdentifier >& Identifier ) throw( IllegalIdentifierException, RuntimeException ) { // Get original provider an forward the call... osl::Guard< osl::Mutex > aGuard( m_aMutex ); Reference< XContentProvider > xProvider = getContentProvider(); if ( xProvider.is() ) return xProvider->queryContent( Identifier ); return Reference< XContent >(); } //========================================================================= // virtual sal_Int32 SAL_CALL UcbContentProviderProxy::compareContentIds( const Reference< XContentIdentifier >& Id1, const Reference< XContentIdentifier >& Id2 ) throw( RuntimeException ) { // Get original provider an forward the call... osl::Guard< osl::Mutex > aGuard( m_aMutex ); Reference< XContentProvider > xProvider = getContentProvider(); if ( xProvider.is() ) return xProvider->compareContentIds( Id1, Id2 ); // OSL_FAIL( // "UcbContentProviderProxy::compareContentIds - No provider!" ); // @@@ What else? return 0; } //========================================================================= // // XParameterizedContentProvider methods. // //========================================================================= // virtual Reference< XContentProvider > SAL_CALL UcbContentProviderProxy::registerInstance( const OUString& Template, const OUString& Arguments, sal_Bool ReplaceExisting ) throw( IllegalArgumentException, RuntimeException ) { // Just remember that this method was called ( and the params ). osl::Guard< osl::Mutex > aGuard( m_aMutex ); if ( !m_bRegister ) { // m_xTargetProvider = 0; m_aTemplate = Template; m_aArguments = Arguments; m_bReplace = ReplaceExisting; m_bRegister = sal_True; } return this; } //========================================================================= // virtual Reference< XContentProvider > SAL_CALL UcbContentProviderProxy::deregisterInstance( const OUString& Template, const OUString& Arguments ) throw( IllegalArgumentException, RuntimeException ) { osl::Guard< osl::Mutex > aGuard( m_aMutex ); // registerInstance called at proxy and at original? if ( m_bRegister && m_xTargetProvider.is() ) { m_bRegister = sal_False; m_xTargetProvider = 0; Reference< XParameterizedContentProvider > xParamProvider( m_xProvider, UNO_QUERY ); if ( xParamProvider.is() ) { try { xParamProvider->deregisterInstance( Template, Arguments ); } catch ( IllegalIdentifierException const & ) { OSL_FAIL( "UcbContentProviderProxy::deregisterInstance - " "Caught IllegalIdentifierException!" ); } } } return this; } //========================================================================= // // XContentProviderSupplier methods. // //========================================================================= // virtual Reference< XContentProvider > SAL_CALL UcbContentProviderProxy::getContentProvider() throw( RuntimeException ) { osl::Guard< osl::Mutex > aGuard( m_aMutex ); if ( !m_xProvider.is() ) { try { m_xProvider = Reference< XContentProvider >( m_xSMgr->createInstance( m_aService ), UNO_QUERY ); if ( m_aArguments == "NoConfig" ) { Reference<XInitialization> xInit(m_xProvider,UNO_QUERY); if(xInit.is()) { Sequence<Any> aArgs(1); aArgs[0] <<= m_aArguments; xInit->initialize(aArgs); } } } catch ( RuntimeException const & ) { throw; } catch ( Exception const & ) { } // registerInstance called at proxy, but not yet at original? if ( m_xProvider.is() && m_bRegister ) { Reference< XParameterizedContentProvider > xParamProvider( m_xProvider, UNO_QUERY ); if ( xParamProvider.is() ) { try { m_xTargetProvider = xParamProvider->registerInstance( m_aTemplate, m_aArguments, m_bReplace ); } catch ( IllegalIdentifierException const & ) { OSL_FAIL( "UcbContentProviderProxy::getContentProvider - " "Caught IllegalIdentifierException!" ); } OSL_ENSURE( m_xTargetProvider.is(), "UcbContentProviderProxy::getContentProvider - " "No provider!" ); } } if ( !m_xTargetProvider.is() ) m_xTargetProvider = m_xProvider; } OSL_ENSURE( m_xProvider.is(), OStringBuffer("UcbContentProviderProxy::getContentProvider - No provider for '").append(OUStringToOString(m_aService, osl_getThreadTextEncoding())).append(".").getStr() ); return m_xTargetProvider; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>UCB Show more infos about errors loading UCP<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * 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/. * * This file incorporates work covered by the following license notice: * * 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 . */ #include <osl/diagnose.h> #include <osl/thread.h> #include <rtl/strbuf.hxx> #include "provprox.hxx" #include <com/sun/star/lang/XInitialization.hpp> using namespace com::sun::star::lang; using namespace com::sun::star::ucb; using namespace com::sun::star::uno; //========================================================================= //========================================================================= // // UcbContentProviderProxyFactory Implementation. // //========================================================================= //========================================================================= UcbContentProviderProxyFactory::UcbContentProviderProxyFactory( const Reference< XMultiServiceFactory >& rxSMgr ) : m_xSMgr( rxSMgr ) { } //========================================================================= // virtual UcbContentProviderProxyFactory::~UcbContentProviderProxyFactory() { } //========================================================================= // // XInterface methods. // //========================================================================= XINTERFACE_IMPL_3( UcbContentProviderProxyFactory, XTypeProvider, XServiceInfo, XContentProviderFactory ); //========================================================================= // // XTypeProvider methods. // //========================================================================= XTYPEPROVIDER_IMPL_3( UcbContentProviderProxyFactory, XTypeProvider, XServiceInfo, XContentProviderFactory ); //========================================================================= // // XServiceInfo methods. // //========================================================================= XSERVICEINFO_IMPL_1( UcbContentProviderProxyFactory, OUString( "com.sun.star.comp.ucb.UcbContentProviderProxyFactory" ), OUString( PROVIDER_FACTORY_SERVICE_NAME ) ); //========================================================================= // // Service factory implementation. // //========================================================================= ONE_INSTANCE_SERVICE_FACTORY_IMPL( UcbContentProviderProxyFactory ); //========================================================================= // // XContentProviderFactory methods. // //========================================================================= // virtual Reference< XContentProvider > SAL_CALL UcbContentProviderProxyFactory::createContentProvider( const OUString& Service ) throw( RuntimeException ) { return Reference< XContentProvider >( new UcbContentProviderProxy( m_xSMgr, Service ) ); } //========================================================================= //========================================================================= // // UcbContentProviderProxy Implementation. // //========================================================================= //========================================================================= UcbContentProviderProxy::UcbContentProviderProxy( const Reference< XMultiServiceFactory >& rxSMgr, const OUString& Service ) : m_aService( Service ), m_bReplace( sal_False ), m_bRegister( sal_False ), m_xSMgr( rxSMgr ) { } //========================================================================= // virtual UcbContentProviderProxy::~UcbContentProviderProxy() { } //========================================================================= // // XInterface methods. // //========================================================================= XINTERFACE_COMMON_IMPL( UcbContentProviderProxy ); //============================================================================ // virtual Any SAL_CALL UcbContentProviderProxy::queryInterface( const Type & rType ) throw ( RuntimeException ) { Any aRet = cppu::queryInterface( rType, static_cast< XTypeProvider * >( this ), static_cast< XServiceInfo * >( this ), static_cast< XContentProvider * >( this ), static_cast< XParameterizedContentProvider * >( this ), static_cast< XContentProviderSupplier * >( this ) ); if ( !aRet.hasValue() ) aRet = OWeakObject::queryInterface( rType ); if ( !aRet.hasValue() ) { // Get original provider an forward the call... osl::Guard< osl::Mutex > aGuard( m_aMutex ); Reference< XContentProvider > xProvider = getContentProvider(); if ( xProvider.is() ) aRet = xProvider->queryInterface( rType ); } return aRet; } //========================================================================= // // XTypeProvider methods. // //========================================================================= XTYPEPROVIDER_COMMON_IMPL( UcbContentProviderProxy ); //========================================================================= Sequence< Type > SAL_CALL UcbContentProviderProxy::getTypes() \ throw( RuntimeException ) { // Get original provider an forward the call... osl::Guard< osl::Mutex > aGuard( m_aMutex ); Reference< XTypeProvider > xProvider( getContentProvider(), UNO_QUERY ); if ( xProvider.is() ) { return xProvider->getTypes(); } else { static cppu::OTypeCollection collection( CPPU_TYPE_REF( XTypeProvider ), CPPU_TYPE_REF( XServiceInfo ), CPPU_TYPE_REF( XContentProvider ), CPPU_TYPE_REF( XParameterizedContentProvider ), CPPU_TYPE_REF( XContentProviderSupplier ) ); return collection.getTypes(); } } //========================================================================= // // XServiceInfo methods. // //========================================================================= XSERVICEINFO_NOFACTORY_IMPL_1( UcbContentProviderProxy, OUString( "com.sun.star.comp.ucb.UcbContentProviderProxy" ), OUString( PROVIDER_PROXY_SERVICE_NAME ) ); //========================================================================= // // XContentProvider methods. // //========================================================================= // virtual Reference< XContent > SAL_CALL UcbContentProviderProxy::queryContent( const Reference< XContentIdentifier >& Identifier ) throw( IllegalIdentifierException, RuntimeException ) { // Get original provider an forward the call... osl::Guard< osl::Mutex > aGuard( m_aMutex ); Reference< XContentProvider > xProvider = getContentProvider(); if ( xProvider.is() ) return xProvider->queryContent( Identifier ); return Reference< XContent >(); } //========================================================================= // virtual sal_Int32 SAL_CALL UcbContentProviderProxy::compareContentIds( const Reference< XContentIdentifier >& Id1, const Reference< XContentIdentifier >& Id2 ) throw( RuntimeException ) { // Get original provider an forward the call... osl::Guard< osl::Mutex > aGuard( m_aMutex ); Reference< XContentProvider > xProvider = getContentProvider(); if ( xProvider.is() ) return xProvider->compareContentIds( Id1, Id2 ); // OSL_FAIL( // "UcbContentProviderProxy::compareContentIds - No provider!" ); // @@@ What else? return 0; } //========================================================================= // // XParameterizedContentProvider methods. // //========================================================================= // virtual Reference< XContentProvider > SAL_CALL UcbContentProviderProxy::registerInstance( const OUString& Template, const OUString& Arguments, sal_Bool ReplaceExisting ) throw( IllegalArgumentException, RuntimeException ) { // Just remember that this method was called ( and the params ). osl::Guard< osl::Mutex > aGuard( m_aMutex ); if ( !m_bRegister ) { // m_xTargetProvider = 0; m_aTemplate = Template; m_aArguments = Arguments; m_bReplace = ReplaceExisting; m_bRegister = sal_True; } return this; } //========================================================================= // virtual Reference< XContentProvider > SAL_CALL UcbContentProviderProxy::deregisterInstance( const OUString& Template, const OUString& Arguments ) throw( IllegalArgumentException, RuntimeException ) { osl::Guard< osl::Mutex > aGuard( m_aMutex ); // registerInstance called at proxy and at original? if ( m_bRegister && m_xTargetProvider.is() ) { m_bRegister = sal_False; m_xTargetProvider = 0; Reference< XParameterizedContentProvider > xParamProvider( m_xProvider, UNO_QUERY ); if ( xParamProvider.is() ) { try { xParamProvider->deregisterInstance( Template, Arguments ); } catch ( IllegalIdentifierException const & ) { OSL_FAIL( "UcbContentProviderProxy::deregisterInstance - " "Caught IllegalIdentifierException!" ); } } } return this; } //========================================================================= // // XContentProviderSupplier methods. // //========================================================================= // virtual Reference< XContentProvider > SAL_CALL UcbContentProviderProxy::getContentProvider() throw( RuntimeException ) { osl::Guard< osl::Mutex > aGuard( m_aMutex ); if ( !m_xProvider.is() ) { try { m_xProvider = Reference< XContentProvider >( m_xSMgr->createInstance( m_aService ), UNO_QUERY ); if ( m_aArguments == "NoConfig" ) { Reference<XInitialization> xInit(m_xProvider,UNO_QUERY); if(xInit.is()) { Sequence<Any> aArgs(1); aArgs[0] <<= m_aArguments; xInit->initialize(aArgs); } } } catch ( RuntimeException const & ) { throw; } catch ( Exception const & e) { SAL_INFO( "ucb.core", "Exception when getting content provider: " << e.Message ); } // registerInstance called at proxy, but not yet at original? if ( m_xProvider.is() && m_bRegister ) { Reference< XParameterizedContentProvider > xParamProvider( m_xProvider, UNO_QUERY ); if ( xParamProvider.is() ) { try { m_xTargetProvider = xParamProvider->registerInstance( m_aTemplate, m_aArguments, m_bReplace ); } catch ( IllegalIdentifierException const & ) { OSL_FAIL( "UcbContentProviderProxy::getContentProvider - " "Caught IllegalIdentifierException!" ); } OSL_ENSURE( m_xTargetProvider.is(), "UcbContentProviderProxy::getContentProvider - " "No provider!" ); } } if ( !m_xTargetProvider.is() ) m_xTargetProvider = m_xProvider; } OSL_ENSURE( m_xProvider.is(), OStringBuffer("UcbContentProviderProxy::getContentProvider - No provider for '").append(OUStringToOString(m_aService, osl_getThreadTextEncoding())).append(".").getStr() ); return m_xTargetProvider; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // TODO(port): the ifdefs in here are a first step towards trying to determine // the correct abstraction for all the OS functionality required at this // stage of process initialization. It should not be taken as a final // abstraction. #include "build/build_config.h" #if defined(OS_WIN) #include <algorithm> #include <atlbase.h> #include <atlapp.h> #include <malloc.h> #include <new.h> #endif #if defined(OS_LINUX) #include <gtk/gtk.h> #endif #include "base/at_exit.h" #include "base/command_line.h" #include "base/debug_util.h" #include "base/icu_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/scoped_nsautorelease_pool.h" #include "base/stats_table.h" #include "base/string_util.h" #if defined(OS_WIN) #include "base/win_util.h" #endif #include "chrome/app/scoped_ole_initializer.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_counters.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/logging_chrome.h" #include "chrome/common/main_function_params.h" #include "chrome/common/resource_bundle.h" #include "chrome/common/sandbox_init_wrapper.h" #if defined(OS_WIN) #include "sandbox/src/sandbox.h" #include "tools/memory_watcher/memory_watcher.h" #endif #if defined(OS_MACOSX) #include "third_party/WebKit/WebKit/mac/WebCoreSupport/WebSystemInterface.h" #endif extern int BrowserMain(const MainFunctionParams&); extern int RendererMain(const MainFunctionParams&); extern int PluginMain(const MainFunctionParams&); extern int WorkerMain(const MainFunctionParams&); #if defined(OS_WIN) // TODO(erikkay): isn't this already defined somewhere? #define DLLEXPORT __declspec(dllexport) // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling. extern "C" { DLLEXPORT int __cdecl ChromeMain(HINSTANCE instance, sandbox::SandboxInterfaceInfo* sandbox_info, TCHAR* command_line); } #elif defined(OS_POSIX) extern "C" { int ChromeMain(int argc, const char** argv); } #endif namespace { #if defined(OS_WIN) const wchar_t kProfilingDll[] = L"memory_watcher.dll"; // Load the memory profiling DLL. All it needs to be activated // is to be loaded. Return true on success, false otherwise. bool LoadMemoryProfiler() { HMODULE prof_module = LoadLibrary(kProfilingDll); return prof_module != NULL; } CAppModule _Module; #pragma optimize("", off) // Handlers for invalid parameter and pure call. They generate a breakpoint to // tell breakpad that it needs to dump the process. void InvalidParameter(const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t reserved) { __debugbreak(); } void PureCall() { __debugbreak(); } int OnNoMemory(size_t memory_size) { __debugbreak(); // Return memory_size so it is not optimized out. Make sure the return value // is at least 1 so malloc/new is retried, especially useful when under a // debugger. return memory_size ? static_cast<int>(memory_size) : 1; } // Handlers to silently dump the current process when there is an assert in // chrome. void ChromeAssert(const std::string& str) { // Get the breakpad pointer from chrome.exe typedef void (__stdcall *DumpProcessFunction)(); DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>( ::GetProcAddress(::GetModuleHandle(L"chrome.exe"), "DumpProcess")); if (DumpProcess) DumpProcess(); } #pragma optimize("", on) // Early versions of Chrome incorrectly registered a chromehtml: URL handler. // Later versions fixed the registration but in some cases (e.g. Vista and non- // admin installs) the fix could not be applied. This prevents Chrome to be // launched with the incorrect format. // CORRECT: <broser.exe> -- "chromehtml:<url>" // INVALID: <broser.exe> "chromehtml:<url>" bool IncorrectChromeHtmlArguments(const std::wstring& command_line) { const wchar_t kChromeHtml[] = L"-- \"chromehtml:"; const wchar_t kOffset = 5; // Where chromehtml: starts in above std::wstring command_line_lower = command_line; // We are only searching for ASCII characters so this is OK. StringToLowerASCII(&command_line_lower); std::wstring::size_type pos = command_line_lower.find( kChromeHtml + kOffset); if (pos == std::wstring::npos) return false; // The browser is being launched with chromehtml: somewhere on the command // line. We will not launch unless it's preceded by the -- switch terminator. if (pos >= kOffset) { if (equal(kChromeHtml, kChromeHtml + arraysize(kChromeHtml) - 1, command_line_lower.begin() + pos - kOffset)) { return false; } } return true; } #endif // OS_WIN // Register the invalid param handler and pure call handler to be able to // notify breakpad when it happens. void RegisterInvalidParamHandler() { #if defined(OS_WIN) _set_invalid_parameter_handler(InvalidParameter); _set_purecall_handler(PureCall); // Gather allocation failure. _set_new_handler(&OnNoMemory); // Make sure malloc() calls the new handler too. _set_new_mode(1); #endif } void SetupCRT(const CommandLine& parsed_command_line) { #if defined(OS_WIN) #ifdef _CRTDBG_MAP_ALLOC _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); #else if (!parsed_command_line.HasSwitch(switches::kDisableBreakpad)) { _CrtSetReportMode(_CRT_ASSERT, 0); } #endif // Enable the low fragmentation heap for the CRT heap. The heap is not changed // if the process is run under the debugger is enabled or if certain gflags // are set. bool use_lfh = false; if (parsed_command_line.HasSwitch(switches::kUseLowFragHeapCrt)) use_lfh = parsed_command_line.GetSwitchValue(switches::kUseLowFragHeapCrt) != L"false"; if (use_lfh) { void* crt_heap = reinterpret_cast<void*>(_get_heap_handle()); ULONG enable_lfh = 2; HeapSetInformation(crt_heap, HeapCompatibilityInformation, &enable_lfh, sizeof(enable_lfh)); } #endif } // Enable the heap profiler if the appropriate command-line switch is // present, bailing out of the app we can't. void EnableHeapProfiler(const CommandLine& parsed_command_line) { #if defined(OS_WIN) if (parsed_command_line.HasSwitch(switches::kMemoryProfiling)) if (!LoadMemoryProfiler()) exit(-1); #endif } void CommonSubprocessInit() { // Initialize ResourceBundle which handles files loaded from external // sources. The language should have been passed in to us from the // browser process as a command line flag. ResourceBundle::InitSharedInstance(std::wstring()); #if defined(OS_WIN) // HACK: Let Windows know that we have started. This is needed to suppress // the IDC_APPSTARTING cursor from being displayed for a prolonged period // while a subprocess is starting. PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0); MSG msg; PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); #endif } } // namespace #if defined(OS_WIN) DLLEXPORT int __cdecl ChromeMain(HINSTANCE instance, sandbox::SandboxInterfaceInfo* sandbox_info, TCHAR* command_line) { #elif defined(OS_POSIX) int ChromeMain(int argc, const char** argv) { #endif #if defined(OS_MACOSX) DebugUtil::DisableOSCrashDumps(); #endif RegisterInvalidParamHandler(); // The exit manager is in charge of calling the dtors of singleton objects. base::AtExitManager exit_manager; // We need this pool for all the objects created before we get to the // event loop, but we don't want to leave them hanging around until the // app quits. Each "main" needs to flush this pool right before it goes into // its main event loop to get rid of the cruft. base::ScopedNSAutoreleasePool autorelease_pool; // Initialize the command line. #if defined(OS_WIN) CommandLine::Init(0, NULL); #else CommandLine::Init(argc, argv); #endif const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); #if defined(OS_WIN) // Must do this before any other usage of command line! if (::IncorrectChromeHtmlArguments(parsed_command_line.command_line_string())) return 1; #endif SetupCRT(parsed_command_line); // Initialize the Chrome path provider. chrome::RegisterPathProvider(); // Initialize the Stats Counters table. With this initialized, // the StatsViewer can be utilized to read counters outside of // Chrome. These lines can be commented out to effectively turn // counters 'off'. The table is created and exists for the life // of the process. It is not cleaned up. // TODO(port): we probably need to shut this down correctly to avoid // leaking shared memory regions on posix platforms. std::string statsfile = chrome::kStatsFilename; std::string pid_string = StringPrintf("-%d", base::GetCurrentProcId()); statsfile += pid_string; StatsTable *stats_table = new StatsTable(statsfile, chrome::kStatsMaxThreads, chrome::kStatsMaxCounters); StatsTable::set_current(stats_table); StatsScope<StatsCounterTimer> startup_timer(chrome::Counters::chrome_main()); // Enable the heap profiler as early as possible! EnableHeapProfiler(parsed_command_line); // Enable Message Loop related state asap. if (parsed_command_line.HasSwitch(switches::kMessageLoopHistogrammer)) MessageLoop::EnableHistogrammer(true); std::wstring process_type = parsed_command_line.GetSwitchValue(switches::kProcessType); // Checks if the sandbox is enabled in this process and initializes it if this // is the case. The crash handler depends on this so it has to be done before // its initialization. SandboxInitWrapper sandbox_wrapper; #if defined(OS_WIN) sandbox_wrapper.SetServices(sandbox_info); #endif sandbox_wrapper.InitializeSandbox(parsed_command_line, process_type); #if defined(OS_WIN) _Module.Init(NULL, instance); #endif // Notice a user data directory override if any const std::wstring user_data_dir = parsed_command_line.GetSwitchValue(switches::kUserDataDir); if (!user_data_dir.empty()) PathService::Override(chrome::DIR_USER_DATA, user_data_dir); bool single_process = #if defined (GOOGLE_CHROME_BUILD) // This is an unsupported and not fully tested mode, so don't enable it for // official Chrome builds. false; #else parsed_command_line.HasSwitch(switches::kSingleProcess); #endif if (single_process) RenderProcessHost::set_run_renderer_in_process(true); #if defined(OS_MACOSX) // TODO(port-mac): This is from renderer_main_platform_delegate.cc. // shess tried to refactor things appropriately, but it sprawled out // of control because different platforms needed different styles of // initialization. Try again once we understand the process // architecture needed and where it should live. if (single_process) InitWebCoreSystemInterface(); #endif bool icu_result = icu_util::Initialize(); CHECK(icu_result); logging::OldFileDeletionState file_state = logging::APPEND_TO_OLD_LOG_FILE; if (process_type.empty()) { file_state = logging::DELETE_OLD_LOG_FILE; } logging::InitChromeLogging(parsed_command_line, file_state); #ifdef NDEBUG if (parsed_command_line.HasSwitch(switches::kSilentDumpOnDCHECK) && parsed_command_line.HasSwitch(switches::kEnableDCHECK)) { #if defined(OS_WIN) logging::SetLogReportHandler(ChromeAssert); #endif } #endif // NDEBUG if (!process_type.empty()) CommonSubprocessInit(); startup_timer.Stop(); // End of Startup Time Measurement. MainFunctionParams main_params(parsed_command_line, sandbox_wrapper, &autorelease_pool); // TODO(port): turn on these main() functions as they've been de-winified. int rv = -1; if (process_type == switches::kRendererProcess) { rv = RendererMain(main_params); } else if (process_type == switches::kPluginProcess) { #if defined(OS_WIN) rv = PluginMain(main_params); #endif } else if (process_type == switches::kWorkerProcess) { #if defined(OS_WIN) rv = WorkerMain(main_params); #endif } else if (process_type.empty()) { #if defined(OS_LINUX) // gtk_init() can change |argc| and |argv|, but nobody else uses them. gtk_init(&argc, const_cast<char***>(&argv)); #endif ScopedOleInitializer ole_initializer; rv = BrowserMain(main_params); } else { NOTREACHED() << "Unknown process type"; } if (!process_type.empty()) { ResourceBundle::CleanupSharedInstance(); } #if defined(OS_WIN) #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif // _CRTDBG_MAP_ALLOC _Module.Term(); #endif logging::CleanupChromeLogging(); return rv; } <commit_msg>I was a moron and did http://codereview.chromium.org/40012/ against a read only repository. TBR: jrg Review URL: http://codereview.chromium.org/42071<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // TODO(port): the ifdefs in here are a first step towards trying to determine // the correct abstraction for all the OS functionality required at this // stage of process initialization. It should not be taken as a final // abstraction. #include "build/build_config.h" #if defined(OS_WIN) #include <algorithm> #include <atlbase.h> #include <atlapp.h> #include <malloc.h> #include <new.h> #endif #if defined(OS_LINUX) #include <gtk/gtk.h> #endif #include "base/at_exit.h" #include "base/command_line.h" #include "base/debug_util.h" #include "base/icu_util.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/scoped_nsautorelease_pool.h" #include "base/stats_table.h" #include "base/string_util.h" #if defined(OS_WIN) #include "base/win_util.h" #endif #include "chrome/app/scoped_ole_initializer.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_counters.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/logging_chrome.h" #include "chrome/common/main_function_params.h" #include "chrome/common/resource_bundle.h" #include "chrome/common/sandbox_init_wrapper.h" #if defined(OS_WIN) #include "sandbox/src/sandbox.h" #include "tools/memory_watcher/memory_watcher.h" #endif #if defined(OS_MACOSX) #include "third_party/WebKit/WebKit/mac/WebCoreSupport/WebSystemInterface.h" #endif extern int BrowserMain(const MainFunctionParams&); extern int RendererMain(const MainFunctionParams&); extern int PluginMain(const MainFunctionParams&); extern int WorkerMain(const MainFunctionParams&); #if defined(OS_WIN) // TODO(erikkay): isn't this already defined somewhere? #define DLLEXPORT __declspec(dllexport) // We use extern C for the prototype DLLEXPORT to avoid C++ name mangling. extern "C" { DLLEXPORT int __cdecl ChromeMain(HINSTANCE instance, sandbox::SandboxInterfaceInfo* sandbox_info, TCHAR* command_line); } #elif defined(OS_POSIX) extern "C" { int ChromeMain(int argc, const char** argv); } #endif namespace { #if defined(OS_WIN) const wchar_t kProfilingDll[] = L"memory_watcher.dll"; // Load the memory profiling DLL. All it needs to be activated // is to be loaded. Return true on success, false otherwise. bool LoadMemoryProfiler() { HMODULE prof_module = LoadLibrary(kProfilingDll); return prof_module != NULL; } CAppModule _Module; #pragma optimize("", off) // Handlers for invalid parameter and pure call. They generate a breakpoint to // tell breakpad that it needs to dump the process. void InvalidParameter(const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t reserved) { __debugbreak(); } void PureCall() { __debugbreak(); } int OnNoMemory(size_t memory_size) { __debugbreak(); // Return memory_size so it is not optimized out. Make sure the return value // is at least 1 so malloc/new is retried, especially useful when under a // debugger. return memory_size ? static_cast<int>(memory_size) : 1; } // Handlers to silently dump the current process when there is an assert in // chrome. void ChromeAssert(const std::string& str) { // Get the breakpad pointer from chrome.exe typedef void (__stdcall *DumpProcessFunction)(); DumpProcessFunction DumpProcess = reinterpret_cast<DumpProcessFunction>( ::GetProcAddress(::GetModuleHandle(L"chrome.exe"), "DumpProcess")); if (DumpProcess) DumpProcess(); } #pragma optimize("", on) // Early versions of Chrome incorrectly registered a chromehtml: URL handler. // Later versions fixed the registration but in some cases (e.g. Vista and non- // admin installs) the fix could not be applied. This prevents Chrome to be // launched with the incorrect format. // CORRECT: <broser.exe> -- "chromehtml:<url>" // INVALID: <broser.exe> "chromehtml:<url>" bool IncorrectChromeHtmlArguments(const std::wstring& command_line) { const wchar_t kChromeHtml[] = L"-- \"chromehtml:"; const wchar_t kOffset = 5; // Where chromehtml: starts in above std::wstring command_line_lower = command_line; // We are only searching for ASCII characters so this is OK. StringToLowerASCII(&command_line_lower); std::wstring::size_type pos = command_line_lower.find( kChromeHtml + kOffset); if (pos == std::wstring::npos) return false; // The browser is being launched with chromehtml: somewhere on the command // line. We will not launch unless it's preceded by the -- switch terminator. if (pos >= kOffset) { if (equal(kChromeHtml, kChromeHtml + arraysize(kChromeHtml) - 1, command_line_lower.begin() + pos - kOffset)) { return false; } } return true; } #endif // OS_WIN // Register the invalid param handler and pure call handler to be able to // notify breakpad when it happens. void RegisterInvalidParamHandler() { #if defined(OS_WIN) _set_invalid_parameter_handler(InvalidParameter); _set_purecall_handler(PureCall); // Gather allocation failure. _set_new_handler(&OnNoMemory); // Make sure malloc() calls the new handler too. _set_new_mode(1); #endif } void SetupCRT(const CommandLine& parsed_command_line) { #if defined(OS_WIN) #ifdef _CRTDBG_MAP_ALLOC _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR); _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); #else if (!parsed_command_line.HasSwitch(switches::kDisableBreakpad)) { _CrtSetReportMode(_CRT_ASSERT, 0); } #endif // Enable the low fragmentation heap for the CRT heap. The heap is not changed // if the process is run under the debugger is enabled or if certain gflags // are set. bool use_lfh = false; if (parsed_command_line.HasSwitch(switches::kUseLowFragHeapCrt)) use_lfh = parsed_command_line.GetSwitchValue(switches::kUseLowFragHeapCrt) != L"false"; if (use_lfh) { void* crt_heap = reinterpret_cast<void*>(_get_heap_handle()); ULONG enable_lfh = 2; HeapSetInformation(crt_heap, HeapCompatibilityInformation, &enable_lfh, sizeof(enable_lfh)); } #endif } // Enable the heap profiler if the appropriate command-line switch is // present, bailing out of the app we can't. void EnableHeapProfiler(const CommandLine& parsed_command_line) { #if defined(OS_WIN) if (parsed_command_line.HasSwitch(switches::kMemoryProfiling)) if (!LoadMemoryProfiler()) exit(-1); #endif } void CommonSubprocessInit() { // Initialize ResourceBundle which handles files loaded from external // sources. The language should have been passed in to us from the // browser process as a command line flag. ResourceBundle::InitSharedInstance(std::wstring()); #if defined(OS_WIN) // HACK: Let Windows know that we have started. This is needed to suppress // the IDC_APPSTARTING cursor from being displayed for a prolonged period // while a subprocess is starting. PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0); MSG msg; PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); #endif } } // namespace #if defined(OS_WIN) DLLEXPORT int __cdecl ChromeMain(HINSTANCE instance, sandbox::SandboxInterfaceInfo* sandbox_info, TCHAR* command_line) { #elif defined(OS_POSIX) int ChromeMain(int argc, const char** argv) { #endif #if defined(OS_MACOSX) DebugUtil::DisableOSCrashDumps(); #endif RegisterInvalidParamHandler(); // The exit manager is in charge of calling the dtors of singleton objects. base::AtExitManager exit_manager; // We need this pool for all the objects created before we get to the // event loop, but we don't want to leave them hanging around until the // app quits. Each "main" needs to flush this pool right before it goes into // its main event loop to get rid of the cruft. base::ScopedNSAutoreleasePool autorelease_pool; // Initialize the command line. #if defined(OS_WIN) CommandLine::Init(0, NULL); #else CommandLine::Init(argc, argv); #endif const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess(); #if defined(OS_WIN) // Must do this before any other usage of command line! if (::IncorrectChromeHtmlArguments(parsed_command_line.command_line_string())) return 1; #endif int browser_pid; std::wstring process_type = parsed_command_line.GetSwitchValue(switches::kProcessType); if (process_type.empty()) { browser_pid = base::GetCurrentProcId(); } else { std::wstring channel_name = parsed_command_line.GetSwitchValue(switches::kProcessChannelID); browser_pid = _wtoi(channel_name.c_str()); DCHECK(browser_pid != 0); } SetupCRT(parsed_command_line); // Initialize the Chrome path provider. chrome::RegisterPathProvider(); // Initialize the Stats Counters table. With this initialized, // the StatsViewer can be utilized to read counters outside of // Chrome. These lines can be commented out to effectively turn // counters 'off'. The table is created and exists for the life // of the process. It is not cleaned up. // TODO(port): we probably need to shut this down correctly to avoid // leaking shared memory regions on posix platforms. std::string statsfile = chrome::kStatsFilename; std::string pid_string = StringPrintf("-%d", browser_pid); statsfile += pid_string; StatsTable *stats_table = new StatsTable(statsfile, chrome::kStatsMaxThreads, chrome::kStatsMaxCounters); StatsTable::set_current(stats_table); StatsScope<StatsCounterTimer> startup_timer(chrome::Counters::chrome_main()); // Enable the heap profiler as early as possible! EnableHeapProfiler(parsed_command_line); // Enable Message Loop related state asap. if (parsed_command_line.HasSwitch(switches::kMessageLoopHistogrammer)) MessageLoop::EnableHistogrammer(true); // Checks if the sandbox is enabled in this process and initializes it if this // is the case. The crash handler depends on this so it has to be done before // its initialization. SandboxInitWrapper sandbox_wrapper; #if defined(OS_WIN) sandbox_wrapper.SetServices(sandbox_info); #endif sandbox_wrapper.InitializeSandbox(parsed_command_line, process_type); #if defined(OS_WIN) _Module.Init(NULL, instance); #endif // Notice a user data directory override if any const std::wstring user_data_dir = parsed_command_line.GetSwitchValue(switches::kUserDataDir); if (!user_data_dir.empty()) PathService::Override(chrome::DIR_USER_DATA, user_data_dir); bool single_process = #if defined (GOOGLE_CHROME_BUILD) // This is an unsupported and not fully tested mode, so don't enable it for // official Chrome builds. false; #else parsed_command_line.HasSwitch(switches::kSingleProcess); #endif if (single_process) RenderProcessHost::set_run_renderer_in_process(true); #if defined(OS_MACOSX) // TODO(port-mac): This is from renderer_main_platform_delegate.cc. // shess tried to refactor things appropriately, but it sprawled out // of control because different platforms needed different styles of // initialization. Try again once we understand the process // architecture needed and where it should live. if (single_process) InitWebCoreSystemInterface(); #endif bool icu_result = icu_util::Initialize(); CHECK(icu_result); logging::OldFileDeletionState file_state = logging::APPEND_TO_OLD_LOG_FILE; if (process_type.empty()) { file_state = logging::DELETE_OLD_LOG_FILE; } logging::InitChromeLogging(parsed_command_line, file_state); #ifdef NDEBUG if (parsed_command_line.HasSwitch(switches::kSilentDumpOnDCHECK) && parsed_command_line.HasSwitch(switches::kEnableDCHECK)) { #if defined(OS_WIN) logging::SetLogReportHandler(ChromeAssert); #endif } #endif // NDEBUG if (!process_type.empty()) CommonSubprocessInit(); startup_timer.Stop(); // End of Startup Time Measurement. MainFunctionParams main_params(parsed_command_line, sandbox_wrapper, &autorelease_pool); // TODO(port): turn on these main() functions as they've been de-winified. int rv = -1; if (process_type == switches::kRendererProcess) { rv = RendererMain(main_params); } else if (process_type == switches::kPluginProcess) { #if defined(OS_WIN) rv = PluginMain(main_params); #endif } else if (process_type == switches::kWorkerProcess) { #if defined(OS_WIN) rv = WorkerMain(main_params); #endif } else if (process_type.empty()) { #if defined(OS_LINUX) // gtk_init() can change |argc| and |argv|, but nobody else uses them. gtk_init(&argc, const_cast<char***>(&argv)); #endif ScopedOleInitializer ole_initializer; rv = BrowserMain(main_params); } else { NOTREACHED() << "Unknown process type"; } if (!process_type.empty()) { ResourceBundle::CleanupSharedInstance(); } #if defined(OS_WIN) #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); #endif // _CRTDBG_MAP_ALLOC _Module.Term(); #endif logging::CleanupChromeLogging(); return rv; } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/child_thread.h" #include "base/string_util.h" #include "base/command_line.h" #include "chrome/common/child_process.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_service.h" #include "chrome/common/plugin_messages.h" #include "chrome/common/socket_stream_dispatcher.h" #include "ipc/ipc_logging.h" #include "ipc/ipc_message.h" #include "ipc/ipc_switches.h" #include "webkit/glue/webkit_glue.h" ChildThread::ChildThread() { channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kProcessChannelID); Init(); } ChildThread::ChildThread(const std::string& channel_name) : channel_name_(channel_name) { Init(); } void ChildThread::Init() { check_with_browser_before_shutdown_ = false; message_loop_ = MessageLoop::current(); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUserAgent)) { webkit_glue::SetUserAgent( CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kUserAgent)); } channel_.reset(new IPC::SyncChannel(channel_name_, IPC::Channel::MODE_CLIENT, this, NULL, ChildProcess::current()->io_message_loop(), true, ChildProcess::current()->GetShutDownEvent())); #ifdef IPC_MESSAGE_LOG_ENABLED IPC::Logging::current()->SetIPCSender(this); #endif resource_dispatcher_.reset(new ResourceDispatcher(this)); socket_stream_dispatcher_.reset(new SocketStreamDispatcher()); // When running in unit tests, there is already a NotificationService object. // Since only one can exist at a time per thread, check first. if (!NotificationService::current()) notification_service_.reset(new NotificationService); } ChildThread::~ChildThread() { #ifdef IPC_MESSAGE_LOG_ENABLED IPC::Logging::current()->SetIPCSender(NULL); #endif // The ChannelProxy object caches a pointer to the IPC thread, so need to // reset it as it's not guaranteed to outlive this object. // NOTE: this also has the side-effect of not closing the main IPC channel to // the browser process. This is needed because this is the signal that the // browser uses to know that this process has died, so we need it to be alive // until this process is shut down, and the OS closes the handle // automatically. We used to watch the object handle on Windows to do this, // but it wasn't possible to do so on POSIX. channel_->ClearIPCMessageLoop(); } void ChildThread::OnChannelError() { set_on_channel_error_called(true); MessageLoop::current()->Quit(); } bool ChildThread::Send(IPC::Message* msg) { if (!channel_.get()) { delete msg; return false; } return channel_->Send(msg); } void ChildThread::AddRoute(int32 routing_id, IPC::Channel::Listener* listener) { DCHECK(MessageLoop::current() == message_loop()); router_.AddRoute(routing_id, listener); } void ChildThread::RemoveRoute(int32 routing_id) { DCHECK(MessageLoop::current() == message_loop()); router_.RemoveRoute(routing_id); } IPC::Channel::Listener* ChildThread::ResolveRoute(int32 routing_id) { DCHECK(MessageLoop::current() == message_loop()); return router_.ResolveRoute(routing_id); } webkit_glue::ResourceLoaderBridge* ChildThread::CreateBridge( const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info, int host_renderer_id, int host_render_view_id) { return resource_dispatcher()-> CreateBridge(request_info, host_renderer_id, host_render_view_id); } void ChildThread::OnMessageReceived(const IPC::Message& msg) { // Resource responses are sent to the resource dispatcher. if (resource_dispatcher_->OnMessageReceived(msg)) return; if (socket_stream_dispatcher_->OnMessageReceived(msg)) return; bool handled = true; IPC_BEGIN_MESSAGE_MAP(ChildThread, msg) IPC_MESSAGE_HANDLER(PluginProcessMsg_AskBeforeShutdown, OnAskBeforeShutdown) IPC_MESSAGE_HANDLER(PluginProcessMsg_Shutdown, OnShutdown) #if defined(IPC_MESSAGE_LOG_ENABLED) IPC_MESSAGE_HANDLER(PluginProcessMsg_SetIPCLoggingEnabled, OnSetIPCLoggingEnabled) #endif // IPC_MESSAGE_HANDLER IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() if (handled) return; if (msg.routing_id() == MSG_ROUTING_CONTROL) { OnControlMessageReceived(msg); } else { router_.OnMessageReceived(msg); } } void ChildThread::OnAskBeforeShutdown() { check_with_browser_before_shutdown_ = true; } void ChildThread::OnShutdown() { MessageLoop::current()->Quit(); } #if defined(IPC_MESSAGE_LOG_ENABLED) void ChildThread::OnSetIPCLoggingEnabled(bool enable) { if (enable) IPC::Logging::current()->Enable(); else IPC::Logging::current()->Disable(); } #endif // IPC_MESSAGE_LOG_ENABLED ChildThread* ChildThread::current() { return ChildProcess::current()->main_thread(); } void ChildThread::OnProcessFinalRelease() { if (on_channel_error_called_ || !check_with_browser_before_shutdown_) { MessageLoop::current()->Quit(); return; } // The child process shutdown sequence is a request response based mechanism, // where we send out an initial feeler request to the child process host // instance in the browser to verify if it's ok to shutdown the child process. // The browser then sends back a response if it's ok to shutdown. Send(new PluginProcessHostMsg_ShutdownRequest); } <commit_msg>Fix a conditional jump depending on an uninitialized value from r39951 by setting it to false in the ctor.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/common/child_thread.h" #include "base/string_util.h" #include "base/command_line.h" #include "chrome/common/child_process.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_service.h" #include "chrome/common/plugin_messages.h" #include "chrome/common/socket_stream_dispatcher.h" #include "ipc/ipc_logging.h" #include "ipc/ipc_message.h" #include "ipc/ipc_switches.h" #include "webkit/glue/webkit_glue.h" ChildThread::ChildThread() { channel_name_ = CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kProcessChannelID); Init(); } ChildThread::ChildThread(const std::string& channel_name) : channel_name_(channel_name), on_channel_error_called_(false) { Init(); } void ChildThread::Init() { check_with_browser_before_shutdown_ = false; message_loop_ = MessageLoop::current(); if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kUserAgent)) { webkit_glue::SetUserAgent( CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kUserAgent)); } channel_.reset(new IPC::SyncChannel(channel_name_, IPC::Channel::MODE_CLIENT, this, NULL, ChildProcess::current()->io_message_loop(), true, ChildProcess::current()->GetShutDownEvent())); #ifdef IPC_MESSAGE_LOG_ENABLED IPC::Logging::current()->SetIPCSender(this); #endif resource_dispatcher_.reset(new ResourceDispatcher(this)); socket_stream_dispatcher_.reset(new SocketStreamDispatcher()); // When running in unit tests, there is already a NotificationService object. // Since only one can exist at a time per thread, check first. if (!NotificationService::current()) notification_service_.reset(new NotificationService); } ChildThread::~ChildThread() { #ifdef IPC_MESSAGE_LOG_ENABLED IPC::Logging::current()->SetIPCSender(NULL); #endif // The ChannelProxy object caches a pointer to the IPC thread, so need to // reset it as it's not guaranteed to outlive this object. // NOTE: this also has the side-effect of not closing the main IPC channel to // the browser process. This is needed because this is the signal that the // browser uses to know that this process has died, so we need it to be alive // until this process is shut down, and the OS closes the handle // automatically. We used to watch the object handle on Windows to do this, // but it wasn't possible to do so on POSIX. channel_->ClearIPCMessageLoop(); } void ChildThread::OnChannelError() { set_on_channel_error_called(true); MessageLoop::current()->Quit(); } bool ChildThread::Send(IPC::Message* msg) { if (!channel_.get()) { delete msg; return false; } return channel_->Send(msg); } void ChildThread::AddRoute(int32 routing_id, IPC::Channel::Listener* listener) { DCHECK(MessageLoop::current() == message_loop()); router_.AddRoute(routing_id, listener); } void ChildThread::RemoveRoute(int32 routing_id) { DCHECK(MessageLoop::current() == message_loop()); router_.RemoveRoute(routing_id); } IPC::Channel::Listener* ChildThread::ResolveRoute(int32 routing_id) { DCHECK(MessageLoop::current() == message_loop()); return router_.ResolveRoute(routing_id); } webkit_glue::ResourceLoaderBridge* ChildThread::CreateBridge( const webkit_glue::ResourceLoaderBridge::RequestInfo& request_info, int host_renderer_id, int host_render_view_id) { return resource_dispatcher()-> CreateBridge(request_info, host_renderer_id, host_render_view_id); } void ChildThread::OnMessageReceived(const IPC::Message& msg) { // Resource responses are sent to the resource dispatcher. if (resource_dispatcher_->OnMessageReceived(msg)) return; if (socket_stream_dispatcher_->OnMessageReceived(msg)) return; bool handled = true; IPC_BEGIN_MESSAGE_MAP(ChildThread, msg) IPC_MESSAGE_HANDLER(PluginProcessMsg_AskBeforeShutdown, OnAskBeforeShutdown) IPC_MESSAGE_HANDLER(PluginProcessMsg_Shutdown, OnShutdown) #if defined(IPC_MESSAGE_LOG_ENABLED) IPC_MESSAGE_HANDLER(PluginProcessMsg_SetIPCLoggingEnabled, OnSetIPCLoggingEnabled) #endif // IPC_MESSAGE_HANDLER IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() if (handled) return; if (msg.routing_id() == MSG_ROUTING_CONTROL) { OnControlMessageReceived(msg); } else { router_.OnMessageReceived(msg); } } void ChildThread::OnAskBeforeShutdown() { check_with_browser_before_shutdown_ = true; } void ChildThread::OnShutdown() { MessageLoop::current()->Quit(); } #if defined(IPC_MESSAGE_LOG_ENABLED) void ChildThread::OnSetIPCLoggingEnabled(bool enable) { if (enable) IPC::Logging::current()->Enable(); else IPC::Logging::current()->Disable(); } #endif // IPC_MESSAGE_LOG_ENABLED ChildThread* ChildThread::current() { return ChildProcess::current()->main_thread(); } void ChildThread::OnProcessFinalRelease() { if (on_channel_error_called_ || !check_with_browser_before_shutdown_) { MessageLoop::current()->Quit(); return; } // The child process shutdown sequence is a request response based mechanism, // where we send out an initial feeler request to the child process host // instance in the browser to verify if it's ok to shutdown the child process. // The browser then sends back a response if it's ok to shutdown. Send(new PluginProcessHostMsg_ShutdownRequest); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "base/perf_test_suite.h" #include "chrome/common/chrome_paths.cc" int main(int argc, char **argv) { chrome::RegisterPathProvider(); MessageLoop main_message_loop; return PerfTestSuite(argc, argv).Run(); } <commit_msg>Fix error [FATAL:at_exit.cc(40)] Check failed: false. Tried to RegisterCallback without an AtExitManager in (possibly unused) binary perf_tests<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "base/perf_test_suite.h" #include "chrome/common/chrome_paths.cc" int main(int argc, char **argv) { PerfTestSuite suite(argc, argv); chrome::RegisterPathProvider(); MessageLoop main_message_loop; return suite.Run(); } <|endoftext|>
<commit_before>/************************************************************************* * Copyright (c) 2013 eProsima. All rights reserved. * * This copy of FastCdr is licensed to you under the terms described in the * EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution. * *************************************************************************/ /* * HistoryCache.cpp * * Created on: Feb 25, 2014 * Author: Gonzalo Rodriguez Canosa * email: [email protected] * [email protected] */ #include "eprosimartps/HistoryCache.h" #include "eprosimartps/writer/ReaderLocator.h" #include "eprosimartps/writer/RTPSWriter.h" #include "eprosimartps/writer/StatelessWriter.h" #include "eprosimartps/reader/RTPSReader.h" #include "eprosimartps/reader/StatelessReader.h" #include "eprosimartps/common/rtps_elem_seqnum.h" #include "eprosimartps/common/rtps_elem_guid.h" namespace eprosima { namespace rtps { bool sort_CacheChanges_History_SeqNum (CacheChange_t* c1,CacheChange_t* c2) { return(c1->sequenceNumber.to64long() < c2->sequenceNumber.to64long()); } HistoryCache::HistoryCache(uint16_t historysize,uint32_t payload_size, HistoryKind_t kind,Endpoint* endp): mp_rtpswriter(NULL),mp_rtpsreader(NULL), m_historyKind(kind), m_history_max_size(historysize), isHistoryFull(false), changePool(historysize,payload_size), m_isMaxMinUpdated(false) { if(m_historyKind == WRITER) mp_rtpswriter = (RTPSWriter*)endp; else if(m_historyKind == READER) mp_rtpsreader = (RTPSReader*)endp; SEQUENCENUMBER_UNKOWN(m_minSeqNum); SEQUENCENUMBER_UNKOWN(m_maxSeqNum); GUID_UNKNOWN(m_minSeqNumGuid); GUID_UNKNOWN(m_maxSeqNumGuid); pDebugInfo("History created"<<endl); } HistoryCache::~HistoryCache() { pDebugInfo("HistoryCache destructor"<<endl;); for(std::vector<CacheChange_t*>::iterator it=m_changes.begin(); it!=m_changes.end();++it) { changePool.release_Cache(*it); } } bool HistoryCache::get_change(SequenceNumber_t& seqNum,GUID_t& writerGuid,CacheChange_t** ch_ptr,uint16_t *ch_number) { boost::lock_guard<HistoryCache> guard(*this); (*ch_number)=0; for( std::vector<CacheChange_t*>::iterator it = m_changes.begin(); it!=m_changes.end();++it){ if((*it)->sequenceNumber.to64long() == seqNum.to64long() ) if(m_historyKind == WRITER || (m_historyKind == READER && (*it)->writerGUID == writerGuid)) { *ch_ptr = *it; return true; } (*ch_number)++; } return false; } bool HistoryCache::get_change(SequenceNumber_t& seqNum,GUID_t& writerGuid,CacheChange_t** ch_ptr) { boost::lock_guard<HistoryCache> guard(*this); std::vector<CacheChange_t*>::iterator it; for(it = m_changes.begin();it!=m_changes.end();++it){ if((*it)->sequenceNumber.to64long() == seqNum.to64long()) { if(m_historyKind == WRITER || (m_historyKind == READER && (*it)->writerGUID == writerGuid)) { *ch_ptr = *it; return true; } } } return false; } bool HistoryCache::get_last_added_cache(CacheChange_t** ch_ptr) { boost::lock_guard<HistoryCache> guard(*this); if(!m_changes.empty()) { *ch_ptr = *(m_changes.end()-1); return true; } else { *ch_ptr = NULL; return false; } } bool HistoryCache::add_change(CacheChange_t* a_change) { boost::lock_guard<HistoryCache> guard(*this); if(m_changes.size() == (size_t)m_history_max_size) //History is full { pWarning("Attempting to add change with Full History" << endl); return false; } //make copy of change to save if(m_historyKind == WRITER) { m_lastChangeSequenceNumber++; a_change->sequenceNumber = m_lastChangeSequenceNumber; m_changes.push_back(a_change); } else if(m_historyKind == READER) { //Check that the same change has not been already introduced std::vector<CacheChange_t*>::iterator it; for(it=m_changes.begin();it!=m_changes.end();++it) { if((*it)->sequenceNumber.to64long() == a_change->sequenceNumber.to64long() && (*it)->writerGUID == a_change->writerGUID) { pWarning("Change with the same seqNum already in History" << endl); return false; } } m_changes.push_back(a_change); } else { pError(B_RED<<"HistoryType UNDEFINED"<<DEF <<endl); return false; } if(m_changes.size()==m_history_max_size) isHistoryFull = true; m_isMaxMinUpdated = false; pDebugInfo("Cache added to History with seqNum: " << a_change->sequenceNumber.to64long() << " from entityId: "<< a_change->writerGUID.entityId.value[0] << "." << a_change->writerGUID.entityId.value[1] << "." << a_change->writerGUID.entityId.value[2] << "." << a_change->writerGUID.entityId.value[3] << endl); return true; } bool HistoryCache::remove_change(SequenceNumber_t& seqnum, GUID_t& guid) { boost::lock_guard<HistoryCache> guard(*this); for(std::vector<CacheChange_t*>::iterator it = m_changes.begin(); it!=m_changes.end();++it) { if((*it)->sequenceNumber.to64long() == seqnum.to64long()) { if(m_historyKind == WRITER || (m_historyKind == READER && (*it)->writerGUID == guid)) { changePool.release_Cache(*it); m_changes.erase(it); isHistoryFull = false; m_isMaxMinUpdated = false; pDebugInfo("Change removed"<<endl) return true; } } } pWarning("Change NOT removed"<<endl); return false; } bool HistoryCache::remove_change(std::vector<CacheChange_t*>::iterator it) { boost::lock_guard<HistoryCache> guard(*this); changePool.release_Cache(*it); m_changes.erase(it); isHistoryFull = false; m_isMaxMinUpdated = false; pDebugInfo("Change removed"<<endl); return true; } bool HistoryCache::remove_all_changes() { boost::lock_guard<HistoryCache> guard(*this); if(!m_changes.empty()) { for(std::vector<CacheChange_t*>::iterator it = m_changes.begin();it!=m_changes.end();++it) { changePool.release_Cache(*it); } m_changes.clear(); isHistoryFull = false; m_isMaxMinUpdated = false; return true; } return false; } bool HistoryCache::isFull() { //boost::lock_guard<HistoryCache> guard(*this); if(isHistoryFull) return true; else return false; } bool HistoryCache::get_seq_num_min(SequenceNumber_t* seqnum,GUID_t* guid) { boost::lock_guard<HistoryCache> guard(*this); updateMaxMinSeqNum(); *seqnum =m_minSeqNum; if(guid!=NULL) *guid = m_minSeqNumGuid; return true; } bool HistoryCache::get_seq_num_max(SequenceNumber_t* seqnum,GUID_t* guid) { boost::lock_guard<HistoryCache> guard(*this); updateMaxMinSeqNum(); *seqnum = m_maxSeqNum; if(guid!=NULL) *guid = m_maxSeqNumGuid; return true; } void HistoryCache::updateMaxMinSeqNum() { //boost::lock_guard<HistoryCache> guard(*this); if(!m_changes.empty()) { if(!m_isMaxMinUpdated) { std::sort(m_changes.begin(),m_changes.end(),sort_CacheChanges_History_SeqNum); m_maxSeqNum = (*(m_changes.end()-1))->sequenceNumber; m_maxSeqNumGuid = (*(m_changes.end()-1))->writerGUID; m_minSeqNum = (*m_changes.begin())->sequenceNumber; m_minSeqNumGuid = (*m_changes.begin())->writerGUID; // m_maxSeqNum = m_minSeqNum = m_changes[0]->sequenceNumber; // m_maxSeqNumGuid = m_minSeqNumGuid = m_changes[0]->writerGUID; // // for(std::vector<CacheChange_t*>::iterator it = m_changes.begin(); // it!=m_changes.end();++it){ // if((*it)->sequenceNumber.to64long() > m_maxSeqNum.to64long()) // { // m_maxSeqNum = (*it)->sequenceNumber; // m_maxSeqNumGuid = (*it)->writerGUID; // } // if((*it)->sequenceNumber.to64long() < m_minSeqNum.to64long()) // { // m_minSeqNum = (*it)->sequenceNumber; // m_minSeqNumGuid = (*it)->writerGUID; // } // } m_isMaxMinUpdated = true; } } else { SEQUENCENUMBER_UNKOWN(m_minSeqNum); SEQUENCENUMBER_UNKOWN(m_maxSeqNum); GUID_UNKNOWN(m_minSeqNumGuid); GUID_UNKNOWN(m_maxSeqNumGuid); } return; } CacheChange_t* HistoryCache::reserve_Cache() { return changePool.reserve_Cache(); } void HistoryCache::release_Cache(CacheChange_t* ch) { return changePool.release_Cache(ch); } void HistoryCache::sortCacheChangesBySeqNum() { std::sort(m_changes.begin(),m_changes.end(),sort_CacheChanges_History_SeqNum); } } /* namespace rtps */ } /* namespace eprosima */ <commit_msg>HistoryCache change again<commit_after>/************************************************************************* * Copyright (c) 2013 eProsima. All rights reserved. * * This copy of FastCdr is licensed to you under the terms described in the * EPROSIMARTPS_LIBRARY_LICENSE file included in this distribution. * *************************************************************************/ /* * HistoryCache.cpp * * Created on: Feb 25, 2014 * Author: Gonzalo Rodriguez Canosa * email: [email protected] * [email protected] */ #include "eprosimartps/HistoryCache.h" #include "eprosimartps/writer/ReaderLocator.h" #include "eprosimartps/writer/RTPSWriter.h" #include "eprosimartps/writer/StatelessWriter.h" #include "eprosimartps/reader/RTPSReader.h" #include "eprosimartps/reader/StatelessReader.h" #include "eprosimartps/common/rtps_elem_seqnum.h" #include "eprosimartps/common/rtps_elem_guid.h" namespace eprosima { namespace rtps { bool sort_CacheChanges_History_SeqNum (CacheChange_t* c1,CacheChange_t* c2) { return(c1->sequenceNumber.to64long() < c2->sequenceNumber.to64long()); } HistoryCache::HistoryCache(uint16_t historysize,uint32_t payload_size, HistoryKind_t kind,Endpoint* endp): mp_rtpswriter(NULL),mp_rtpsreader(NULL), m_historyKind(kind), m_history_max_size(historysize), isHistoryFull(false), changePool(historysize,payload_size), m_isMaxMinUpdated(false) { if(m_historyKind == WRITER) mp_rtpswriter = (RTPSWriter*)endp; else if(m_historyKind == READER) mp_rtpsreader = (RTPSReader*)endp; SEQUENCENUMBER_UNKOWN(m_minSeqNum); SEQUENCENUMBER_UNKOWN(m_maxSeqNum); GUID_UNKNOWN(m_minSeqNumGuid); GUID_UNKNOWN(m_maxSeqNumGuid); pDebugInfo("History created"<<endl); } HistoryCache::~HistoryCache() { pDebugInfo("HistoryCache destructor"<<endl;); for(std::vector<CacheChange_t*>::iterator it=m_changes.begin(); it!=m_changes.end();++it) { changePool.release_Cache(*it); } } bool HistoryCache::get_change(SequenceNumber_t& seqNum,GUID_t& writerGuid,CacheChange_t** ch_ptr,uint16_t *ch_number) { boost::lock_guard<HistoryCache> guard(*this); (*ch_number)=0; for( std::vector<CacheChange_t*>::iterator it = m_changes.begin(); it!=m_changes.end();++it){ if((*it)->sequenceNumber.to64long() == seqNum.to64long() ) if(m_historyKind == WRITER || (m_historyKind == READER && (*it)->writerGUID == writerGuid)) { *ch_ptr = *it; return true; } (*ch_number)++; } return false; } bool HistoryCache::get_change(SequenceNumber_t& seqNum,GUID_t& writerGuid,CacheChange_t** ch_ptr) { boost::lock_guard<HistoryCache> guard(*this); std::vector<CacheChange_t*>::iterator it; for(it = m_changes.begin();it!=m_changes.end();++it){ if((*it)->sequenceNumber.to64long() == seqNum.to64long()) { if(m_historyKind == WRITER || (m_historyKind == READER && (*it)->writerGUID == writerGuid)) { *ch_ptr = *it; return true; } } } return false; } bool HistoryCache::get_last_added_cache(CacheChange_t** ch_ptr) { boost::lock_guard<HistoryCache> guard(*this); if(!m_changes.empty()) { *ch_ptr = *(m_changes.end()-1); return true; } else { *ch_ptr = NULL; return false; } } bool HistoryCache::add_change(CacheChange_t* a_change) { boost::lock_guard<HistoryCache> guard(*this); if(m_changes.size() == (size_t)m_history_max_size) //History is full { pWarning("Attempting to add change with Full History" << endl); return false; } //make copy of change to save if(m_historyKind == WRITER) { m_lastChangeSequenceNumber++; a_change->sequenceNumber = m_lastChangeSequenceNumber; m_changes.push_back(a_change); } else if(m_historyKind == READER) { //Check that the same change has not been already introduced std::vector<CacheChange_t*>::iterator it; for(it=m_changes.begin();it!=m_changes.end();++it) { if((*it)->sequenceNumber.to64long() == a_change->sequenceNumber.to64long() && (*it)->writerGUID == a_change->writerGUID) { pWarning("Change with the same seqNum already in History" << endl); return false; } } m_changes.push_back(a_change); } else { pError(B_RED<<"HistoryType UNDEFINED"<<DEF <<endl); return false; } if(m_changes.size()==m_history_max_size) isHistoryFull = true; m_isMaxMinUpdated = false; pDebugInfo("Cache added to History with seqNum: " << a_change->sequenceNumber.to64long() << " from entityId: "<< (int)a_change->writerGUID.entityId.value[0] << "." << (int)a_change->writerGUID.entityId.value[1] << "." << (int)a_change->writerGUID.entityId.value[2] << "." << (int)a_change->writerGUID.entityId.value[3] << endl); return true; } bool HistoryCache::remove_change(SequenceNumber_t& seqnum, GUID_t& guid) { boost::lock_guard<HistoryCache> guard(*this); for(std::vector<CacheChange_t*>::iterator it = m_changes.begin(); it!=m_changes.end();++it) { if((*it)->sequenceNumber.to64long() == seqnum.to64long()) { if(m_historyKind == WRITER || (m_historyKind == READER && (*it)->writerGUID == guid)) { changePool.release_Cache(*it); m_changes.erase(it); isHistoryFull = false; m_isMaxMinUpdated = false; pDebugInfo("Change removed"<<endl) return true; } } } pWarning("Change NOT removed"<<endl); return false; } bool HistoryCache::remove_change(std::vector<CacheChange_t*>::iterator it) { boost::lock_guard<HistoryCache> guard(*this); changePool.release_Cache(*it); m_changes.erase(it); isHistoryFull = false; m_isMaxMinUpdated = false; pDebugInfo("Change removed"<<endl); return true; } bool HistoryCache::remove_all_changes() { boost::lock_guard<HistoryCache> guard(*this); if(!m_changes.empty()) { for(std::vector<CacheChange_t*>::iterator it = m_changes.begin();it!=m_changes.end();++it) { changePool.release_Cache(*it); } m_changes.clear(); isHistoryFull = false; m_isMaxMinUpdated = false; return true; } return false; } bool HistoryCache::isFull() { //boost::lock_guard<HistoryCache> guard(*this); if(isHistoryFull) return true; else return false; } bool HistoryCache::get_seq_num_min(SequenceNumber_t* seqnum,GUID_t* guid) { boost::lock_guard<HistoryCache> guard(*this); updateMaxMinSeqNum(); *seqnum =m_minSeqNum; if(guid!=NULL) *guid = m_minSeqNumGuid; return true; } bool HistoryCache::get_seq_num_max(SequenceNumber_t* seqnum,GUID_t* guid) { boost::lock_guard<HistoryCache> guard(*this); updateMaxMinSeqNum(); *seqnum = m_maxSeqNum; if(guid!=NULL) *guid = m_maxSeqNumGuid; return true; } void HistoryCache::updateMaxMinSeqNum() { //boost::lock_guard<HistoryCache> guard(*this); if(!m_changes.empty()) { if(!m_isMaxMinUpdated) { std::sort(m_changes.begin(),m_changes.end(),sort_CacheChanges_History_SeqNum); m_maxSeqNum = (*(m_changes.end()-1))->sequenceNumber; m_maxSeqNumGuid = (*(m_changes.end()-1))->writerGUID; m_minSeqNum = (*m_changes.begin())->sequenceNumber; m_minSeqNumGuid = (*m_changes.begin())->writerGUID; // m_maxSeqNum = m_minSeqNum = m_changes[0]->sequenceNumber; // m_maxSeqNumGuid = m_minSeqNumGuid = m_changes[0]->writerGUID; // // for(std::vector<CacheChange_t*>::iterator it = m_changes.begin(); // it!=m_changes.end();++it){ // if((*it)->sequenceNumber.to64long() > m_maxSeqNum.to64long()) // { // m_maxSeqNum = (*it)->sequenceNumber; // m_maxSeqNumGuid = (*it)->writerGUID; // } // if((*it)->sequenceNumber.to64long() < m_minSeqNum.to64long()) // { // m_minSeqNum = (*it)->sequenceNumber; // m_minSeqNumGuid = (*it)->writerGUID; // } // } m_isMaxMinUpdated = true; } } else { SEQUENCENUMBER_UNKOWN(m_minSeqNum); SEQUENCENUMBER_UNKOWN(m_maxSeqNum); GUID_UNKNOWN(m_minSeqNumGuid); GUID_UNKNOWN(m_maxSeqNumGuid); } return; } CacheChange_t* HistoryCache::reserve_Cache() { return changePool.reserve_Cache(); } void HistoryCache::release_Cache(CacheChange_t* ch) { return changePool.release_Cache(ch); } void HistoryCache::sortCacheChangesBySeqNum() { std::sort(m_changes.begin(),m_changes.end(),sort_CacheChanges_History_SeqNum); } } /* namespace rtps */ } /* namespace eprosima */ <|endoftext|>
<commit_before>/* * * Copyright 2015, Google Inc. * 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <grpc++/server.h> #include <utility> #include <grpc/grpc.h> #include <grpc/grpc_security.h> #include <grpc/support/log.h> #include <grpc++/completion_queue.h> #include <grpc++/generic_service.h> #include <grpc++/impl/rpc_service_method.h> #include <grpc++/impl/service_type.h> #include <grpc++/server_context.h> #include <grpc++/server_credentials.h> #include <grpc++/thread_pool_interface.h> #include "src/cpp/proto/proto_utils.h" #include "src/cpp/util/time.h" namespace grpc { class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag { public: SyncRequest(RpcServiceMethod* method, void* tag) : method_(method), tag_(tag), in_flight_(false), has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC || method->method_type() == RpcMethod::SERVER_STREAMING), has_response_payload_(method->method_type() == RpcMethod::NORMAL_RPC || method->method_type() == RpcMethod::CLIENT_STREAMING) { grpc_metadata_array_init(&request_metadata_); } static SyncRequest* Wait(CompletionQueue* cq, bool* ok) { void* tag = nullptr; *ok = false; if (!cq->Next(&tag, ok)) { return nullptr; } auto* mrd = static_cast<SyncRequest*>(tag); GPR_ASSERT(mrd->in_flight_); return mrd; } void Request(grpc_server* server) { GPR_ASSERT(!in_flight_); in_flight_ = true; cq_ = grpc_completion_queue_create(); GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_registered_call( server, tag_, &call_, &deadline_, &request_metadata_, has_request_payload_ ? &request_payload_ : nullptr, cq_, this)); } bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { if (!*status) { grpc_completion_queue_destroy(cq_); } return true; } class CallData GRPC_FINAL { public: explicit CallData(Server* server, SyncRequest* mrd) : cq_(mrd->cq_), call_(mrd->call_, server, &cq_), ctx_(mrd->deadline_, mrd->request_metadata_.metadata, mrd->request_metadata_.count), has_request_payload_(mrd->has_request_payload_), has_response_payload_(mrd->has_response_payload_), request_payload_(mrd->request_payload_), method_(mrd->method_) { ctx_.call_ = mrd->call_; GPR_ASSERT(mrd->in_flight_); mrd->in_flight_ = false; mrd->request_metadata_.count = 0; } ~CallData() { if (has_request_payload_ && request_payload_) { grpc_byte_buffer_destroy(request_payload_); } } void Run() { std::unique_ptr<grpc::protobuf::Message> req; std::unique_ptr<grpc::protobuf::Message> res; if (has_request_payload_) { req.reset(method_->AllocateRequestProto()); if (!DeserializeProto(request_payload_, req.get())) { abort(); // for now } } if (has_response_payload_) { res.reset(method_->AllocateResponseProto()); } ctx_.BeginCompletionOp(&call_); auto status = method_->handler()->RunHandler( MethodHandler::HandlerParameter(&call_, &ctx_, req.get(), res.get())); CallOpBuffer buf; if (!ctx_.sent_initial_metadata_) { buf.AddSendInitialMetadata(&ctx_.initial_metadata_); } if (has_response_payload_) { buf.AddSendMessage(*res); } buf.AddServerSendStatus(&ctx_.trailing_metadata_, status); call_.PerformOps(&buf); GPR_ASSERT(cq_.Pluck(&buf)); void* ignored_tag; bool ignored_ok; cq_.Shutdown(); GPR_ASSERT(cq_.Next(&ignored_tag, &ignored_ok) == false); } private: CompletionQueue cq_; Call call_; ServerContext ctx_; const bool has_request_payload_; const bool has_response_payload_; grpc_byte_buffer* request_payload_; RpcServiceMethod* const method_; }; private: RpcServiceMethod* const method_; void* const tag_; bool in_flight_; const bool has_request_payload_; const bool has_response_payload_; grpc_call* call_; gpr_timespec deadline_; grpc_metadata_array request_metadata_; grpc_byte_buffer* request_payload_; grpc_completion_queue* cq_; }; Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned) : started_(false), shutdown_(false), num_running_cb_(0), server_(grpc_server_create(cq_.cq(), nullptr)), thread_pool_(thread_pool), thread_pool_owned_(thread_pool_owned) {} Server::~Server() { std::unique_lock<std::mutex> lock(mu_); if (started_ && !shutdown_) { lock.unlock(); Shutdown(); } else { lock.unlock(); } grpc_server_destroy(server_); if (thread_pool_owned_) { delete thread_pool_; } } bool Server::RegisterService(RpcService* service) { for (int i = 0; i < service->GetMethodCount(); ++i) { RpcServiceMethod* method = service->GetMethod(i); void* tag = grpc_server_register_method(server_, method->name(), nullptr, cq_.cq()); if (!tag) { gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", method->name()); return false; } sync_methods_.emplace_back(method, tag); } return true; } bool Server::RegisterAsyncService(AsynchronousService* service) { GPR_ASSERT(service->dispatch_impl_ == nullptr && "Can only register an asynchronous service against one server."); service->dispatch_impl_ = this; service->request_args_ = new void* [service->method_count_]; for (size_t i = 0; i < service->method_count_; ++i) { void* tag = grpc_server_register_method(server_, service->method_names_[i], nullptr, service->completion_queue()->cq()); if (!tag) { gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", service->method_names_[i]); return false; } service->request_args_[i] = tag; } return true; } void Server::RegisterGenericService(GenericService* service) { GPR_ASSERT(service->server_ == nullptr && "Can only register an generic service against one server."); service->server_ = this; } int Server::AddPort(const grpc::string& addr, ServerCredentials* creds) { GPR_ASSERT(!started_); return creds->AddPortToServer(addr, server_); } bool Server::Start() { GPR_ASSERT(!started_); started_ = true; grpc_server_start(server_); // Start processing rpcs. if (!sync_methods_.empty()) { for (auto& m : sync_methods_) { m.Request(server_); } ScheduleCallback(); } return true; } void Server::Shutdown() { std::unique_lock<std::mutex> lock(mu_); if (started_ && !shutdown_) { shutdown_ = true; grpc_server_shutdown(server_); cq_.Shutdown(); // Wait for running callbacks to finish. while (num_running_cb_ != 0) { callback_cv_.wait(lock); } } } void Server::Wait() { std::unique_lock<std::mutex> lock(mu_); while (num_running_cb_ != 0) { callback_cv_.wait(lock); } } void Server::PerformOpsOnCall(CallOpBuffer* buf, Call* call) { static const size_t MAX_OPS = 8; size_t nops = MAX_OPS; grpc_op ops[MAX_OPS]; buf->FillOps(ops, &nops); GPR_ASSERT(GRPC_CALL_OK == grpc_call_start_batch(call->call(), ops, nops, buf)); } class Server::AsyncRequest GRPC_FINAL : public CompletionQueueTag { public: AsyncRequest(Server* server, void* registered_method, ServerContext* ctx, grpc::protobuf::Message* request, ServerAsyncStreamingInterface* stream, CompletionQueue* cq, void* tag) : tag_(tag), request_(request), stream_(stream), cq_(cq), ctx_(ctx), generic_ctx_(nullptr), server_(server), call_(nullptr), payload_(nullptr) { memset(&array_, 0, sizeof(array_)); grpc_call_details_init(&call_details_); grpc_server_request_registered_call( server->server_, registered_method, &call_, &call_details_.deadline, &array_, request ? &payload_ : nullptr, cq->cq(), this); } AsyncRequest(Server* server, GenericServerContext* ctx, ServerAsyncStreamingInterface* stream, CompletionQueue* cq, void* tag) : tag_(tag), request_(nullptr), stream_(stream), cq_(cq), ctx_(nullptr), generic_ctx_(ctx), server_(server), call_(nullptr), payload_(nullptr) { memset(&array_, 0, sizeof(array_)); grpc_call_details_init(&call_details_); grpc_server_request_call( server->server_, &call_, &call_details_, &array_, cq->cq(), this); } ~AsyncRequest() { if (payload_) { grpc_byte_buffer_destroy(payload_); } grpc_metadata_array_destroy(&array_); } bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { *tag = tag_; bool orig_status = *status; if (*status && request_) { if (payload_) { *status = DeserializeProto(payload_, request_); } else { *status = false; } } ServerContext* ctx = ctx_ ? ctx_ : generic_ctx_; GPR_ASSERT(ctx); if (*status) { ctx->deadline_ = Timespec2Timepoint(call_details_.deadline); for (size_t i = 0; i < array_.count; i++) { ctx->client_metadata_.insert(std::make_pair( grpc::string(array_.metadata[i].key), grpc::string( array_.metadata[i].value, array_.metadata[i].value + array_.metadata[i].value_length))); } if (generic_ctx_) { generic_ctx_->method_ = call_details_.method; generic_ctx_->host_ = call_details_.host; } } ctx->call_ = call_; Call call(call_, server_, cq_); if (orig_status && call_) { ctx->BeginCompletionOp(&call); } // just the pointers inside call are copied here stream_->BindCall(&call); delete this; return true; } private: void* const tag_; grpc::protobuf::Message* const request_; ServerAsyncStreamingInterface* const stream_; CompletionQueue* const cq_; ServerContext* const ctx_; GenericServerContext* const generic_ctx_; Server* const server_; grpc_call* call_; grpc_call_details call_details_; grpc_metadata_array array_; grpc_byte_buffer* payload_; }; void Server::RequestAsyncCall(void* registered_method, ServerContext* context, grpc::protobuf::Message* request, ServerAsyncStreamingInterface* stream, CompletionQueue* cq, void* tag) { new AsyncRequest(this, registered_method, context, request, stream, cq, tag); } void Server::RequestGenericCall(GenericServerContext* context, ServerAsyncStreamingInterface* stream, CompletionQueue* cq, void* tag) { new AsyncRequest(this, context, stream, cq, tag); } void Server::ScheduleCallback() { { std::unique_lock<std::mutex> lock(mu_); num_running_cb_++; } thread_pool_->ScheduleCallback(std::bind(&Server::RunRpc, this)); } void Server::RunRpc() { // Wait for one more incoming rpc. bool ok; auto* mrd = SyncRequest::Wait(&cq_, &ok); if (mrd) { ScheduleCallback(); if (ok) { SyncRequest::CallData cd(this, mrd); mrd->Request(server_); cd.Run(); } } { std::unique_lock<std::mutex> lock(mu_); num_running_cb_--; if (shutdown_) { callback_cv_.notify_all(); } } } } // namespace grpc <commit_msg>resolve leak, now asan clean<commit_after>/* * * Copyright 2015, Google Inc. * 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <grpc++/server.h> #include <utility> #include <grpc/grpc.h> #include <grpc/grpc_security.h> #include <grpc/support/alloc.h> #include <grpc/support/log.h> #include <grpc++/completion_queue.h> #include <grpc++/generic_service.h> #include <grpc++/impl/rpc_service_method.h> #include <grpc++/impl/service_type.h> #include <grpc++/server_context.h> #include <grpc++/server_credentials.h> #include <grpc++/thread_pool_interface.h> #include "src/cpp/proto/proto_utils.h" #include "src/cpp/util/time.h" namespace grpc { class Server::SyncRequest GRPC_FINAL : public CompletionQueueTag { public: SyncRequest(RpcServiceMethod* method, void* tag) : method_(method), tag_(tag), in_flight_(false), has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC || method->method_type() == RpcMethod::SERVER_STREAMING), has_response_payload_(method->method_type() == RpcMethod::NORMAL_RPC || method->method_type() == RpcMethod::CLIENT_STREAMING) { grpc_metadata_array_init(&request_metadata_); } static SyncRequest* Wait(CompletionQueue* cq, bool* ok) { void* tag = nullptr; *ok = false; if (!cq->Next(&tag, ok)) { return nullptr; } auto* mrd = static_cast<SyncRequest*>(tag); GPR_ASSERT(mrd->in_flight_); return mrd; } void Request(grpc_server* server) { GPR_ASSERT(!in_flight_); in_flight_ = true; cq_ = grpc_completion_queue_create(); GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_registered_call( server, tag_, &call_, &deadline_, &request_metadata_, has_request_payload_ ? &request_payload_ : nullptr, cq_, this)); } bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { if (!*status) { grpc_completion_queue_destroy(cq_); } return true; } class CallData GRPC_FINAL { public: explicit CallData(Server* server, SyncRequest* mrd) : cq_(mrd->cq_), call_(mrd->call_, server, &cq_), ctx_(mrd->deadline_, mrd->request_metadata_.metadata, mrd->request_metadata_.count), has_request_payload_(mrd->has_request_payload_), has_response_payload_(mrd->has_response_payload_), request_payload_(mrd->request_payload_), method_(mrd->method_) { ctx_.call_ = mrd->call_; GPR_ASSERT(mrd->in_flight_); mrd->in_flight_ = false; mrd->request_metadata_.count = 0; } ~CallData() { if (has_request_payload_ && request_payload_) { grpc_byte_buffer_destroy(request_payload_); } } void Run() { std::unique_ptr<grpc::protobuf::Message> req; std::unique_ptr<grpc::protobuf::Message> res; if (has_request_payload_) { req.reset(method_->AllocateRequestProto()); if (!DeserializeProto(request_payload_, req.get())) { abort(); // for now } } if (has_response_payload_) { res.reset(method_->AllocateResponseProto()); } ctx_.BeginCompletionOp(&call_); auto status = method_->handler()->RunHandler( MethodHandler::HandlerParameter(&call_, &ctx_, req.get(), res.get())); CallOpBuffer buf; if (!ctx_.sent_initial_metadata_) { buf.AddSendInitialMetadata(&ctx_.initial_metadata_); } if (has_response_payload_) { buf.AddSendMessage(*res); } buf.AddServerSendStatus(&ctx_.trailing_metadata_, status); call_.PerformOps(&buf); GPR_ASSERT(cq_.Pluck(&buf)); void* ignored_tag; bool ignored_ok; cq_.Shutdown(); GPR_ASSERT(cq_.Next(&ignored_tag, &ignored_ok) == false); } private: CompletionQueue cq_; Call call_; ServerContext ctx_; const bool has_request_payload_; const bool has_response_payload_; grpc_byte_buffer* request_payload_; RpcServiceMethod* const method_; }; private: RpcServiceMethod* const method_; void* const tag_; bool in_flight_; const bool has_request_payload_; const bool has_response_payload_; grpc_call* call_; gpr_timespec deadline_; grpc_metadata_array request_metadata_; grpc_byte_buffer* request_payload_; grpc_completion_queue* cq_; }; Server::Server(ThreadPoolInterface* thread_pool, bool thread_pool_owned) : started_(false), shutdown_(false), num_running_cb_(0), server_(grpc_server_create(cq_.cq(), nullptr)), thread_pool_(thread_pool), thread_pool_owned_(thread_pool_owned) {} Server::~Server() { std::unique_lock<std::mutex> lock(mu_); if (started_ && !shutdown_) { lock.unlock(); Shutdown(); } else { lock.unlock(); } grpc_server_destroy(server_); if (thread_pool_owned_) { delete thread_pool_; } } bool Server::RegisterService(RpcService* service) { for (int i = 0; i < service->GetMethodCount(); ++i) { RpcServiceMethod* method = service->GetMethod(i); void* tag = grpc_server_register_method(server_, method->name(), nullptr, cq_.cq()); if (!tag) { gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", method->name()); return false; } sync_methods_.emplace_back(method, tag); } return true; } bool Server::RegisterAsyncService(AsynchronousService* service) { GPR_ASSERT(service->dispatch_impl_ == nullptr && "Can only register an asynchronous service against one server."); service->dispatch_impl_ = this; service->request_args_ = new void* [service->method_count_]; for (size_t i = 0; i < service->method_count_; ++i) { void* tag = grpc_server_register_method(server_, service->method_names_[i], nullptr, service->completion_queue()->cq()); if (!tag) { gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", service->method_names_[i]); return false; } service->request_args_[i] = tag; } return true; } void Server::RegisterGenericService(GenericService* service) { GPR_ASSERT(service->server_ == nullptr && "Can only register an generic service against one server."); service->server_ = this; } int Server::AddPort(const grpc::string& addr, ServerCredentials* creds) { GPR_ASSERT(!started_); return creds->AddPortToServer(addr, server_); } bool Server::Start() { GPR_ASSERT(!started_); started_ = true; grpc_server_start(server_); // Start processing rpcs. if (!sync_methods_.empty()) { for (auto& m : sync_methods_) { m.Request(server_); } ScheduleCallback(); } return true; } void Server::Shutdown() { std::unique_lock<std::mutex> lock(mu_); if (started_ && !shutdown_) { shutdown_ = true; grpc_server_shutdown(server_); cq_.Shutdown(); // Wait for running callbacks to finish. while (num_running_cb_ != 0) { callback_cv_.wait(lock); } } } void Server::Wait() { std::unique_lock<std::mutex> lock(mu_); while (num_running_cb_ != 0) { callback_cv_.wait(lock); } } void Server::PerformOpsOnCall(CallOpBuffer* buf, Call* call) { static const size_t MAX_OPS = 8; size_t nops = MAX_OPS; grpc_op ops[MAX_OPS]; buf->FillOps(ops, &nops); GPR_ASSERT(GRPC_CALL_OK == grpc_call_start_batch(call->call(), ops, nops, buf)); } class Server::AsyncRequest GRPC_FINAL : public CompletionQueueTag { public: AsyncRequest(Server* server, void* registered_method, ServerContext* ctx, grpc::protobuf::Message* request, ServerAsyncStreamingInterface* stream, CompletionQueue* cq, void* tag) : tag_(tag), request_(request), stream_(stream), cq_(cq), ctx_(ctx), generic_ctx_(nullptr), server_(server), call_(nullptr), payload_(nullptr) { memset(&array_, 0, sizeof(array_)); grpc_call_details_init(&call_details_); grpc_server_request_registered_call( server->server_, registered_method, &call_, &call_details_.deadline, &array_, request ? &payload_ : nullptr, cq->cq(), this); } AsyncRequest(Server* server, GenericServerContext* ctx, ServerAsyncStreamingInterface* stream, CompletionQueue* cq, void* tag) : tag_(tag), request_(nullptr), stream_(stream), cq_(cq), ctx_(nullptr), generic_ctx_(ctx), server_(server), call_(nullptr), payload_(nullptr) { memset(&array_, 0, sizeof(array_)); grpc_call_details_init(&call_details_); grpc_server_request_call( server->server_, &call_, &call_details_, &array_, cq->cq(), this); } ~AsyncRequest() { if (payload_) { grpc_byte_buffer_destroy(payload_); } grpc_metadata_array_destroy(&array_); } bool FinalizeResult(void** tag, bool* status) GRPC_OVERRIDE { *tag = tag_; bool orig_status = *status; if (*status && request_) { if (payload_) { *status = DeserializeProto(payload_, request_); } else { *status = false; } } ServerContext* ctx = ctx_ ? ctx_ : generic_ctx_; GPR_ASSERT(ctx); if (*status) { ctx->deadline_ = Timespec2Timepoint(call_details_.deadline); for (size_t i = 0; i < array_.count; i++) { ctx->client_metadata_.insert(std::make_pair( grpc::string(array_.metadata[i].key), grpc::string( array_.metadata[i].value, array_.metadata[i].value + array_.metadata[i].value_length))); } if (generic_ctx_) { // TODO(yangg) remove the copy here. generic_ctx_->method_ = call_details_.method; generic_ctx_->host_ = call_details_.host; gpr_free(call_details_.method); gpr_free(call_details_.host); } } ctx->call_ = call_; Call call(call_, server_, cq_); if (orig_status && call_) { ctx->BeginCompletionOp(&call); } // just the pointers inside call are copied here stream_->BindCall(&call); delete this; return true; } private: void* const tag_; grpc::protobuf::Message* const request_; ServerAsyncStreamingInterface* const stream_; CompletionQueue* const cq_; ServerContext* const ctx_; GenericServerContext* const generic_ctx_; Server* const server_; grpc_call* call_; grpc_call_details call_details_; grpc_metadata_array array_; grpc_byte_buffer* payload_; }; void Server::RequestAsyncCall(void* registered_method, ServerContext* context, grpc::protobuf::Message* request, ServerAsyncStreamingInterface* stream, CompletionQueue* cq, void* tag) { new AsyncRequest(this, registered_method, context, request, stream, cq, tag); } void Server::RequestGenericCall(GenericServerContext* context, ServerAsyncStreamingInterface* stream, CompletionQueue* cq, void* tag) { new AsyncRequest(this, context, stream, cq, tag); } void Server::ScheduleCallback() { { std::unique_lock<std::mutex> lock(mu_); num_running_cb_++; } thread_pool_->ScheduleCallback(std::bind(&Server::RunRpc, this)); } void Server::RunRpc() { // Wait for one more incoming rpc. bool ok; auto* mrd = SyncRequest::Wait(&cq_, &ok); if (mrd) { ScheduleCallback(); if (ok) { SyncRequest::CallData cd(this, mrd); mrd->Request(server_); cd.Run(); } } { std::unique_lock<std::mutex> lock(mu_); num_running_cb_--; if (shutdown_) { callback_cv_.notify_all(); } } } } // namespace grpc <|endoftext|>
<commit_before>#pragma once #include <ShaderManager.h> namespace Rendering { namespace Factory { class [ClassName] { private: Rendering::Manager::ShaderManager *_shaderMgr; public: [ClassName](Rendering::Manager::ShaderManager*& shaderManager) { _shaderMgr = shaderManager; } ~[ClassName](void) { } public: bool LoadShader(const std::string& shaderName, const std::string& mainVSFuncName, const std::string& mainPSFuncName, const std::string* includeFileName, Shader::VertexShader** outVertexShader, Shader::PixelShader** outPixelShader) { std::string folderPath = ""; std::vector<D3D11_INPUT_ELEMENT_DESC> vertexDeclations; typedef unsigned int uint; auto AddInputElementDesc = [&](const char* semanticName, uint semanticIndex, DXGI_FORMAT format, uint alignedByteOffset, D3D11_INPUT_CLASSIFICATION inputSlotClass, uint inputSlot, uint instanceDataStepRate) { auto MakeInputElementDesc = [&](D3D11_INPUT_ELEMENT_DESC& out) { out.SemanticName = semanticName; out.SemanticIndex = semanticIndex; out.AlignedByteOffset = alignedByteOffset; out.Format = format; out.InputSlotClass = inputSlotClass; out.InputSlot = inputSlot; out.InstanceDataStepRate = instanceDataStepRate; }; D3D11_INPUT_ELEMENT_DESC desc; MakeInputElementDesc(desc); vertexDeclations.push_back(desc); }; /** Script Begin **/ /** Script End **/ const std::string baseCommand = shaderName+':'; Shader::VertexShader* vs = _shaderMgr->LoadVertexShader(folderPath, baseCommand + mainVSFuncName, true, vertexDeclations, includeFileName); Shader::PixelShader* ps = _shaderMgr->LoadPixelShader(folderPath, baseCommand + mainPSFuncName, true, includeFileName); if(outVertexShader) (*outVertexShader) = vs; if(outPixelShader) (*outPixelShader) = ps; return (vs && ps); } }; } }<commit_msg>ShaderFactoryTemplate - Macro 기능 추가 #51<commit_after>#pragma once #include <ShaderManager.h> namespace Rendering { namespace Factory { class [ClassName] { private: Rendering::Manager::ShaderManager *_shaderMgr; public: [ClassName](Rendering::Manager::ShaderManager*& shaderManager) { _shaderMgr = shaderManager; } ~[ClassName](void) { } public: bool LoadShader(const std::string& shaderName, const std::string& mainVSFuncName, const std::string& mainPSFuncName, const std::string* includeFileName, const std::vector<std::string>* includeMacros, Shader::VertexShader** outVertexShader, Shader::PixelShader** outPixelShader) { std::string folderPath = ""; std::vector<D3D11_INPUT_ELEMENT_DESC> vertexDeclations; typedef unsigned int uint; auto AddInputElementDesc = [&](const char* semanticName, uint semanticIndex, DXGI_FORMAT format, uint alignedByteOffset, D3D11_INPUT_CLASSIFICATION inputSlotClass, uint inputSlot, uint instanceDataStepRate) { auto MakeInputElementDesc = [&](D3D11_INPUT_ELEMENT_DESC& out) { out.SemanticName = semanticName; out.SemanticIndex = semanticIndex; out.AlignedByteOffset = alignedByteOffset; out.Format = format; out.InputSlotClass = inputSlotClass; out.InputSlot = inputSlot; out.InstanceDataStepRate = instanceDataStepRate; }; D3D11_INPUT_ELEMENT_DESC desc; MakeInputElementDesc(desc); vertexDeclations.push_back(desc); }; /** Script Begin **/ /** Script End **/ const std::string baseCommand = shaderName+':'; Shader::VertexShader* vs = nullptr; if(mainVSFuncName.empty() == false) vs = _shaderMgr->LoadVertexShader(folderPath, baseCommand + mainVSFuncName, true, vertexDeclations, includeFileName); Shader::PixelShader* ps = nullptr; if(mainPSFuncName.empty() == false) ps = _shaderMgr->LoadPixelShader(folderPath, baseCommand + mainPSFuncName, true, includeFileName); if(outVertexShader) (*outVertexShader) = vs; if(outPixelShader) (*outPixelShader) = ps; return (vs && ps); } }; } }<|endoftext|>
<commit_before>#include "SysControl.h" #include "ControlsApp.h" #include "ControlsXPad360.h" //ƽַ̨ #ifdef _WIN32 #pragma execution_character_set("utf-8") #endif using namespace MathLib; class CSysControlLocal : public CSysControl { public: CSysControlLocal(); virtual ~CSysControlLocal(); virtual void Init(); //ɫҪʼɫҪʼ virtual void Update(float ifps); virtual void Shutdown(); virtual int GetState(int state); //״̬״̬״̬ӵ״̬ȵȡ virtual int ClearState(int state); virtual float GetMouseDX(); virtual float GetMouseDY(); virtual void SetMouseGrab(int g); //Ƿʾ virtual int GetMouseGrab(); //ȡ״̬ʾػDzʾ״̬ virtual void SetControlMode(ControlMode mode); //ģʽ virtual ControlMode GetControlMode() const; //ȡģʽ private: void Update_Mouse(float ifps); void Update_Keyboard(float ifps); void Update_XPad360(float ifps); CControlsApp *m_pControlsApp; //Ϸƶ CControlsXPad360 *m_pControlsXPad360; ControlMode m_nControlMode; //ģʽ int m_nOldMouseX; //һX int m_nOldMouseY; //һY CObjectGui *m_pTest3DUI; CWidgetLabel *m_pTestMessageLabel; }; CSysControlLocal::CSysControlLocal() { } CSysControlLocal::~CSysControlLocal() { } void CSysControlLocal::Init() { m_pControlsApp = new CControlsApp; m_pControlsXPad360 = new CControlsXPad360(0); } <commit_msg>Signed-off-by: mrlitong <[email protected]><commit_after>#include "SysControl.h" #include "ControlsApp.h" #include "ControlsXPad360.h" //ƽַ̨ #ifdef _WIN32 #pragma execution_character_set("utf-8") #endif using namespace MathLib; class CSysControlLocal : public CSysControl { public: CSysControlLocal(); virtual ~CSysControlLocal(); virtual void Init(); //ɫҪʼɫҪʼ virtual void Update(float ifps); virtual void Shutdown(); virtual int GetState(int state); //״̬״̬״̬ӵ״̬ȵȡ virtual int ClearState(int state); virtual float GetMouseDX(); virtual float GetMouseDY(); virtual void SetMouseGrab(int g); //Ƿʾ virtual int GetMouseGrab(); //ȡ״̬ʾػDzʾ״̬ virtual void SetControlMode(ControlMode mode); //ģʽ virtual ControlMode GetControlMode() const; //ȡģʽ private: void Update_Mouse(float ifps); void Update_Keyboard(float ifps); void Update_XPad360(float ifps); CControlsApp *m_pControlsApp; //Ϸƶ CControlsXPad360 *m_pControlsXPad360; ControlMode m_nControlMode; //ģʽ int m_nOldMouseX; //һX int m_nOldMouseY; //һY CObjectGui *m_pTest3DUI; CWidgetLabel *m_pTestMessageLabel; }; CSysControlLocal::CSysControlLocal() { } CSysControlLocal::~CSysControlLocal() { } void CSysControlLocal::Init() { m_pControlsApp = new CControlsApp; m_pControlsXPad360 = new CControlsXPad360(0); m_nOldMouseX = 0; m_nOldMouseY = 0; } <|endoftext|>
<commit_before>MatrixXd ones = MatrixXd::Ones(3,3); EigenSolver<MatrixXd> es(ones); cout << "The first eigenvector of the 3x3 matrix of ones is:" << endl << es.eigenvectors().col(1) << endl; <commit_msg>Typo in the example for Eigen::SelfAdjointEigenSolver::eigenvectors, the first eigenvector should be col(0) not col(1)<commit_after>MatrixXd ones = MatrixXd::Ones(3,3); EigenSolver<MatrixXd> es(ones); cout << "The first eigenvector of the 3x3 matrix of ones is:" << endl << es.eigenvectors().col(0) << endl; <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** 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 [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/qstring.h> #include <QtCore/qdebug.h> #include <QtGui/QIcon> #include <QtCore/QDir> #include <QtCore/QDebug> #include "qgstreamerserviceplugin.h" #ifdef QMEDIA_GSTREAMER_PLAYER #include "qgstreamerplayerservice.h" #endif #if defined(QMEDIA_GSTREAMER_CAPTURE) && (defined(Q_WS_MAEMO_5) || defined(Q_WS_MAEMO_6)) #include "qgstreamercaptureservice_maemo.h" #elif defined(QMEDIA_GSTREAMER_CAPTURE) #include "qgstreamercaptureservice.h" #endif #include <qmediaserviceprovider.h> #include <linux/types.h> #include <sys/time.h> #include <sys/ioctl.h> #include <sys/poll.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> #include <linux/videodev2.h> QStringList QGstreamerServicePlugin::keys() const { return QStringList() #ifdef QMEDIA_GSTREAMER_PLAYER << QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER) #endif #ifdef QMEDIA_GSTREAMER_CAPTURE << QLatin1String(Q_MEDIASERVICE_AUDIOSOURCE) #endif ; } QMediaService* QGstreamerServicePlugin::create(const QString &key) { #ifdef QMEDIA_GSTREAMER_PLAYER if (key == QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER)) return new QGstreamerPlayerService; #endif #ifdef QMEDIA_GSTREAMER_CAPTURE if (key == QLatin1String(Q_MEDIASERVICE_AUDIOSOURCE)) return new QGstreamerCaptureService(key); #endif //qDebug() << "unsupported key:" << key; return 0; } void QGstreamerServicePlugin::release(QMediaService *service) { delete service; } Q_EXPORT_PLUGIN2(qtmedia_gstengine, QGstreamerServicePlugin); <commit_msg>Fixed compilation on maemo5<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** 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 [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtCore/qstring.h> #include <QtCore/qdebug.h> #include <QtGui/QIcon> #include <QtCore/QDir> #include <QtCore/QDebug> #include "qgstreamerserviceplugin.h" #ifdef QMEDIA_GSTREAMER_PLAYER #include "qgstreamerplayerservice.h" #endif #if defined(QMEDIA_GSTREAMER_CAPTURE) #include "qgstreamercaptureservice.h" #endif #include <qmediaserviceprovider.h> #include <linux/types.h> #include <sys/time.h> #include <sys/ioctl.h> #include <sys/poll.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <sys/mman.h> #include <linux/videodev2.h> QStringList QGstreamerServicePlugin::keys() const { return QStringList() #ifdef QMEDIA_GSTREAMER_PLAYER << QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER) #endif #ifdef QMEDIA_GSTREAMER_CAPTURE << QLatin1String(Q_MEDIASERVICE_AUDIOSOURCE) #endif ; } QMediaService* QGstreamerServicePlugin::create(const QString &key) { #ifdef QMEDIA_GSTREAMER_PLAYER if (key == QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER)) return new QGstreamerPlayerService; #endif #ifdef QMEDIA_GSTREAMER_CAPTURE if (key == QLatin1String(Q_MEDIASERVICE_AUDIOSOURCE)) return new QGstreamerCaptureService(key); #endif //qDebug() << "unsupported key:" << key; return 0; } void QGstreamerServicePlugin::release(QMediaService *service) { delete service; } Q_EXPORT_PLUGIN2(qtmedia_gstengine, QGstreamerServicePlugin); <|endoftext|>
<commit_before>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "interface.h" #include "indexreader.h" #include "combinedindexmanager.h" #include "indexwriter.h" #include "indexscheduler.h" #include "eventlistener.h" #include "streamanalyzer.h" #include "analysisresult.h" #include "analyzerconfiguration.h" #include "stringstream.h" #include "query.h" #include "queryparser.h" #include <sstream> #include <iostream> #include <vector> #include <sys/types.h> #include <signal.h> #include <unistd.h> using namespace std; using namespace Strigi; Interface::Interface(CombinedIndexManager& m, IndexScheduler& s) :ClientInterface(0), manager(m), scheduler(s), active(true) { eventListener = NULL; } void Interface::setEventListener (EventListener* eListener) { eventListener = eListener; } int Interface::countHits(const string& query) { QueryParser parser; Query q = parser.buildQuery(query); int count = manager.indexReader()->countHits(q); return count; } ClientInterface::Hits Interface::getHits(const string& query, uint32_t max, uint32_t off) { QueryParser parser; Query q = parser.buildQuery(query); Hits hits; hits.hits = manager.indexReader()->query(q, off, max); // highlight the hits in the results // TODO fix highlighting /* vector<IndexedDocument>::iterator i; for (i = hits.hits.begin(); i != hits.hits.end(); ++i) { i->fragment = q.highlight(i->fragment); }*/ return hits; } vector<string> Interface::getBackEnds() { return manager.backEnds(); } map<string, string> Interface::getStatus() { map<string,string> status; status["Status"]=scheduler.getStateString(); ostringstream out; out << scheduler.getQueueSize(); status["Documents in queue"]= out.str(); out.str(""); IndexReader* reader = manager.indexReader(); out << reader->countDocuments(); status["Documents indexed"]= out.str(); out.str(""); out << reader->countWords(); status["Unique words indexed"] = out.str(); out.str(""); out << reader->indexSize()/1024/1024; status["Index size"] = out.str()+" MB"; return status; } string Interface::stopDaemon() { cerr << "stopDaemon" << endl; active = false; // signal to all threads to quit. Do not use raise() here, because it will // cause a hang kill(getpid(), SIGINT); return ""; } string Interface::startIndexing() { scheduler.startIndexing(); return ""; } string Interface::stopIndexing() { scheduler.stopIndexing(); return ""; } set<string> Interface::getIndexedDirectories() { return scheduler.getIndexedDirectories(); } string Interface::setIndexedDirectories(set<string> dirs) { if (eventListener != NULL) eventListener->setIndexedDirectories( dirs); scheduler.setIndexedDirectories(dirs); return ""; } void Interface::setFilters(const vector<pair<bool,string> >& rules) { scheduler.getIndexerConfiguration().setFilters(rules); } vector<pair<bool,string> > Interface::getFilters() { return scheduler.getIndexerConfiguration().filters(); } void Interface::indexFile(const string &path, uint64_t mtime, const vector<char>& content) { // TODO if the file is already there, remove it first IndexWriter* writer = manager.indexWriter(); vector<string> paths; paths.push_back(path); writer->deleteEntries(paths); AnalyzerConfiguration ic; StreamAnalyzer streamindexer(ic); StringInputStream sr(&content[0], content.size(), false); AnalysisResult idx(path, mtime, *writer, streamindexer); idx.index(&sr); } vector<string> Interface::getFieldNames() { return manager.indexReader()->fieldNames(); } vector<pair<string, uint32_t> > Interface::getHistogram(const string& query, const string& field, const string& labeltype) { return manager.indexReader()->histogram(query, field, labeltype); } int32_t Interface::countKeywords(const string& keywordmatch, const vector<string>& fieldnames) { return 0; } vector<string> Interface::getKeywords(const string& keywordmatch, const vector<string>& fieldnames, uint32_t max, uint32_t offset) { return vector<string>(); } <commit_msg>Gracefully exit on dbus call "stopDaemon"<commit_after>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "interface.h" #include "indexreader.h" #include "combinedindexmanager.h" #include "indexwriter.h" #include "indexscheduler.h" #include "eventlistener.h" #include "streamanalyzer.h" #include "analysisresult.h" #include "analyzerconfiguration.h" #include "stringstream.h" #include "query.h" #include "queryparser.h" #include <sstream> #include <iostream> #include <vector> #include <sys/types.h> #include <signal.h> #include <unistd.h> using namespace std; using namespace Strigi; Interface::Interface(CombinedIndexManager& m, IndexScheduler& s) :ClientInterface(0), manager(m), scheduler(s), active(true) { eventListener = NULL; } void Interface::setEventListener (EventListener* eListener) { eventListener = eListener; } int Interface::countHits(const string& query) { QueryParser parser; Query q = parser.buildQuery(query); int count = manager.indexReader()->countHits(q); return count; } ClientInterface::Hits Interface::getHits(const string& query, uint32_t max, uint32_t off) { QueryParser parser; Query q = parser.buildQuery(query); Hits hits; hits.hits = manager.indexReader()->query(q, off, max); // highlight the hits in the results // TODO fix highlighting /* vector<IndexedDocument>::iterator i; for (i = hits.hits.begin(); i != hits.hits.end(); ++i) { i->fragment = q.highlight(i->fragment); }*/ return hits; } vector<string> Interface::getBackEnds() { return manager.backEnds(); } map<string, string> Interface::getStatus() { map<string,string> status; status["Status"]=scheduler.getStateString(); ostringstream out; out << scheduler.getQueueSize(); status["Documents in queue"]= out.str(); out.str(""); IndexReader* reader = manager.indexReader(); out << reader->countDocuments(); status["Documents indexed"]= out.str(); out.str(""); out << reader->countWords(); status["Unique words indexed"] = out.str(); out.str(""); out << reader->indexSize()/1024/1024; status["Index size"] = out.str()+" MB"; return status; } string Interface::stopDaemon() { cerr << "stopDaemon" << endl; StrigiThread::stopThreads(); return ""; } string Interface::startIndexing() { scheduler.startIndexing(); return ""; } string Interface::stopIndexing() { scheduler.stopIndexing(); return ""; } set<string> Interface::getIndexedDirectories() { return scheduler.getIndexedDirectories(); } string Interface::setIndexedDirectories(set<string> dirs) { if (eventListener != NULL) eventListener->setIndexedDirectories( dirs); scheduler.setIndexedDirectories(dirs); return ""; } void Interface::setFilters(const vector<pair<bool,string> >& rules) { scheduler.getIndexerConfiguration().setFilters(rules); } vector<pair<bool,string> > Interface::getFilters() { return scheduler.getIndexerConfiguration().filters(); } void Interface::indexFile(const string &path, uint64_t mtime, const vector<char>& content) { // TODO if the file is already there, remove it first IndexWriter* writer = manager.indexWriter(); vector<string> paths; paths.push_back(path); writer->deleteEntries(paths); AnalyzerConfiguration ic; StreamAnalyzer streamindexer(ic); StringInputStream sr(&content[0], content.size(), false); AnalysisResult idx(path, mtime, *writer, streamindexer); idx.index(&sr); } vector<string> Interface::getFieldNames() { return manager.indexReader()->fieldNames(); } vector<pair<string, uint32_t> > Interface::getHistogram(const string& query, const string& field, const string& labeltype) { return manager.indexReader()->histogram(query, field, labeltype); } int32_t Interface::countKeywords(const string& keywordmatch, const vector<string>& fieldnames) { return 0; } vector<string> Interface::getKeywords(const string& keywordmatch, const vector<string>& fieldnames, uint32_t max, uint32_t offset) { return vector<string>(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2014 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 "webrtc/modules/audio_processing/audio_processing_impl.h" #include "webrtc/config.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/audio_processing/test/test_utils.h" #include "webrtc/modules/interface/module_common_types.h" using ::testing::Invoke; using ::testing::Return; namespace webrtc { class MockInitialize : public AudioProcessingImpl { public: explicit MockInitialize(const Config& config) : AudioProcessingImpl(config) { } MOCK_METHOD0(InitializeLocked, int()); int RealInitializeLocked() { return AudioProcessingImpl::InitializeLocked(); } }; TEST(AudioProcessingImplTest, AudioParameterChangeTriggersInit) { Config config; MockInitialize mock(config); ON_CALL(mock, InitializeLocked()) .WillByDefault(Invoke(&mock, &MockInitialize::RealInitializeLocked)); EXPECT_CALL(mock, InitializeLocked()).Times(1); mock.Initialize(); AudioFrame frame; // Call with the default parameters; there should be no init. frame.num_channels_ = 1; SetFrameSampleRate(&frame, 16000); EXPECT_CALL(mock, InitializeLocked()) .Times(0); EXPECT_NOERR(mock.ProcessStream(&frame)); EXPECT_NOERR(mock.AnalyzeReverseStream(&frame)); // New sample rate. (Only impacts ProcessStream). SetFrameSampleRate(&frame, 32000); EXPECT_CALL(mock, InitializeLocked()) .Times(1); EXPECT_NOERR(mock.ProcessStream(&frame)); // New number of channels. frame.num_channels_ = 2; EXPECT_CALL(mock, InitializeLocked()) .Times(2); EXPECT_NOERR(mock.ProcessStream(&frame)); // ProcessStream sets num_channels_ == num_output_channels. frame.num_channels_ = 2; EXPECT_NOERR(mock.AnalyzeReverseStream(&frame)); // A new sample rate passed to AnalyzeReverseStream should be an error and // not cause an init. SetFrameSampleRate(&frame, 16000); EXPECT_CALL(mock, InitializeLocked()) .Times(0); EXPECT_EQ(mock.kBadSampleRateError, mock.AnalyzeReverseStream(&frame)); } } // namespace webrtc <commit_msg>Reorder includes in audio_processing_impl_unittest.<commit_after>/* * Copyright (c) 2014 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 "webrtc/modules/audio_processing/audio_processing_impl.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/config.h" #include "webrtc/modules/audio_processing/test/test_utils.h" #include "webrtc/modules/interface/module_common_types.h" using ::testing::Invoke; using ::testing::Return; namespace webrtc { class MockInitialize : public AudioProcessingImpl { public: explicit MockInitialize(const Config& config) : AudioProcessingImpl(config) { } MOCK_METHOD0(InitializeLocked, int()); int RealInitializeLocked() { return AudioProcessingImpl::InitializeLocked(); } }; TEST(AudioProcessingImplTest, AudioParameterChangeTriggersInit) { Config config; MockInitialize mock(config); ON_CALL(mock, InitializeLocked()) .WillByDefault(Invoke(&mock, &MockInitialize::RealInitializeLocked)); EXPECT_CALL(mock, InitializeLocked()).Times(1); mock.Initialize(); AudioFrame frame; // Call with the default parameters; there should be no init. frame.num_channels_ = 1; SetFrameSampleRate(&frame, 16000); EXPECT_CALL(mock, InitializeLocked()) .Times(0); EXPECT_NOERR(mock.ProcessStream(&frame)); EXPECT_NOERR(mock.AnalyzeReverseStream(&frame)); // New sample rate. (Only impacts ProcessStream). SetFrameSampleRate(&frame, 32000); EXPECT_CALL(mock, InitializeLocked()) .Times(1); EXPECT_NOERR(mock.ProcessStream(&frame)); // New number of channels. frame.num_channels_ = 2; EXPECT_CALL(mock, InitializeLocked()) .Times(2); EXPECT_NOERR(mock.ProcessStream(&frame)); // ProcessStream sets num_channels_ == num_output_channels. frame.num_channels_ = 2; EXPECT_NOERR(mock.AnalyzeReverseStream(&frame)); // A new sample rate passed to AnalyzeReverseStream should be an error and // not cause an init. SetFrameSampleRate(&frame, 16000); EXPECT_CALL(mock, InitializeLocked()) .Times(0); EXPECT_EQ(mock.kBadSampleRateError, mock.AnalyzeReverseStream(&frame)); } } // namespace webrtc <|endoftext|>
<commit_before>#include "AST/ast.h" #include "Parse/parser.h" #include "Sema/symbolcollector.h" #include "Sema/symboltable.h" #include "Sema/typechecker.h" #include "Utils/astprinter.h" // TODO: include codegen #include <iostream> static void Compile(const std::string& programFile) { TosLang::FrontEnd::Parser parser; auto programAST = parser.ParseProgram(programFile); if (programAST == nullptr) return; auto symbolTable = std::make_shared<TosLang::FrontEnd::SymbolTable>(); TosLang::FrontEnd::SymbolCollector sCollector{ symbolTable }; size_t errorCount = sCollector.Run(programAST); if (errorCount != 0) return; TosLang::FrontEnd::TypeChecker tChecker{ symbolTable }; errorCount = tChecker.Run(programAST); if (errorCount != 0) return; } static void DumpAST(const std::string& programFile) { TosLang::FrontEnd::Parser parser; auto programAST = parser.ParseProgram(programFile); if (programAST == nullptr) return; std::ostream& stream = std::cout; TosLang::Utils::ASTPrinter<std::ostream> printer(std::move(stream)); } int main(int argc, char** argv) { if (argc < 2) { std::cout << "Correct usage: tc [options] <filename>" << std::endl << "Options:" << std::endl << " -dump-ast Will output the program AST to stdout" << std::endl; } else if (argc == 2) { Compile(argv[1]); } else { if (argv[1] == "-dump-ast") { DumpAST(argv[2]); } } }<commit_msg>Finally fixing build break<commit_after>#include "AST/ast.h" #include "Parse/parser.h" #include "Sema/symbolcollector.h" #include "Sema/symboltable.h" #include "Sema/typechecker.h" #include "Utils/astprinter.h" // TODO: include codegen #include <iostream> static void Compile(const std::string& programFile) { TosLang::FrontEnd::Parser parser; auto programAST = parser.ParseProgram(programFile); if (programAST == nullptr) return; auto symbolTable = std::make_shared<TosLang::FrontEnd::SymbolTable>(); TosLang::FrontEnd::SymbolCollector sCollector{ symbolTable }; size_t errorCount = sCollector.Run(programAST); if (errorCount != 0) return; TosLang::FrontEnd::TypeChecker tChecker{ symbolTable }; errorCount = tChecker.Run(programAST); if (errorCount != 0) return; } static void DumpAST(const std::string& programFile) { TosLang::FrontEnd::Parser parser; auto programAST = parser.ParseProgram(programFile); if (programAST == nullptr) return; std::ostream& stream = std::cout; TosLang::Utils::ASTPrinter<std::ostream> printer(stream); } int main(int argc, char** argv) { if (argc < 2) { std::cout << "Correct usage: tc [options] <filename>" << std::endl << "Options:" << std::endl << " -dump-ast Will output the program AST to stdout" << std::endl; } else if (argc == 2) { Compile(argv[1]); } else { if (argv[1] == "-dump-ast") { DumpAST(argv[2]); } } }<|endoftext|>
<commit_before>#ifndef _VINECPP_HEADER_HPP_ #define _VINECPP_HEADER_HPP_ // headers #include <iostream> #include <string> #define _USE_MATH_DEFINES #include <cmath> #include <vector> #include <nlopt.hpp> #include <algorithm> #include <utility> #include <omp.h> #include <stdlib.h> #include <stdio.h> #include<fstream> #include<time.h> // headers from the boost library #include <boost/math/distributions/normal.hpp> #include <boost/math/distributions/students_t.hpp> //#include <boost/math/special_functions/detail/t_distribution_inv.hpp> #include <boost/math/tools/roots.hpp> #include <boost/random.hpp> // gsl library //#include <stdio.h> //#include <gsl/gsl_cdf.h> // User written headers #include "VineCPP_helper.hpp" #include "PC.hpp" #include "PathToBoundsAndSeed.hpp" #endif <commit_msg>float.h included<commit_after>#ifndef _VINECPP_HEADER_HPP_ #define _VINECPP_HEADER_HPP_ // headers #ifndef DBL_MAX #define DBL_MAX 1.79769e+308 #endif #include <iostream> #include <string> #define _USE_MATH_DEFINES #include <cmath> #include <vector> #include <nlopt.hpp> #include <algorithm> #include <utility> #include <omp.h> #include <stdlib.h> #include <stdio.h> #include<fstream> #include<time.h> // headers from the boost library #include <boost/math/distributions/normal.hpp> #include <boost/math/distributions/students_t.hpp> //#include <boost/math/special_functions/detail/t_distribution_inv.hpp> #include <boost/math/tools/roots.hpp> #include <boost/random.hpp> // gsl library //#include <stdio.h> //#include <gsl/gsl_cdf.h> // User written headers #include "VineCPP_helper.hpp" #include "PC.hpp" #include "PathToBoundsAndSeed.hpp" #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2013 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 "webrtc/modules/audio_coding/neteq/tools/input_audio_file.h" #include "webrtc/base/checks.h" namespace webrtc { namespace test { InputAudioFile::InputAudioFile(const std::string file_name) { fp_ = fopen(file_name.c_str(), "rb"); } InputAudioFile::~InputAudioFile() { fclose(fp_); } bool InputAudioFile::Read(size_t samples, int16_t* destination) { if (!fp_) { return false; } size_t samples_read = fread(destination, sizeof(int16_t), samples, fp_); if (samples_read < samples) { // Rewind and read the missing samples. rewind(fp_); size_t missing_samples = samples - samples_read; if (fread(destination, sizeof(int16_t), missing_samples, fp_) < missing_samples) { // Could not read enough even after rewinding the file. return false; } } return true; } bool InputAudioFile::Seek(int samples) { if (!fp_) { return false; } // Find file boundaries. const long current_pos = ftell(fp_); RTC_CHECK_NE(EOF, current_pos) << "Error returned when getting file position."; RTC_CHECK_EQ(0, fseek(fp_, 0, SEEK_END)); // Move to end of file. const long file_size = ftell(fp_); RTC_CHECK_NE(EOF, file_size) << "Error returned when getting file position."; // Find new position. long new_pos = current_pos + sizeof(int16_t) * samples; // Samples to bytes. RTC_CHECK_GE(new_pos, 0) << "Trying to move to before the beginning of the file"; new_pos = new_pos % file_size; // Wrap around the end of the file. // Move to new position relative to the beginning of the file. RTC_CHECK_EQ(0, fseek(fp_, new_pos, SEEK_SET)); return true; } void InputAudioFile::DuplicateInterleaved(const int16_t* source, size_t samples, size_t channels, int16_t* destination) { // Start from the end of |source| and |destination|, and work towards the // beginning. This is to allow in-place interleaving of the same array (i.e., // |source| and |destination| are the same array). for (int i = static_cast<int>(samples - 1); i >= 0; --i) { for (int j = static_cast<int>(channels - 1); j >= 0; --j) { destination[i * channels + j] = source[i]; } } } } // namespace test } // namespace webrtc <commit_msg>Fix a bug in InputAudioFile::Read<commit_after>/* * Copyright (c) 2013 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 "webrtc/modules/audio_coding/neteq/tools/input_audio_file.h" #include "webrtc/base/checks.h" namespace webrtc { namespace test { InputAudioFile::InputAudioFile(const std::string file_name) { fp_ = fopen(file_name.c_str(), "rb"); } InputAudioFile::~InputAudioFile() { fclose(fp_); } bool InputAudioFile::Read(size_t samples, int16_t* destination) { if (!fp_) { return false; } size_t samples_read = fread(destination, sizeof(int16_t), samples, fp_); if (samples_read < samples) { // Rewind and read the missing samples. rewind(fp_); size_t missing_samples = samples - samples_read; if (fread(destination + samples_read, sizeof(int16_t), missing_samples, fp_) < missing_samples) { // Could not read enough even after rewinding the file. return false; } } return true; } bool InputAudioFile::Seek(int samples) { if (!fp_) { return false; } // Find file boundaries. const long current_pos = ftell(fp_); RTC_CHECK_NE(EOF, current_pos) << "Error returned when getting file position."; RTC_CHECK_EQ(0, fseek(fp_, 0, SEEK_END)); // Move to end of file. const long file_size = ftell(fp_); RTC_CHECK_NE(EOF, file_size) << "Error returned when getting file position."; // Find new position. long new_pos = current_pos + sizeof(int16_t) * samples; // Samples to bytes. RTC_CHECK_GE(new_pos, 0) << "Trying to move to before the beginning of the file"; new_pos = new_pos % file_size; // Wrap around the end of the file. // Move to new position relative to the beginning of the file. RTC_CHECK_EQ(0, fseek(fp_, new_pos, SEEK_SET)); return true; } void InputAudioFile::DuplicateInterleaved(const int16_t* source, size_t samples, size_t channels, int16_t* destination) { // Start from the end of |source| and |destination|, and work towards the // beginning. This is to allow in-place interleaving of the same array (i.e., // |source| and |destination| are the same array). for (int i = static_cast<int>(samples - 1); i >= 0; --i) { for (int j = static_cast<int>(channels - 1); j >= 0; --j) { destination[i * channels + j] = source[i]; } } } } // namespace test } // namespace webrtc <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** 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 [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // User includes #include "qorganizeritemrequestqueue.h" QOrganizerItemRequestQueue* QOrganizerItemRequestQueue::instance( QOrganizerItemSymbianEngine& aOrganizerItemManagerEngine) { return new QOrganizerItemRequestQueue(aOrganizerItemManagerEngine); } QOrganizerItemRequestQueue::~QOrganizerItemRequestQueue() { // Cleanup, delete all the pointers from the hash map QMapIterator<QOrganizerItemAbstractRequest*, COrganizerItemRequestsServiceProvider*> iter(m_abstractRequestMap); // Delete all the asynch requests one by one while (iter.hasNext()) { // Advance to next item iter.next(); // It deletes the asynch request service provider delete iter.value(); } // Clear the abstract request map m_abstractRequestMap.clear(); } bool QOrganizerItemRequestQueue::startRequest( QOrganizerItemAbstractRequest* req) { // Find m_abstractRequestMap if an asynchronous service provider for request // req already exists COrganizerItemRequestsServiceProvider* requestServiceProvider( m_abstractRequestMap[req]); // asynchronous service provider does not exist, create a new one if (!requestServiceProvider) { requestServiceProvider = COrganizerItemRequestsServiceProvider::NewL( iOrganizerItemManagerEngine); m_abstractRequestMap.insert(req, requestServiceProvider); } // Start the request return requestServiceProvider->StartRequest(req); } // To cancel aReq request bool QOrganizerItemRequestQueue::cancelRequest( QOrganizerItemAbstractRequest* req) { COrganizerItemRequestsServiceProvider* requestServiceProvider( m_abstractRequestMap[req]); //Cancel the request if (requestServiceProvider) { return requestServiceProvider->CancelRequest(); } else { return false; } } // Wait for request to complete bool QOrganizerItemRequestQueue::waitForRequestFinished( QOrganizerItemAbstractRequest* req, int msecs) { Q_UNUSED(req) Q_UNUSED(msecs) // Not supported return false; } // Request is not more a valid request void QOrganizerItemRequestQueue::requestDestroyed( QOrganizerItemAbstractRequest* req) { // Get the pointer to the Asynchronous service provider for req request COrganizerItemRequestsServiceProvider* requestServiceProvider( m_abstractRequestMap[req]); if (requestServiceProvider) { // Delete the asynchronous service provider delete requestServiceProvider; // Remove req request & asynchronous service provider from the map // count is used only for the debugging purpose. Count should always be // 1, there is a serious programming mistake if not so. int count(m_abstractRequestMap.remove(req)); } } QOrganizerItemRequestQueue::QOrganizerItemRequestQueue( QOrganizerItemSymbianEngine& aOrganizerItemManagerEngine) : iOrganizerItemManagerEngine(aOrganizerItemManagerEngine) { // C++ constructor } <commit_msg>Rectified review comments in the Queue for asynch request<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** 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 [email protected]. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // User includes #include "qorganizeritemrequestqueue.h" QOrganizerItemRequestQueue* QOrganizerItemRequestQueue::instance( QOrganizerItemSymbianEngine& aOrganizerItemManagerEngine) { return new QOrganizerItemRequestQueue(aOrganizerItemManagerEngine); } QOrganizerItemRequestQueue::~QOrganizerItemRequestQueue() { // Cleanup, delete all the pointers from the hash map QMapIterator<QOrganizerItemAbstractRequest*, COrganizerItemRequestsServiceProvider*> iter(m_abstractRequestMap); // Delete all the asynch requests one by one while (iter.hasNext()) { // Advance to next item iter.next(); // It deletes the asynch request service provider delete iter.value(); } // Clear the abstract request map m_abstractRequestMap.clear(); } bool QOrganizerItemRequestQueue::startRequest( QOrganizerItemAbstractRequest* req) { // Find m_abstractRequestMap if an asynchronous service provider for request // req already exists COrganizerItemRequestsServiceProvider* requestServiceProvider( m_abstractRequestMap[req]); // asynchronous service provider does not exist, create a new one if (!requestServiceProvider) { requestServiceProvider = COrganizerItemRequestsServiceProvider::NewL( iOrganizerItemManagerEngine); m_abstractRequestMap.insert(req, requestServiceProvider); } // Start the request return requestServiceProvider->StartRequest(req); } // To cancel aReq request bool QOrganizerItemRequestQueue::cancelRequest( QOrganizerItemAbstractRequest* req) { COrganizerItemRequestsServiceProvider* requestServiceProvider( m_abstractRequestMap[req]); //Cancel the request if (requestServiceProvider) { return requestServiceProvider->CancelRequest(); } else { return false; } } // Wait for request to complete bool QOrganizerItemRequestQueue::waitForRequestFinished( QOrganizerItemAbstractRequest* req, int msecs) { Q_UNUSED(req) Q_UNUSED(msecs) // Not supported return false; } // Request is not more a valid request void QOrganizerItemRequestQueue::requestDestroyed( QOrganizerItemAbstractRequest* req) { // Get the pointer to the Asynchronous service provider for req request COrganizerItemRequestsServiceProvider* requestServiceProvider( m_abstractRequestMap[req]); if (requestServiceProvider) { // Remove req request & asynchronous service provider from the map // count is used only for the debugging purpose. Count should always be // 1, there is a serious programming mistake if not so. int count(m_abstractRequestMap.remove(req)); // Delete the asynchronous service provider delete requestServiceProvider; } } QOrganizerItemRequestQueue::QOrganizerItemRequestQueue( QOrganizerItemSymbianEngine& aOrganizerItemManagerEngine) : iOrganizerItemManagerEngine(aOrganizerItemManagerEngine) { // C++ constructor } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle 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 "paddle/fluid/operators/fusion_seq_concat_fc_op.h" #include <string> #include "paddle/fluid/operators/math/blas.h" #include "paddle/fluid/operators/math/cpu_vec.h" #include "paddle/fluid/operators/math/fc_compute.h" #include "paddle/fluid/platform/cpu_info.h" namespace paddle { namespace operators { void FusionSeqConcatFCOp::InferShape(framework::InferShapeContext* ctx) const { PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) of FusionSeqConcatFC should not be null."); PADDLE_ENFORCE(ctx->HasInput("FCWeight"), "Input(FCWeight) of FusionSeqConcatFC should not be null."); PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) of FusionSeqConcatFC should not be null."); PADDLE_ENFORCE(ctx->HasOutput("FCOut"), "Output(FCOut) of FusionSeqConcatFC should not be null."); // need check fc height = all inputs width sum auto x_dims = ctx->GetInputDim("X"); const int M = x_dims[1]; PADDLE_ENFORCE_EQ(x_dims.size(), 2, "Input(X)'s rank must be 2."); auto w_dims = ctx->GetInputDim("LSTMWeight"); const int D = w_dims[1] / 4; PADDLE_ENFORCE_EQ(w_dims.size(), 2, "Input(LSTMWeight)'s rank must be 2."); PADDLE_ENFORCE_EQ(w_dims[0], D + M, "LSTMWeight dims should be (%d + %d) * %d.", D + M, 4 * D); auto b_dims = ctx->GetInputDim("LSTMBias"); PADDLE_ENFORCE_EQ(b_dims.size(), 2, "Input(LSTMBias)'s rank must be 2."); PADDLE_ENFORCE_EQ(b_dims[0], 1, "LSTMBias dims should be 1 x %d.", 4 * D); PADDLE_ENFORCE_EQ(b_dims[1], 4 * D, "LSTMBias dims should be 1 x %d.", 4 * D); auto c_dims = ctx->GetInputDim("C0"); PADDLE_ENFORCE_EQ(c_dims.size(), 2, "Input(C0)'s rank must be 2."); PADDLE_ENFORCE_EQ(c_dims[1], D, "C0 dims should be N x %d.", D); if (ctx->HasInput("H0")) { auto h_dims = ctx->GetInputDim("H0"); PADDLE_ENFORCE(h_dims == c_dims, "The dimension of Input(H0) and Input(C0) " "should be the same."); } auto atten_w_dims = ctx->GetInputDim("AttentionWeight"); PADDLE_ENFORCE_EQ(atten_w_dims.size(), 2, "Input(AttentionWeight)'s rank must be 2."); PADDLE_ENFORCE_EQ(atten_w_dims[0], M + D, "AttentionWeight shapes must be (%d + %d) * 1.", M, D); PADDLE_ENFORCE_EQ(atten_w_dims[1], 1, "AttentionWeight shapes must be (%d + %d) * 1.", M, D); if (ctx->HasInput("AttentionBias")) { auto atten_b_dims = ctx->GetInputDim("AttentionBias"); PADDLE_ENFORCE_EQ(atten_b_dims.size(), 2, "Input(AttentionBias)'s rank must be 2."); PADDLE_ENFORCE_EQ(atten_b_dims[0], 1, "AttentionBias shapes must be 1 * 1."); PADDLE_ENFORCE_EQ(atten_b_dims[1], 1, "AttentionBias shapes must be 1 * 1."); } if (ctx->HasInput("AttentionScalar")) { auto dims = ctx->GetInputDim("AttentionScalar"); PADDLE_ENFORCE_EQ(dims.size(), 2, "Input(AttentionScalar)'s rank must be 2."); PADDLE_ENFORCE_EQ(dims[0], 1, "AttentionScalar shapes must be 1 * 1."); PADDLE_ENFORCE_EQ(dims[1], 1, "AttentionScalar shapes must be 1 * 1."); } if (ctx->HasInput("AttentionScalarBias")) { auto dims = ctx->GetInputDim("AttentionScalarBias"); PADDLE_ENFORCE( ctx->HasInput("AttentionScalar"), "AttentionScalar should not be null when have AttentionScalarBias."); PADDLE_ENFORCE_EQ(dims.size(), 2, "Input(AttentionScalarBias)'s rank must be 2."); PADDLE_ENFORCE_EQ(dims[0], 1, "AttentionScalarBias shapes must be 1 * 1."); PADDLE_ENFORCE_EQ(dims[1], 1, "AttentionScalarBias shapes must be 1 * 1."); } framework::DDim out_dims({x_dims[0], D}); ctx->SetOutputDim("Hidden", out_dims); ctx->SetOutputDim("Cell", out_dims); ctx->SetOutputDim("AttentionedX", {x_dims[0], 1}); ctx->SetOutputDim("LSTMX", {1, M}); ctx->SetOutputDim("LSTMOUT", {1, 4 * D}); // AttentionFCOut should be reshape as (maxseqlen,1) in runtime ctx->ShareLoD("X", "Hidden"); ctx->ShareLoD("X", "Cell"); ctx->SetOutputDim("Out", out_dims); ctx->ShareLoD("X", /*->*/ "Out"); } framework::OpKernelType FusionSeqConcatFCOp::GetExpectedKernelType( const framework::ExecutionContext& ctx) const { return framework::OpKernelType( framework::ToDataType(ctx.Input<framework::LoDTensor>("X")->type()), ctx.device_context()); } void FusionSeqConcatFCOpMaker::Make() { AddInput("X", "(LoDTensor) input LodDTensors, the first one must be have ref lod " "for sequence expand, and the rest input should have same lod.") .AsDuplicable(); AddInput("FCWeight", "(Tensor) the weights of fc."); AddInput("FCBias", "(Tensor, optional) the bias of fc.").AsDispensable(); AddOutput("Out", "(LoDTensor) Output LodTensor."); AddOutput( "FCOut", "(Tensor) the intermediate tensor to keep the result of fc." "Shape is (N x D), where N is the batch size, D is the output dim of fc") .AsIntermediate(); AddAttr<std::string>("fc_activation", "(string, default: identity)" "The activation for the result of fc." "`identity` by default.") .SetDefault("identity") .InEnum({"sigmoid", "tanh", "relu", "identity"}); AddComment(R"DOC( Fusion Sequence expand + concat + fc Operator. All below conditions should be meet: The ref_level of seq_expand should be 0. The ref lod of seq_expand level is the first input of concat. The other inputs should have same lod and same batch size of ref lod. The seq len of other inputs should be 1. The concat axis should be 1. )DOC"); } // y[i] = (x[i] + bias[0]) > 0 ? (x[i] + bias[0]) : 0; template <typename T> inline void bias_relu(const int n, const T* x, const T* bias, T* y) { if (bias) { math::vec_add_bias<T, platform::jit::avx>(n, *bias, x, y); math::vec_relu<T, platform::jit::avx>(n, y, y); } else { math::vec_relu<T, platform::jit::avx>(n, x, y); } } template <typename T> inline void vec_softmax(const int n, const T* x, T* y) { T scalar = x[0]; // max for (int i = 1; i < n; ++i) { scalar = scalar < x[i] ? x[i] : scalar; } math::vec_add_bias<T, platform::jit::avx>(n, -scalar, x, y); // sub math::vec_exp<T>(n, y, y); // exp // sum scalar = T(0); for (int i = 0; i < n; ++i) { scalar += y[i]; } math::vec_scal<T>(n, static_cast<T>(1) / scalar, y); // scale } template <typename T> class FusionSeqConcatFCKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { using DeviceContext = paddle::platform::CPUDeviceContext; auto* ins = ctx.Input<LoDTensor>("X"); auto* w = ctx.Input<Tensor>("FCWeight"); auto* b = ctx.Input<Tensor>("FCBias"); auto* out = ctx.Output<LoDTensor>("Out"); auto* fc_out = ctx.Output<Tensor>("FCOUT"); std::function<void(const int, const T*, T*)> fc_act; auto& fc_act_str = ctx.Attr<std::string>("fc_activation"); if (platform::jit::MayIUse(platform::jit::avx)) { math::VecActivations<T, platform::jit::avx> act_functor; fc_act = act_functor(fc_act_str); } else { math::VecActivations<T, platform::jit::isa_any> act_functor; fc_act = act_functor(fc_act_str); } PADDLE_ENFORCE_GT(ins.size(), 1, "Input(X)'s size must larger than 1."); auto* ref_in = ins[0]; auto ref_in_lod = ref_in->lod(); const int N = ref_in_lod[0].size() - 1; auto ref_in_dims = ref_in->dims(); // T x M0 auto w_dims = w->dims(); // (M0+M1+M2+..) x D const int total_T = ref_in_dims[0]; const int M0 = ref_in_dims[1]; const int M1 = ins[1]->dims()[1]; const int D = w_dims[1]; const T* ref_in_data = ref_in->data<T>(); // size should be check at infershape const T* in1_data = ins[1]->data<T>(); const T* w_data = w->data<T>(); T* out_data = out->mutable_data<T>(ctx.GetPlace()); T* fc_out_data = fc_out->mutable_data<T>(ctx.GetPlace()); auto blas = math::GetBlas<DeviceContext, T>(ctx); math::FCCompute<DeviceContext, T>(blas, total_T, D, M0, ref_in_data, w_data, out_data, b ? b->data<T>() : NULL); w_data = w_data + M0 * D; // first one use write on blas.MatMul(N, D, M1, in1_data, w_data, fc_out_data); w_data = w_data + M1 * D; for (int i = 2; i < ins.size(); ++i) { // add on const T* in_data = ins[i]->data<T>(); const int K = ins[i]->dims()[1]; blas.GEMM(CblasNoTrans, CblasNoTrans, N, D, K, static_cast<T>(1), in_data, K, w_data, D, static_cast<T>(1), fc_out_data, D); w_data = w_data + K * D; } for (int i = 0; i < N; ++i) { int seq_len = ref_in_lod[0][i + 1] - ref_in_lod[0][i]; T* src = fc_out_data + i * D; for (int step = 0; step < seq_len; ++step) { blas.VADD(D, out_data, src, out_data); out_data = out_data + D; } } fc_act(out_dims[0] * out_dims[1], out_data, out_data); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(fusion_seq_concat_fc, ops::FusionSeqConcatFCOp, ops::FusionSeqConcatFCOpMaker, paddle::framework::DefaultGradOpDescMaker<true>); REGISTER_OP_CPU_KERNEL(fusion_seq_concat_fc, ops::FusionSeqConcatFCKernel<float>, ops::FusionSeqConcatFCKernel<double>); <commit_msg>refine infershape and forward<commit_after>/* Copyright (c) 2016 PaddlePaddle 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 "paddle/fluid/operators/fusion_seq_concat_fc_op.h" #include <string> #include "paddle/fluid/operators/math/blas.h" #include "paddle/fluid/operators/math/cpu_vec.h" #include "paddle/fluid/operators/math/fc_compute.h" #include "paddle/fluid/platform/cpu_info.h" namespace paddle { namespace operators { void FusionSeqConcatFCOp::InferShape(framework::InferShapeContext* ctx) const { PADDLE_ENFORCE_GT(ctx->Inputs("X").size(), 1UL, "Inputs(X) of FusionSeqConcatFCOp should larger than 1."); PADDLE_ENFORCE(ctx->HasInput("FCWeight"), "Input(FCWeight) of FusionSeqConcatFC should not be null."); PADDLE_ENFORCE(ctx->HasOutput("Out"), "Output(Out) of FusionSeqConcatFC should not be null."); PADDLE_ENFORCE(ctx->HasOutput("FCOut"), "Output(FCOut) of FusionSeqConcatFC should not be null."); auto ins_dims = ctx->GetInputsDim("X"); auto w_dims = ctx->GetInputDim("FCWeight"); // (M0+M1+M2+..) x D PADDLE_ENFORCE_EQ(w_dims.size(), 2UL, "Input(FCWeight)'s rank must be 2."); const int D = w_dims[1]; int sum = ins_dims[0][1]; for (size_t i = 1; i < ins_dims.size(); ++i) { sum += ins_dims[i][1]; } PADDLE_ENFORCE_EQ(sum, w_dims[0], "FC height should be sum of all inputs width."); if (ctx->HasInput("FCBias")) { auto b_dims = ctx->GetInputDim("FCBias"); PADDLE_ENFORCE_EQ(b_dims.size(), 2, "Input(FCBias)'s rank must be 2."); PADDLE_ENFORCE_EQ(b_dims[0], 1, "FCBias shapes must be 1 * %d.", D); PADDLE_ENFORCE_EQ(b_dims[1], D, "FCBias shapes must be 1 * %d.", D); } ctx->SetOutputDim("Out", {ins_dims[0][0], D}); // fcout should be reshape when run since can not get lod in infershape // explicit share the ref lod ctx->ShareLoD("X", "Out", 0); } framework::OpKernelType FusionSeqConcatFCOp::GetExpectedKernelType( const framework::ExecutionContext& ctx) const { return framework::OpKernelType( framework::ToDataType(ctx.Input<framework::LoDTensor>("X")->type()), ctx.device_context()); } void FusionSeqConcatFCOpMaker::Make() { AddInput("X", "(LoDTensor) input LodDTensors, the first one must be have ref lod " "for sequence expand, and the rest input should have same lod.") .AsDuplicable(); AddInput("FCWeight", "(Tensor) the weights of fc."); AddInput("FCBias", "(Tensor, optional) the bias of fc.").AsDispensable(); AddOutput("Out", "(LoDTensor) Output LodTensor."); AddOutput( "FCOut", "(Tensor) the intermediate tensor to keep the result of fc." "Shape is (N x D), where N is the batch size, D is the output dim of fc") .AsIntermediate(); AddAttr<std::string>("fc_activation", "(string, default: identity)" "The activation for the result of fc." "`identity` by default.") .SetDefault("identity") .InEnum({"sigmoid", "tanh", "relu", "identity"}); AddComment(R"DOC( Fusion Sequence expand + concat + fc Operator. All below conditions should be meet: The ref_level of seq_expand should be 0. The ref lod of seq_expand level is the first input of concat. The other inputs should have same lod and same batch size of ref lod. The seq len of other inputs should be 1. The concat axis should be 1. )DOC"); } template <typename T> class FusionSeqConcatFCKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { using DeviceContext = paddle::platform::CPUDeviceContext; auto ins = ctx.MultiInput<LoDTensor>("X"); auto* w = ctx.Input<Tensor>("FCWeight"); auto* b = ctx.Input<Tensor>("FCBias"); auto* out = ctx.Output<LoDTensor>("Out"); auto* fc_out = ctx.Output<Tensor>("FCOUT"); auto* ref_in = ins[0]; auto ref_lod = ref_in->lod(); auto in1_lod = ins[1]->lod(); auto ref_dims = ref_in->dims(); // T x M0 auto in1_dims = ins[1]->dims(); // N x M1 auto w_dims = w->dims(); const int N = ref_lod[0].size() - 1; const int total_T = ref_dims[0]; const int M0 = ref_dims[1]; const int M1 = in1_dims[1]; const int D = w_dims[1]; // some check and fcout should be reshape here // since infershape can not get lod info PADDLE_ENFORCE_EQ(ref_lod.size(), 1UL, "Only support input lod size is 1."); PADDLE_ENFORCE_EQ(in1_lod.size(), 1UL, "Only support input lod size is 1."); PADDLE_ENFORCE_EQ(in1_lod[0].size() - 1, N, "Batch size of all inputs should be equal."); PADDLE_ENFORCE_EQ(in1_lod[0][N], N, "Seq_length of other inputs should be 1."); PADDLE_ENFORCE_EQ(in1_dims[0], N, "input height should be batch size."); for (size_t i = 2; i < ins.size(); ++i) { PADDLE_ENFORCE_EQ(ins[i]->dims()[0], N, "All other inputs height should be equal"); PADDLE_ENFORCE_EQ(ins[i]->lod(), in1_lod, "All other inputs should have same lod"); } fc_out->Resize({N, D}); std::function<void(const int, const T*, T*)> fc_act; auto& fc_act_str = ctx.Attr<std::string>("fc_activation"); if (platform::jit::MayIUse(platform::jit::avx)) { math::VecActivations<T, platform::jit::avx> act_functor; fc_act = act_functor(fc_act_str); } else { math::VecActivations<T, platform::jit::isa_any> act_functor; fc_act = act_functor(fc_act_str); } const T* ref_in_data = ref_in->data<T>(); const T* in1_data = ins[1]->data<T>(); const T* w_data = w->data<T>(); T* out_data = out->mutable_data<T>(ctx.GetPlace()); T* fc_out_data = fc_out->mutable_data<T>(ctx.GetPlace()); auto blas = math::GetBlas<DeviceContext, T>(ctx); math::FCCompute<DeviceContext, T>(blas, total_T, D, M0, ref_in_data, w_data, out_data, b ? b->data<T>() : NULL); w_data = w_data + M0 * D; // first one use write on blas.MatMul(N, D, M1, in1_data, w_data, fc_out_data); w_data = w_data + M1 * D; for (size_t i = 2; i < ins.size(); ++i) { // add on const T* in_data = ins[i]->data<T>(); const int K = ins[i]->dims()[1]; blas.GEMM(CblasNoTrans, CblasNoTrans, N, D, K, static_cast<T>(1), in_data, K, w_data, D, static_cast<T>(1), fc_out_data, D); w_data = w_data + K * D; } for (int i = 0; i < N; ++i) { int seq_len = ref_lod[0][i + 1] - ref_lod[0][i]; T* src = fc_out_data + i * D; for (int step = 0; step < seq_len; ++step) { blas.VADD(D, out_data, src, out_data); out_data = out_data + D; } } fc_act(total_T * D, out_data, out_data); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(fusion_seq_concat_fc, ops::FusionSeqConcatFCOp, ops::FusionSeqConcatFCOpMaker, paddle::framework::DefaultGradOpDescMaker<true>); REGISTER_OP_CPU_KERNEL(fusion_seq_concat_fc, ops::FusionSeqConcatFCKernel<float>, ops::FusionSeqConcatFCKernel<double>); <|endoftext|>
<commit_before>/* * Copyright 2016 Stoned Xander * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This example is not meant to simulate flocking, but only "almost" * straight line going agents and how it affects the search tree. */ #include <iostream> #include <random> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <headless-logic/searchtree.hpp> #include "../common.hpp" int loadTexture(sf::Texture &texture, std::string path) { if(!texture.loadFromFile(path)) { std::cerr << "Can't load texture '" << path << "' !" << std::endl; return 0; } texture.setSmooth(true); return 1; } class DisplayerVisitor { private: sf::Sprite *_sprite; sf::RenderWindow *_window; public: DisplayerVisitor() : _sprite(nullptr), _window(nullptr) {} void set(sf::Sprite *sprite, sf::RenderWindow *window) { _sprite = sprite; _window = window; } void init() {} void enter(const Region& region) { glm::vec4 boundary = region.boundary(); #ifdef DISPLAY_CENTER _sprite->setPosition(boundary.x + (boundary.p / 2.0), boundary.y + (boundary.q / 2.0)); _window->draw(*_sprite); #else _sprite->setPosition(boundary.x, boundary.y); _window->draw(*_sprite); _sprite->setPosition(boundary.x + boundary.p, boundary.y); _window->draw(*_sprite); _sprite->setPosition(boundary.x + boundary.p, boundary.y + boundary.q); _window->draw(*_sprite); _sprite->setPosition(boundary.x, boundary.y + boundary.q); _window->draw(*_sprite); #endif } void exit(const Region&) {} void inspect(Element **, unsigned int count) { if(count == 0) { // std::cout << "Empty leaf !" << std::endl; } if(count > 3) { std::cout << "Node Overflow !" << std::endl; } } }; #define AGENT_COUNT 256 /** * Main procedure. */ int main(void) { sf::Vector2f textureOffset(32, 32); sf::Texture agentTexture; if(!loadTexture(agentTexture, "resources/agent.png")) { return -1; } sf::Texture boundaryTexture; if(!loadTexture(boundaryTexture, "resources/cross.png")) { return -1; } sf::Sprite sprite; sf::RenderWindow window(sf::VideoMode(1024, 1024), "Crowd Control", sf::Style::Titlebar | sf::Style::Close); window.setFramerateLimit(60); DisplayerVisitor visitor; visitor.set(&sprite, &window); Region region(glm::vec4(0.0, 0.0, 1024.0, 1024.0)); Headless::Logic::SearchTree::Node<glm::vec2, Region, Element> tree(&region, 3); Element **pool = new Element*[AGENT_COUNT]; std::random_device randomDevice; std::mt19937 mt(randomDevice()); std::uniform_real_distribution<double> posDist(0.0, 1024.0); std::uniform_real_distribution<double> velDist(-128.0, 128.0); for(unsigned int i = 0; i < AGENT_COUNT; ++i) { pool[i] = new Element(glm::vec2(posDist(mt), posDist(mt)), std::string("Agent#").append(std::to_string(i))); pool[i]->velocity(glm::vec2(velDist(mt), velDist(mt))); tree.add(pool[i]); } sf::Clock clock; sf::Time elapsed; glm::vec2 target; glm::vec2 velocity; while (window.isOpen()) { // Logic update elapsed = clock.restart(); float sec = elapsed.asSeconds(); for(unsigned int i = 0; i < AGENT_COUNT; ++i) { target = pool[i]->key(); velocity = pool[i]->velocity(); target.x += velocity.x * sec; target.y += velocity.y * sec; if(target.x < 0 || target.y < 0 || target.x > 1024.0 || target.y > 1024.0) { target.x = posDist(mt); target.y = posDist(mt); velocity.x = velDist(mt); velocity.y = velDist(mt); pool[i]->velocity(velocity); } tree.move(pool[i], target); } // Event handling. sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } } // Draw window.clear(sf::Color::Black); sf::Vector2i localPosition = sf::Mouse::getPosition(window); sprite.setTexture(agentTexture); sprite.setOrigin(textureOffset); sprite.setColor(sf::Color(0, 255, 0)); sprite.setPosition(localPosition.x, localPosition.y); sprite.setScale(sf::Vector2f(.5f, .5f)); window.draw(sprite); sprite.setColor(sf::Color(0, 128, 255)); for(unsigned int i = 0; i < AGENT_COUNT; ++i) { glm::vec2 pos = pool[i]->key(); sprite.setPosition(pos.x, pos.y); window.draw(sprite); } sprite.setColor(sf::Color(255, 255, 255, 32)); sprite.setTexture(boundaryTexture); tree.visit(visitor); window.display(); } // Clean exit. return 0; } <commit_msg>Added crowd-ish behaviour. In fact, it is just a search result with mean vector.<commit_after>/* * Copyright 2016 Stoned Xander * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This example is not meant to simulate flocking, but only "almost" * straight line going agents and how it affects the search tree. */ #include <iostream> #include <random> #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <headless-logic/searchtree.hpp> #include "../common.hpp" int loadTexture(sf::Texture &texture, std::string path) { if(!texture.loadFromFile(path)) { std::cerr << "Can't load texture '" << path << "' !" << std::endl; return 0; } texture.setSmooth(true); return 1; } class DisplayerVisitor { private: sf::Sprite *_sprite; sf::RenderWindow *_window; public: DisplayerVisitor() : _sprite(nullptr), _window(nullptr) {} void set(sf::Sprite *sprite, sf::RenderWindow *window) { _sprite = sprite; _window = window; } void init() {} void enter(const Region& region) { glm::vec4 boundary = region.boundary(); #ifdef DISPLAY_CENTER _sprite->setPosition(boundary.x + (boundary.p / 2.0), boundary.y + (boundary.q / 2.0)); _window->draw(*_sprite); #else _sprite->setPosition(boundary.x, boundary.y); _window->draw(*_sprite); _sprite->setPosition(boundary.x + boundary.p, boundary.y); _window->draw(*_sprite); _sprite->setPosition(boundary.x + boundary.p, boundary.y + boundary.q); _window->draw(*_sprite); _sprite->setPosition(boundary.x, boundary.y + boundary.q); _window->draw(*_sprite); #endif } void exit(const Region&) {} void inspect(Element **, unsigned int count) { if(count == 0) { // std::cout << "Empty leaf !" << std::endl; } if(count > 3) { std::cout << "Node Overflow !" << std::endl; } } }; #define AGENT_COUNT 256 /** * Main procedure. */ int main(void) { sf::Vector2f textureOffset(32, 32); sf::Texture agentTexture; if(!loadTexture(agentTexture, "resources/agent.png")) { return -1; } sf::Texture boundaryTexture; if(!loadTexture(boundaryTexture, "resources/cross.png")) { return -1; } sf::Sprite sprite; sf::RenderWindow window(sf::VideoMode(1024, 1024), "Crowd Control", sf::Style::Titlebar | sf::Style::Close); window.setFramerateLimit(60); DisplayerVisitor visitor; visitor.set(&sprite, &window); Region region(glm::vec4(0.0, 0.0, 1024.0, 1024.0)); Headless::Logic::SearchTree::Node<glm::vec2, Region, Element> tree(&region, 3); Element **pool = new Element*[AGENT_COUNT]; Element **searchResult = new Element*[AGENT_COUNT]; std::random_device randomDevice; std::mt19937 mt(randomDevice()); std::uniform_real_distribution<double> posDist(0.0, 1024.0); std::uniform_real_distribution<double> velDist(-128.0, 128.0); for(unsigned int i = 0; i < AGENT_COUNT; ++i) { pool[i] = new Element(glm::vec2(posDist(mt), posDist(mt)), std::string("Agent#").append(std::to_string(i))); pool[i]->velocity(glm::vec2(velDist(mt), velDist(mt))); tree.add(pool[i]); } sf::Clock clock; sf::Time elapsed; glm::vec2 target; glm::vec2 velocity; Disc searchDisc; while (window.isOpen()) { // Logic update elapsed = clock.restart(); float sec = elapsed.asSeconds(); for(unsigned int i = 0; i < AGENT_COUNT; ++i) { target = pool[i]->key(); velocity = pool[i]->velocity(); target.x += velocity.x * sec; target.y += velocity.y * sec; if(target.x < 0 || target.y < 0 || target.x > 1024.0 || target.y > 1024.0) { target.x = posDist(mt); target.y = posDist(mt); velocity.x = velDist(mt); velocity.y = velDist(mt); pool[i]->velocity(velocity); } tree.move(pool[i], target); // Search neighbor and take mean velocity. searchDisc.set(target, 32.0); unsigned int count = tree.retrieve(searchDisc, searchResult, AGENT_COUNT); glm::vec2 meanVelocity(0.0, 0.0); for(unsigned int j = 0; j < count; ++j) { meanVelocity += searchResult[j]->velocity(); } if(count > 0) { meanVelocity.x /= (double) count; meanVelocity.y /= (double) count; pool[i]->velocity(meanVelocity); } } // Event handling. sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } } // Draw window.clear(sf::Color::Black); sf::Vector2i localPosition = sf::Mouse::getPosition(window); sprite.setTexture(agentTexture); sprite.setOrigin(textureOffset); sprite.setColor(sf::Color(0, 255, 0)); sprite.setPosition(localPosition.x, localPosition.y); sprite.setScale(sf::Vector2f(.5f, .5f)); window.draw(sprite); sprite.setColor(sf::Color(0, 128, 255)); for(unsigned int i = 0; i < AGENT_COUNT; ++i) { glm::vec2 pos = pool[i]->key(); sprite.setPosition(pos.x, pos.y); window.draw(sprite); } sprite.setColor(sf::Color(255, 255, 255, 32)); sprite.setTexture(boundaryTexture); tree.visit(visitor); window.display(); } // Clean Exit. for(unsigned int i = 0; i < AGENT_COUNT; ++i) { delete pool[i]; } delete []pool; delete []searchResult; return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2008, 2009 Nokia Corporation. * * Contact: Marius Vollmer <[email protected]> * * 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., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <QtTest/QtTest> #include <QtCore> #include <stdlib.h> #include "context.h" #include "contextc.h" #include "contextgroup.h" QList<Context*> contextList; QList<ContextGroup*> contextGroupList; QString *lastBusName = NULL; QStringList *lastKeysList = NULL; QDBusConnection::BusType lastConnectionType; QVariant *lastVariantSet = NULL; int lastSubscribed = 0; void *lastUserData = NULL; /* Mocked implementation of ContextGroup */ ContextGroup::ContextGroup(QStringList propertiesToWatch, QObject *parent) : keyList(propertiesToWatch) { contextGroupList.append(this); } ContextGroup::~ContextGroup() { contextGroupList.removeAll(this); } void ContextGroup::fakeFirst() { emit firstSubscriberAppeared(); } void ContextGroup::fakeLast() { emit lastSubscriberDisappeared(); } /* Mocked implementation of Context */ void resetVariants() { delete lastVariantSet; lastVariantSet = NULL; } void emitFirstOn(const QString &k) { foreach (Context* c, contextList) { if (c->getKey() == k) c->fakeFirst(); } foreach (ContextGroup* cg, contextGroupList) { if (cg->keyList.contains(k)) cg->fakeFirst(); } } void emitLastOn(const QString &k) { foreach (Context* c, contextList) { if (c->getKey() == k) c->fakeLast(); } foreach (ContextGroup* cg, contextGroupList) { if (cg->keyList.contains(k)) cg->fakeLast(); } } bool Context::initService(QDBusConnection::BusType busType, const QString &busName, const QStringList &keys) { if (lastBusName && lastBusName == busName) return false; delete lastBusName; lastBusName = new QString(busName); delete lastKeysList; lastKeysList = new QStringList(keys); lastConnectionType = busType; return true; } void Context::stopService(const QString &name) { if (lastBusName && name == lastBusName) { delete lastBusName; lastBusName = NULL; delete lastKeysList; lastKeysList = NULL; } } void Context::set(const QVariant &v) { delete lastVariantSet; lastVariantSet = new QVariant(v); } void Context::unset() { delete lastVariantSet; lastVariantSet = NULL; } Context::Context(const QString &name, QObject *obj) : QObject(obj), key(name) { delete lastVariantSet; lastVariantSet = NULL; contextList.append(this); } Context::~Context() { contextList.removeAll(this); } QString Context::getKey() { return key; } void Context::fakeFirst() { emit firstSubscriberAppeared(key); } void Context::fakeLast() { emit lastSubscriberDisappeared(key); } class ContextCUnitTest : public QObject { Q_OBJECT private slots: void init(); void startStopStart(); void installKey(); void installGroup(); /* void isValid(); void isSet(); void unset(); void getKey(); void setGetInt(); void setGetBool(); void setGetString(); void setGetDouble(); */ }; void MagicCallback(int subscribed, void *user_data) { lastSubscribed = subscribed; lastUserData = user_data; } // Before each test void ContextCUnitTest::init() { context_provider_stop(); int res = context_provider_init(DBUS_BUS_SESSION, "com.test.provider"); QCOMPARE(res, 1); QCOMPARE(*lastBusName, QString("com.test.provider")); QCOMPARE(lastKeysList->size(), 0); QCOMPARE(lastConnectionType, QDBusConnection::SessionBus); } void ContextCUnitTest::startStopStart() { context_provider_stop(); QCOMPARE(context_provider_init(DBUS_BUS_SESSION, "com.test.provider"), 1); QCOMPARE(context_provider_init(DBUS_BUS_SESSION, "com.test.provider"), 0); context_provider_stop(); QCOMPARE(context_provider_init(DBUS_BUS_SESSION, "com.test.provider"), 1); } void ContextCUnitTest::installKey() { context_provider_install_key("Battery.OnBattery", 0, MagicCallback, this); context_provider_install_key("Battery.Power", 0, MagicCallback, this); QVERIFY(lastKeysList->contains("Battery.OnBattery")); QVERIFY(lastKeysList->contains("Battery.Power")); QCOMPARE(lastKeysList->length(), 2); emitFirstOn("Battery.OnBattery"); QCOMPARE(lastSubscribed, 1); QCOMPARE(lastUserData, this); emitLastOn("Battery.Power"); QCOMPARE(lastSubscribed, 0); QCOMPARE(lastUserData, this); emitFirstOn("Battery.Something"); QCOMPARE(lastSubscribed, 0); QCOMPARE(lastUserData, this); } void ContextCUnitTest::installGroup() { const char *keys[3]; keys[0] = "Location.Lat"; keys[1] = "Location.Lon"; keys[2] = NULL; context_provider_install_group(keys, 0, MagicCallback, this); QVERIFY(lastKeysList->contains("Location.Lat")); QVERIFY(lastKeysList->contains("Location.Lon")); QCOMPARE(lastKeysList->length(), 2); emitFirstOn("Location.Lat"); QCOMPARE(lastSubscribed, 1); QCOMPARE(lastUserData, this); emitLastOn("Location.Lat"); QCOMPARE(lastSubscribed, 0); QCOMPARE(lastUserData, this); } /* void ContextCUnitTest::isValid({ ContextPtr *c1 = context_new("Battery.OnBattery"); QCOMPARE(context_is_valid(c1), 1); context_free(c1); ContextPtr *c2 = context_new("Battery.SomethingWeird"); QCOMPARE(context_is_valid(c2), 0); context_free(c2); } void ContextCUnitTest::isSet() { resetVariants(); ContextPtr *c = context_new("Battery.OnBattery"); QCOMPARE(context_is_set(c), 0); context_set_int(c, 999); QCOMPARE(context_is_set(c), 1); context_free(c); } void ContextCUnitTest::unset() { resetVariants(); ContextPtr *c = context_new("Battery.OnBattery"); QCOMPARE(context_is_set(c), 0); context_set_int(c, 999); QCOMPARE(context_is_set(c), 1); context_unset(c); QCOMPARE(context_is_set(c), 0); context_free(c); } void ContextCUnitTest::getKey() { ContextPtr *c = context_new("Battery.OnBattery"); char *k = context_get_key(c); QVERIFY(strcmp(k, "Battery.OnBattery") == 0); context_free(c); } void ContextCUnitTest::setGetInt() { int v; ContextPtr *c = context_new("Battery.OnBattery"); QCOMPARE(context_get_int(c, &v), 0); QCOMPARE(v, 0); context_set_int(c, 666); QCOMPARE(*lastVariantSet, QVariant(666)); QCOMPARE(context_get_int(c, &v), 1); QCOMPARE(v, 666); context_free(c); } void ContextCUnitTest::setGetDouble() { double v; ContextPtr *c = context_new("Battery.OnBattery"); QCOMPARE(context_get_double(c, &v), 0); QCOMPARE(v, 0.0); context_set_double(c, 0.666); QCOMPARE(*lastVariantSet, QVariant(0.666)); QCOMPARE(context_get_double(c, &v), 1); QCOMPARE(v, 0.666); context_free(c); } void ContextCUnitTest::setGetString() { char *v; ContextPtr *c = context_new("Battery.OnBattery"); QCOMPARE(context_get_string(c, &v), 0); QVERIFY(v == NULL); context_set_string(c, "Hello!"); QCOMPARE(*lastVariantSet, QVariant(QString("Hello!"))); QCOMPARE(context_get_string(c, &v), 1); QVERIFY(v != NULL); QVERIFY(strcmp(v, "Hello!") == 0); free(v); context_free(c); } void ContextCUnitTest::setGetBool() { int v; ContextPtr *c = context_new("Battery.OnBattery"); QCOMPARE(context_get_bool(c, &v), 0); QCOMPARE(v, 0); context_set_bool(c, 1); QCOMPARE(*lastVariantSet, QVariant(true)); QCOMPARE(context_get_bool(c, &v), 1); QCOMPARE(v, 1); context_free(c); } */ #include "contextcunittest.moc" QTEST_MAIN(ContextCUnitTest); <commit_msg>Cleanups.<commit_after>/* * Copyright (C) 2008, 2009 Nokia Corporation. * * Contact: Marius Vollmer <[email protected]> * * 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., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include <QtTest/QtTest> #include <QtCore> #include <stdlib.h> #include "context.h" #include "contextc.h" #include "contextgroup.h" QList<Context*> contextList; QList<ContextGroup*> contextGroupList; QString *lastBusName = NULL; QStringList *lastKeysList = NULL; QDBusConnection::BusType lastConnectionType; QVariant *lastVariantSet = NULL; int lastSubscribed = 0; void *lastUserData = NULL; /* Mocked implementation of ContextGroup */ ContextGroup::ContextGroup(QStringList propertiesToWatch, QObject *parent) : keyList(propertiesToWatch) { contextGroupList.append(this); } ContextGroup::~ContextGroup() { contextGroupList.removeAll(this); } void ContextGroup::fakeFirst() { emit firstSubscriberAppeared(); } void ContextGroup::fakeLast() { emit lastSubscriberDisappeared(); } /* Mocked implementation of Context */ void resetVariants() { delete lastVariantSet; lastVariantSet = NULL; } void emitFirstOn(const QString &k) { foreach (Context* c, contextList) { if (c->getKey() == k) c->fakeFirst(); } foreach (ContextGroup* cg, contextGroupList) { if (cg->keyList.contains(k)) cg->fakeFirst(); } } void emitLastOn(const QString &k) { foreach (Context* c, contextList) { if (c->getKey() == k) c->fakeLast(); } foreach (ContextGroup* cg, contextGroupList) { if (cg->keyList.contains(k)) cg->fakeLast(); } } bool Context::initService(QDBusConnection::BusType busType, const QString &busName, const QStringList &keys) { if (lastBusName && lastBusName == busName) return false; delete lastBusName; lastBusName = new QString(busName); delete lastKeysList; lastKeysList = new QStringList(keys); lastConnectionType = busType; return true; } void Context::stopService(const QString &name) { if (lastBusName && name == lastBusName) { delete lastBusName; lastBusName = NULL; delete lastKeysList; lastKeysList = NULL; } } void Context::set(const QVariant &v) { delete lastVariantSet; lastVariantSet = new QVariant(v); } void Context::unset() { delete lastVariantSet; lastVariantSet = NULL; } Context::Context(const QString &name, QObject *obj) : QObject(obj), key(name) { delete lastVariantSet; lastVariantSet = NULL; contextList.append(this); } Context::~Context() { contextList.removeAll(this); } QString Context::getKey() { return key; } void Context::fakeFirst() { emit firstSubscriberAppeared(key); } void Context::fakeLast() { emit lastSubscriberDisappeared(key); } class ContextCUnitTest : public QObject { Q_OBJECT private slots: void init(); void startStopStart(); void installKey(); void installGroup(); }; void MagicCallback(int subscribed, void *user_data) { lastSubscribed = subscribed; lastUserData = user_data; } // Before each test void ContextCUnitTest::init() { context_provider_stop(); int res = context_provider_init(DBUS_BUS_SESSION, "com.test.provider"); QCOMPARE(res, 1); QCOMPARE(*lastBusName, QString("com.test.provider")); QCOMPARE(lastKeysList->size(), 0); QCOMPARE(lastConnectionType, QDBusConnection::SessionBus); } void ContextCUnitTest::startStopStart() { context_provider_stop(); QCOMPARE(context_provider_init(DBUS_BUS_SESSION, "com.test.provider"), 1); QCOMPARE(context_provider_init(DBUS_BUS_SESSION, "com.test.provider"), 0); context_provider_stop(); QCOMPARE(context_provider_init(DBUS_BUS_SESSION, "com.test.provider"), 1); } void ContextCUnitTest::installKey() { context_provider_install_key("Battery.OnBattery", 0, MagicCallback, this); context_provider_install_key("Battery.Power", 0, MagicCallback, this); QVERIFY(lastKeysList->contains("Battery.OnBattery")); QVERIFY(lastKeysList->contains("Battery.Power")); QCOMPARE(lastKeysList->length(), 2); emitFirstOn("Battery.OnBattery"); QCOMPARE(lastSubscribed, 1); QCOMPARE(lastUserData, this); emitLastOn("Battery.Power"); QCOMPARE(lastSubscribed, 0); QCOMPARE(lastUserData, this); emitFirstOn("Battery.Something"); QCOMPARE(lastSubscribed, 0); QCOMPARE(lastUserData, this); } void ContextCUnitTest::installGroup() { const char *keys[3]; keys[0] = "Location.Lat"; keys[1] = "Location.Lon"; keys[2] = NULL; context_provider_install_group(keys, 0, MagicCallback, this); QVERIFY(lastKeysList->contains("Location.Lat")); QVERIFY(lastKeysList->contains("Location.Lon")); QCOMPARE(lastKeysList->length(), 2); emitFirstOn("Location.Lat"); QCOMPARE(lastSubscribed, 1); QCOMPARE(lastUserData, this); emitLastOn("Location.Lat"); QCOMPARE(lastSubscribed, 0); QCOMPARE(lastUserData, this); } #include "contextcunittest.moc" QTEST_MAIN(ContextCUnitTest); <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved */ #ifndef _Stroika_Foundation_IO_Network_InternetAddress_inl_ #define _Stroika_Foundation_IO_Network_InternetAddress_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../../Configuration/Endian.h" #include "../../Memory/Bits.h" namespace Stroika::Foundation::IO::Network { /* ******************************************************************************** *********************** IO::Network::InternetAddress *************************** ******************************************************************************** */ constexpr InternetAddress::InternetAddress () : fAddressFamily_{AddressFamily::UNKNOWN} , fV4_{} { } constexpr InternetAddress::InternetAddress (const in_addr_t& i) : fAddressFamily_ (AddressFamily::V4) #if qPlatform_POSIX , fV4_ { i } #elif qPlatform_Windows , fV4_ { in_addr { { static_cast<uint8_t> (Memory::BitSubstring (i, 0, 8)), static_cast<uint8_t> (Memory::BitSubstring (i, 8, 16)), static_cast<uint8_t> (Memory::BitSubstring (i, 16, 24)), static_cast<uint8_t> (Memory::BitSubstring (i, 24, 32)) } } } #endif { #if qPlatform_Windows Assert (fV4_.s_addr == i); #endif } inline InternetAddress::InternetAddress (const in_addr_t& i, ByteOrder byteOrder) : fAddressFamily_ (AddressFamily::V4) #if qPlatform_POSIX , fV4_ { i } #endif { #if qPlatform_Windows fV4_.s_addr = i; #endif if (byteOrder == ByteOrder::Host) { fV4_.s_addr = htonl (fV4_.s_addr); //NB no ':' cuz some systems use macro } } inline constexpr InternetAddress::InternetAddress (const in_addr& i) : fAddressFamily_{AddressFamily::V4} , fV4_{i} { } inline InternetAddress::InternetAddress (const in_addr& i, ByteOrder byteOrder) : fAddressFamily_{AddressFamily::V4} , fV4_{i} { if (byteOrder == ByteOrder::Host) { fV4_.s_addr = htonl (fV4_.s_addr); //NB no ':' cuz some systems use macro } } constexpr InternetAddress::InternetAddress (byte octet1, byte octet2, byte octet3, byte octet4) : InternetAddress (array<byte, 4>{octet1, octet2, octet3, octet4}) { } constexpr InternetAddress::InternetAddress (uint8_t octet1, uint8_t octet2, uint8_t octet3, uint8_t octet4) : InternetAddress (array<uint8_t, 4>{octet1, octet2, octet3, octet4}) { } constexpr InternetAddress::InternetAddress (tuple<uint8_t, uint8_t, uint8_t, uint8_t> octets) : InternetAddress (array<uint8_t, 4>{get<0> (octets), get<1> (octets), get<2> (octets), get<3> (octets)}) { } constexpr InternetAddress::InternetAddress (array<uint8_t, 4> octets, AddressFamily af) : fAddressFamily_{af} , fArray_4_uint_{octets} { } constexpr InternetAddress::InternetAddress (array<byte, 4> octets, AddressFamily af) : fAddressFamily_{af} , fArray_4_byte_{octets} { } constexpr InternetAddress::InternetAddress (const in6_addr& i) : fAddressFamily_ (AddressFamily::V6) , fV6_{i} { } constexpr InternetAddress::InternetAddress (array<uint8_t, 16> octets, AddressFamily af) : fAddressFamily_{af} , fArray_16_uint_{octets} { } constexpr InternetAddress::InternetAddress (array<byte, 16> octets, AddressFamily af) : fAddressFamily_{af} , fArray_16_byte_{octets} { } template <typename ITERABLE_OF_UINT8OrByte, enable_if_t<Configuration::IsIterableOfT_v<ITERABLE_OF_UINT8OrByte, byte> or Configuration::IsIterableOfT_v<ITERABLE_OF_UINT8OrByte, uint8_t>>*> inline InternetAddress::InternetAddress (ITERABLE_OF_UINT8OrByte octets, AddressFamily af) : fAddressFamily_{af} { Require (af != AddressFamily::V4 or octets.size () == 4); Require (af != AddressFamily::V6 or octets.size () == 16); size_t i = 0; for (auto b : octets) { fArray_16_uint_[i++] = static_cast<uint8_t> (b); } } constexpr bool InternetAddress::empty () const { return fAddressFamily_ == AddressFamily::UNKNOWN; } inline void InternetAddress::clear () { fAddressFamily_ = AddressFamily::UNKNOWN; } constexpr InternetAddress::AddressFamily InternetAddress::GetAddressFamily () const { return fAddressFamily_; } constexpr optional<size_t> InternetAddress::GetAddressSize () const { switch (GetAddressFamily ()) { case AddressFamily::V4: return 4; case AddressFamily::V6: return 16; default: return nullopt; } } template <> String InternetAddress::As<String> () const; #if qPlatform_POSIX template <> inline in_addr_t InternetAddress::As<in_addr_t> () const { Require (fAddressFamily_ == AddressFamily::V4); return fV4_.s_addr; } #endif template <> constexpr in_addr InternetAddress::As<in_addr> () const { Require (fAddressFamily_ == AddressFamily::V4); return fV4_; } template <> constexpr array<uint8_t, 4> InternetAddress::As<array<uint8_t, 4>> () const { Require (GetAddressSize () == 4u); return fArray_4_uint_; } template <> constexpr array<byte, 4> InternetAddress::As<array<byte, 4>> () const { Require (GetAddressSize () == 4u); return fArray_4_byte_; } template <> constexpr array<uint8_t, 16> InternetAddress::As<array<uint8_t, 16>> () const { Require (GetAddressSize () == 16u); return fArray_16_uint_; } template <> constexpr array<byte, 16> InternetAddress::As<array<byte, 16>> () const { Require (GetAddressSize () == 16u); return fArray_16_byte_; } template <> inline vector<byte> InternetAddress::As<vector<byte>> () const { Require (GetAddressSize ().has_value ()); Assert (*GetAddressSize () <= 16); return vector<byte>{fArray_16_byte_.begin (), fArray_16_byte_.begin () + *GetAddressSize ()}; } template <> inline vector<uint8_t> InternetAddress::As<vector<uint8_t>> () const { Require (GetAddressSize ().has_value ()); Assert (*GetAddressSize () <= 16); return vector<uint8_t>{fArray_16_uint_.begin (), fArray_16_uint_.begin () + *GetAddressSize ()}; } template <> [[deprecated ("array<byte,4> works better so this is deprecated since Stroika v2.1d13")]] inline tuple<uint8_t, uint8_t, uint8_t, uint8_t> InternetAddress::As<tuple<uint8_t, uint8_t, uint8_t, uint8_t>> () const { Require (fAddressFamily_ == AddressFamily::V4); switch (Configuration::GetEndianness ()) { case Configuration::Endian::eLittleByte: return make_tuple<uint8_t, uint8_t, uint8_t, uint8_t> ( static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 0, 8)), static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 8, 16)), static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 16, 24)), static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 24, 32))); case Configuration::Endian::eBigByte: return make_tuple<uint8_t, uint8_t, uint8_t, uint8_t> ( static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 24, 32)), static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 16, 24)), static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 8, 16)), static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 0, 8))); default: AssertNotImplemented (); return tuple<uint8_t, uint8_t, uint8_t, uint8_t>{}; } } template <> constexpr in6_addr InternetAddress::As<in6_addr> () const { Require (fAddressFamily_ == AddressFamily::V6); return fV6_; } template <> inline in_addr InternetAddress::As<in_addr> (ByteOrder byteOrder) const { Require (fAddressFamily_ == AddressFamily::V4); if (byteOrder == ByteOrder::Network) { return fV4_; } else { in_addr tmp = fV4_; tmp.s_addr = ntohl (tmp.s_addr); return tmp; } } /* ******************************************************************************** ********************** InternetAddress::ThreeWayComparer *********************** ******************************************************************************** */ constexpr int InternetAddress::ThreeWayComparer::operator() (const InternetAddress& lhs, const InternetAddress& rhs) const { if (int cmp = Common::ThreeWayCompare (lhs.fAddressFamily_, rhs.fAddressFamily_)) { return cmp; } switch (lhs.fAddressFamily_) { case AddressFamily::UNKNOWN: { return 0; } break; case AddressFamily::V4: { return Common::COMPARE_EQUAL (lhs.fArray_4_uint_.begin (), lhs.fArray_4_uint_.end (), rhs.fArray_4_uint_.begin ()); } break; case AddressFamily::V6: { return Common::COMPARE_EQUAL (lhs.fArray_16_uint_.begin (), lhs.fArray_16_uint_.end (), rhs.fArray_16_uint_.begin ()); } break; } //AssertNotReached (); @todo - this really should be an assertion failure, but tricky cuz constexpr function could fix with template) return 0; } /* ******************************************************************************** ************************* InternetAddress operators **************************** ******************************************************************************** */ inline bool operator< (const InternetAddress& lhs, const InternetAddress& rhs) { return Common::ThreeWayCompare (lhs, rhs) < 0; } inline bool operator<= (const InternetAddress& lhs, const InternetAddress& rhs) { return Common::ThreeWayCompare (lhs, rhs) <= 0; } inline bool operator== (const InternetAddress& lhs, const InternetAddress& rhs) { return Common::ThreeWayCompare (lhs, rhs) == 0; } inline bool operator!= (const InternetAddress& lhs, const InternetAddress& rhs) { return Common::ThreeWayCompare (lhs, rhs) != 0; } inline bool operator>= (const InternetAddress& lhs, const InternetAddress& rhs) { return Common::ThreeWayCompare (lhs, rhs) >= 0; } inline bool operator> (const InternetAddress& lhs, const InternetAddress& rhs) { return Common::ThreeWayCompare (lhs, rhs) > 0; } namespace V4 { constexpr InternetAddress kAddrAny{in_addr{}}; } namespace V6 { constexpr InternetAddress kAddrAny{in6_addr{}}; } namespace V4 { constexpr InternetAddress kLocalhost{0x7f, 0x0, 0x0, 0x1}; } namespace V6 { constexpr InternetAddress kLocalhost{in6_addr{{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}}}; } namespace V6 { constexpr InternetAddress kV4MappedLocalhost{in6_addr{{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x7f, 0, 0, 1}}}}; } } #endif /*_Stroika_Foundation_IO_Network_InternetAddress_inl_*/ <commit_msg>use Memory::MemCmp not Common::COMPARE_EQUAL () - was wrong anyhow<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2019. All rights reserved */ #ifndef _Stroika_Foundation_IO_Network_InternetAddress_inl_ #define _Stroika_Foundation_IO_Network_InternetAddress_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../../Configuration/Endian.h" #include "../../Memory/Bits.h" #include "../../Memory/Common.h" namespace Stroika::Foundation::IO::Network { /* ******************************************************************************** *********************** IO::Network::InternetAddress *************************** ******************************************************************************** */ constexpr InternetAddress::InternetAddress () : fAddressFamily_{AddressFamily::UNKNOWN} , fV4_{} { } constexpr InternetAddress::InternetAddress (const in_addr_t& i) : fAddressFamily_ (AddressFamily::V4) #if qPlatform_POSIX , fV4_ { i } #elif qPlatform_Windows , fV4_ { in_addr { { static_cast<uint8_t> (Memory::BitSubstring (i, 0, 8)), static_cast<uint8_t> (Memory::BitSubstring (i, 8, 16)), static_cast<uint8_t> (Memory::BitSubstring (i, 16, 24)), static_cast<uint8_t> (Memory::BitSubstring (i, 24, 32)) } } } #endif { #if qPlatform_Windows Assert (fV4_.s_addr == i); #endif } inline InternetAddress::InternetAddress (const in_addr_t& i, ByteOrder byteOrder) : fAddressFamily_ (AddressFamily::V4) #if qPlatform_POSIX , fV4_ { i } #endif { #if qPlatform_Windows fV4_.s_addr = i; #endif if (byteOrder == ByteOrder::Host) { fV4_.s_addr = htonl (fV4_.s_addr); //NB no ':' cuz some systems use macro } } inline constexpr InternetAddress::InternetAddress (const in_addr& i) : fAddressFamily_{AddressFamily::V4} , fV4_{i} { } inline InternetAddress::InternetAddress (const in_addr& i, ByteOrder byteOrder) : fAddressFamily_{AddressFamily::V4} , fV4_{i} { if (byteOrder == ByteOrder::Host) { fV4_.s_addr = htonl (fV4_.s_addr); //NB no ':' cuz some systems use macro } } constexpr InternetAddress::InternetAddress (byte octet1, byte octet2, byte octet3, byte octet4) : InternetAddress (array<byte, 4>{octet1, octet2, octet3, octet4}) { } constexpr InternetAddress::InternetAddress (uint8_t octet1, uint8_t octet2, uint8_t octet3, uint8_t octet4) : InternetAddress (array<uint8_t, 4>{octet1, octet2, octet3, octet4}) { } constexpr InternetAddress::InternetAddress (tuple<uint8_t, uint8_t, uint8_t, uint8_t> octets) : InternetAddress (array<uint8_t, 4>{get<0> (octets), get<1> (octets), get<2> (octets), get<3> (octets)}) { } constexpr InternetAddress::InternetAddress (array<uint8_t, 4> octets, AddressFamily af) : fAddressFamily_{af} , fArray_4_uint_{octets} { } constexpr InternetAddress::InternetAddress (array<byte, 4> octets, AddressFamily af) : fAddressFamily_{af} , fArray_4_byte_{octets} { } constexpr InternetAddress::InternetAddress (const in6_addr& i) : fAddressFamily_ (AddressFamily::V6) , fV6_{i} { } constexpr InternetAddress::InternetAddress (array<uint8_t, 16> octets, AddressFamily af) : fAddressFamily_{af} , fArray_16_uint_{octets} { } constexpr InternetAddress::InternetAddress (array<byte, 16> octets, AddressFamily af) : fAddressFamily_{af} , fArray_16_byte_{octets} { } template <typename ITERABLE_OF_UINT8OrByte, enable_if_t<Configuration::IsIterableOfT_v<ITERABLE_OF_UINT8OrByte, byte> or Configuration::IsIterableOfT_v<ITERABLE_OF_UINT8OrByte, uint8_t>>*> inline InternetAddress::InternetAddress (ITERABLE_OF_UINT8OrByte octets, AddressFamily af) : fAddressFamily_{af} { Require (af != AddressFamily::V4 or octets.size () == 4); Require (af != AddressFamily::V6 or octets.size () == 16); size_t i = 0; for (auto b : octets) { fArray_16_uint_[i++] = static_cast<uint8_t> (b); } } constexpr bool InternetAddress::empty () const { return fAddressFamily_ == AddressFamily::UNKNOWN; } inline void InternetAddress::clear () { fAddressFamily_ = AddressFamily::UNKNOWN; } constexpr InternetAddress::AddressFamily InternetAddress::GetAddressFamily () const { return fAddressFamily_; } constexpr optional<size_t> InternetAddress::GetAddressSize () const { switch (GetAddressFamily ()) { case AddressFamily::V4: return 4; case AddressFamily::V6: return 16; default: return nullopt; } } template <> String InternetAddress::As<String> () const; #if qPlatform_POSIX template <> inline in_addr_t InternetAddress::As<in_addr_t> () const { Require (fAddressFamily_ == AddressFamily::V4); return fV4_.s_addr; } #endif template <> constexpr in_addr InternetAddress::As<in_addr> () const { Require (fAddressFamily_ == AddressFamily::V4); return fV4_; } template <> constexpr array<uint8_t, 4> InternetAddress::As<array<uint8_t, 4>> () const { Require (GetAddressSize () == 4u); return fArray_4_uint_; } template <> constexpr array<byte, 4> InternetAddress::As<array<byte, 4>> () const { Require (GetAddressSize () == 4u); return fArray_4_byte_; } template <> constexpr array<uint8_t, 16> InternetAddress::As<array<uint8_t, 16>> () const { Require (GetAddressSize () == 16u); return fArray_16_uint_; } template <> constexpr array<byte, 16> InternetAddress::As<array<byte, 16>> () const { Require (GetAddressSize () == 16u); return fArray_16_byte_; } template <> inline vector<byte> InternetAddress::As<vector<byte>> () const { Require (GetAddressSize ().has_value ()); Assert (*GetAddressSize () <= 16); return vector<byte>{fArray_16_byte_.begin (), fArray_16_byte_.begin () + *GetAddressSize ()}; } template <> inline vector<uint8_t> InternetAddress::As<vector<uint8_t>> () const { Require (GetAddressSize ().has_value ()); Assert (*GetAddressSize () <= 16); return vector<uint8_t>{fArray_16_uint_.begin (), fArray_16_uint_.begin () + *GetAddressSize ()}; } template <> [[deprecated ("array<byte,4> works better so this is deprecated since Stroika v2.1d13")]] inline tuple<uint8_t, uint8_t, uint8_t, uint8_t> InternetAddress::As<tuple<uint8_t, uint8_t, uint8_t, uint8_t>> () const { Require (fAddressFamily_ == AddressFamily::V4); switch (Configuration::GetEndianness ()) { case Configuration::Endian::eLittleByte: return make_tuple<uint8_t, uint8_t, uint8_t, uint8_t> ( static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 0, 8)), static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 8, 16)), static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 16, 24)), static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 24, 32))); case Configuration::Endian::eBigByte: return make_tuple<uint8_t, uint8_t, uint8_t, uint8_t> ( static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 24, 32)), static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 16, 24)), static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 8, 16)), static_cast<uint8_t> (Memory::BitSubstring (fV4_.s_addr, 0, 8))); default: AssertNotImplemented (); return tuple<uint8_t, uint8_t, uint8_t, uint8_t>{}; } } template <> constexpr in6_addr InternetAddress::As<in6_addr> () const { Require (fAddressFamily_ == AddressFamily::V6); return fV6_; } template <> inline in_addr InternetAddress::As<in_addr> (ByteOrder byteOrder) const { Require (fAddressFamily_ == AddressFamily::V4); if (byteOrder == ByteOrder::Network) { return fV4_; } else { in_addr tmp = fV4_; tmp.s_addr = ntohl (tmp.s_addr); return tmp; } } /* ******************************************************************************** ********************** InternetAddress::ThreeWayComparer *********************** ******************************************************************************** */ constexpr int InternetAddress::ThreeWayComparer::operator() (const InternetAddress& lhs, const InternetAddress& rhs) const { if (int cmp = Common::ThreeWayCompare (lhs.fAddressFamily_, rhs.fAddressFamily_)) { return cmp; } switch (lhs.fAddressFamily_) { case AddressFamily::UNKNOWN: { return 0; } break; case AddressFamily::V4: { return Memory::MemCmp (&*lhs.fArray_4_uint_.begin (), &*rhs.fArray_4_uint_.begin (), 4); } break; case AddressFamily::V6: { return Memory::MemCmp (&*lhs.fArray_16_uint_.begin (), &*rhs.fArray_16_uint_.begin (), 16); } break; } //AssertNotReached (); @todo - this really should be an assertion failure, but tricky cuz constexpr function could fix with template) return 0; } /* ******************************************************************************** ************************* InternetAddress operators **************************** ******************************************************************************** */ inline bool operator< (const InternetAddress& lhs, const InternetAddress& rhs) { return Common::ThreeWayCompare (lhs, rhs) < 0; } inline bool operator<= (const InternetAddress& lhs, const InternetAddress& rhs) { return Common::ThreeWayCompare (lhs, rhs) <= 0; } inline bool operator== (const InternetAddress& lhs, const InternetAddress& rhs) { return Common::ThreeWayCompare (lhs, rhs) == 0; } inline bool operator!= (const InternetAddress& lhs, const InternetAddress& rhs) { return Common::ThreeWayCompare (lhs, rhs) != 0; } inline bool operator>= (const InternetAddress& lhs, const InternetAddress& rhs) { return Common::ThreeWayCompare (lhs, rhs) >= 0; } inline bool operator> (const InternetAddress& lhs, const InternetAddress& rhs) { return Common::ThreeWayCompare (lhs, rhs) > 0; } namespace V4 { constexpr InternetAddress kAddrAny{in_addr{}}; } namespace V6 { constexpr InternetAddress kAddrAny{in6_addr{}}; } namespace V4 { constexpr InternetAddress kLocalhost{0x7f, 0x0, 0x0, 0x1}; } namespace V6 { constexpr InternetAddress kLocalhost{in6_addr{{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}}}; } namespace V6 { constexpr InternetAddress kV4MappedLocalhost{in6_addr{{{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x7f, 0, 0, 1}}}}; } } #endif /*_Stroika_Foundation_IO_Network_InternetAddress_inl_*/ <|endoftext|>
<commit_before>/*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryQtAssistantUtil.h" #include <berryPlatformUI.h> #include <berryConfig.h> #include <berryLog.h> #include <berryIBundleStorage.h> #include <berryIWorkbench.h> #include <berryIWorkbenchPage.h> #include <berryIWorkbenchPart.h> #include <QFileInfo> #include <QProgressDialog> #include <QMessageBox> #include <QDir> namespace berry { QProcess* QtAssistantUtil::assistantProcess = 0; QString QtAssistantUtil::helpCollectionFile; QString QtAssistantUtil::defaultHelpUrl; QStringList QtAssistantUtil::registeredBundles; void QtAssistantUtil::SetHelpColletionFile(const QString& file) { helpCollectionFile = file; } void QtAssistantUtil::OpenActivePartHelp() { //Get Plugin-ID QString pluginID; berry::IWorkbench* currentWorkbench = berry::PlatformUI::GetWorkbench(); if (currentWorkbench) { berry::IWorkbenchWindow::Pointer currentWorkbenchWindow = currentWorkbench->GetActiveWorkbenchWindow(); if (currentWorkbenchWindow) { berry::IWorkbenchPage::Pointer currentPage = currentWorkbenchWindow->GetActivePage(); if (currentPage) { berry::IWorkbenchPart::Pointer currentPart = currentPage->GetActivePart(); if (currentPart) pluginID = QString::fromStdString(currentPart->GetSite()->GetPluginId()); } } } //End get Plugin-ID QString helpUrl = defaultHelpUrl; if (!pluginID.isEmpty() && registeredBundles.contains(pluginID)) helpUrl = "qthelp://"+pluginID+"/bundle/index.html"; OpenAssistant(helpUrl); } void QtAssistantUtil::OpenAssistant(const QString& startPage) { QString startUrl = startPage; if (startUrl.isEmpty()) startUrl = defaultHelpUrl; if (assistantProcess == 0) { assistantProcess = new QProcess; } if (assistantProcess->state() == QProcess::NotRunning) { QStringList assistantArgs; if (!helpCollectionFile.isEmpty()) { assistantArgs << QLatin1String("-collectionFile") << QLatin1String(helpCollectionFile.toLatin1()); } assistantArgs << QLatin1String("-enableRemoteControl") << QLatin1String("-showUrl") << QLatin1String(startUrl.toLatin1()); assistantProcess->start(GetAssistantExecutable(), assistantArgs); } else { QByteArray ba; ba.append("setSource ").append(startUrl.toLatin1()).append('\0'); assistantProcess->write(ba); } } void QtAssistantUtil::CloseAssistant() { if (assistantProcess && (assistantProcess->state() != QProcess::NotRunning)) { assistantProcess->close(); } delete assistantProcess; } bool QtAssistantUtil::RegisterQCHFiles(const QString& collectionFile, const std::vector<IBundle::Pointer>& bundles) { QString assistantExec = GetAssistantExecutable(); QList<QStringList> argsVector; for (std::size_t i = 0; i < bundles.size(); ++i) { std::vector<std::string> resourceFiles; bundles[i]->GetStorage().List("resources", resourceFiles); bool qchFileFound = false; for (std::size_t j = 0; j < resourceFiles.size(); ++j) { QString resource = QString::fromStdString(resourceFiles[j]); if (resource.endsWith(".qch")) { qchFileFound = true; QStringList args; args << QLatin1String("-collectionFile") << collectionFile; Poco::Path qchPath = bundles[i]->GetPath(); qchPath.pushDirectory("resources"); qchPath.setFileName(resourceFiles[j]); args << QLatin1String("-register") << QString::fromStdString(qchPath.toString()); args << QLatin1String("-quiet"); //BERRY_INFO << "Registering " << qchPath.toString() << " with " << collectionFile.toStdString(); argsVector.push_back(args); } } if (qchFileFound) { registeredBundles.push_back(QString::fromStdString(bundles[i]->GetSymbolicName())); } } bool success = true; QProgressDialog progress("Registering help files...", "Abort Registration", 0, argsVector.size()); progress.setWindowModality(Qt::WindowModal); if (argsVector.isEmpty()) { BERRY_WARN << "No .qch files found. Help contents will not be available."; } QString errorString; int exitCode = 0; for (int i = 0; i < argsVector.size(); ++i) { const QStringList& args = argsVector[i]; progress.setValue(i); QString labelText = QString("Registering ") + args[3]; progress.setLabelText(labelText); if (progress.wasCanceled()) { success = false; break; } QProcess* process = new QProcess; process->start(assistantExec, args); if (!process->waitForStarted()) { success = false; BERRY_ERROR << "Registering compressed help file" << args[3].toStdString() << " failed"; } if (process->error() != QProcess::UnknownError) { errorString = process->errorString(); success = false; } if (process->exitCode() != 0) exitCode = process->exitCode(); } progress.setValue(argsVector.size()); if (!errorString.isEmpty() || exitCode) { QString errText = "Registering one or more help files failed."; if (errorString.isEmpty()) { errText += "\nYou may not have write permissions in " + QDir::toNativeSeparators(QDir::homePath()); } else { errText += " The last error was: " + errorString; } QMessageBox::warning(0, "Help System Error", errText); } return success; } QString QtAssistantUtil::GetAssistantExecutable() { QFileInfo assistantFile(QT_ASSISTANT_EXECUTABLE); return assistantFile.fileName(); } void QtAssistantUtil::SetDefaultHelpUrl(const QString& defaultUrl) { defaultHelpUrl = defaultUrl; } } <commit_msg>FIX (#4432): improved QAssistant exe search logic<commit_after>/*========================================================================= Program: BlueBerry Platform Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "berryQtAssistantUtil.h" #include <berryPlatformUI.h> #include <berryConfig.h> #include <berryLog.h> #include <berryIBundleStorage.h> #include <berryIWorkbench.h> #include <berryIWorkbenchPage.h> #include <berryIWorkbenchPart.h> #include <QFileInfo> #include <QProgressDialog> #include <QMessageBox> #include <QDir> namespace berry { QProcess* QtAssistantUtil::assistantProcess = 0; QString QtAssistantUtil::helpCollectionFile; QString QtAssistantUtil::defaultHelpUrl; QStringList QtAssistantUtil::registeredBundles; void QtAssistantUtil::SetHelpColletionFile(const QString& file) { helpCollectionFile = file; } void QtAssistantUtil::OpenActivePartHelp() { //Get Plugin-ID QString pluginID; berry::IWorkbench* currentWorkbench = berry::PlatformUI::GetWorkbench(); if (currentWorkbench) { berry::IWorkbenchWindow::Pointer currentWorkbenchWindow = currentWorkbench->GetActiveWorkbenchWindow(); if (currentWorkbenchWindow) { berry::IWorkbenchPage::Pointer currentPage = currentWorkbenchWindow->GetActivePage(); if (currentPage) { berry::IWorkbenchPart::Pointer currentPart = currentPage->GetActivePart(); if (currentPart) pluginID = QString::fromStdString(currentPart->GetSite()->GetPluginId()); } } } //End get Plugin-ID QString helpUrl = defaultHelpUrl; if (!pluginID.isEmpty() && registeredBundles.contains(pluginID)) helpUrl = "qthelp://"+pluginID+"/bundle/index.html"; OpenAssistant(helpUrl); } void QtAssistantUtil::OpenAssistant(const QString& startPage) { QString startUrl = startPage; if (startUrl.isEmpty()) startUrl = defaultHelpUrl; if (assistantProcess == 0) { assistantProcess = new QProcess; } if (assistantProcess->state() == QProcess::NotRunning) { QStringList assistantArgs; if (!helpCollectionFile.isEmpty()) { assistantArgs << QLatin1String("-collectionFile") << QLatin1String(helpCollectionFile.toLatin1()); } assistantArgs << QLatin1String("-enableRemoteControl") << QLatin1String("-showUrl") << QLatin1String(startUrl.toLatin1()); assistantProcess->start(GetAssistantExecutable(), assistantArgs); } else { QByteArray ba; ba.append("setSource ").append(startUrl.toLatin1()).append('\0'); assistantProcess->write(ba); } } void QtAssistantUtil::CloseAssistant() { if (assistantProcess && (assistantProcess->state() != QProcess::NotRunning)) { assistantProcess->close(); } delete assistantProcess; } bool QtAssistantUtil::RegisterQCHFiles(const QString& collectionFile, const std::vector<IBundle::Pointer>& bundles) { QString assistantExec = GetAssistantExecutable(); QList<QStringList> argsVector; for (std::size_t i = 0; i < bundles.size(); ++i) { std::vector<std::string> resourceFiles; bundles[i]->GetStorage().List("resources", resourceFiles); bool qchFileFound = false; for (std::size_t j = 0; j < resourceFiles.size(); ++j) { QString resource = QString::fromStdString(resourceFiles[j]); if (resource.endsWith(".qch")) { qchFileFound = true; QStringList args; args << QLatin1String("-collectionFile") << collectionFile; Poco::Path qchPath = bundles[i]->GetPath(); qchPath.pushDirectory("resources"); qchPath.setFileName(resourceFiles[j]); args << QLatin1String("-register") << QString::fromStdString(qchPath.toString()); args << QLatin1String("-quiet"); //BERRY_INFO << "Registering " << qchPath.toString() << " with " << collectionFile.toStdString(); argsVector.push_back(args); } } if (qchFileFound) { registeredBundles.push_back(QString::fromStdString(bundles[i]->GetSymbolicName())); } } bool success = true; QProgressDialog progress("Registering help files...", "Abort Registration", 0, argsVector.size()); progress.setWindowModality(Qt::WindowModal); if (argsVector.isEmpty()) { BERRY_WARN << "No .qch files found. Help contents will not be available."; } QString errorString; int exitCode = 0; for (int i = 0; i < argsVector.size(); ++i) { const QStringList& args = argsVector[i]; progress.setValue(i); QString labelText = QString("Registering ") + args[3]; progress.setLabelText(labelText); if (progress.wasCanceled()) { success = false; break; } QProcess* process = new QProcess; process->start(assistantExec, args); if (!process->waitForStarted()) { success = false; BERRY_ERROR << "Registering compressed help file" << args[3].toStdString() << " failed"; } if (process->error() != QProcess::UnknownError) { errorString = process->errorString(); success = false; } if (process->exitCode() != 0) exitCode = process->exitCode(); } progress.setValue(argsVector.size()); if (!errorString.isEmpty() || exitCode) { QString errText = "Registering one or more help files failed."; if (errorString.isEmpty()) { errText += "\nYou may not have write permissions in " + QDir::toNativeSeparators(QDir::homePath()); } else { errText += " The last error was: " + errorString; } QMessageBox::warning(0, "Help System Error", errText); } return success; } QString QtAssistantUtil::GetAssistantExecutable() { QFileInfo assistantFile(QT_ASSISTANT_EXECUTABLE); QFileInfo localAssistant(QCoreApplication::applicationDirPath() + "/" + assistantFile.fileName() ); if (localAssistant.isExecutable()) { return localAssistant.absoluteFilePath(); } else { return assistantFile.absoluteFilePath(); } } void QtAssistantUtil::SetDefaultHelpUrl(const QString& defaultUrl) { defaultHelpUrl = defaultUrl; } } <|endoftext|>
<commit_before>/* * Copyright (C) 2015-2018 Dubalu LLC. All rights reserved. * * 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 "base_client.h" #include <errno.h> // for errno #include <memory> // for std::shared_ptr #include <sys/socket.h> // for SHUT_RDWR #include <sysexits.h> // for EX_SOFTWARE #include <type_traits> // for remove_reference<>::type #include <utility> // for std::move #include <xapian.h> // for SerialisationError #include "cassert.h" // for ASSERT #include "error.hh" // for error:name, error::description #include "ev/ev++.h" // for ::EV_ERROR, ::EV_READ, ::EV_WRITE #include "ignore_unused.h" // for ignore_unused #include "io.hh" // for io::read, io::close, io::lseek, io::write #include "length.h" // for serialise_length, unserialise_length #include "likely.h" // for likely, unlikely #include "log.h" // for L_CALL, L_ERR, L_EV, L_CONN, L_OBJ #include "manager.h" // for sig_exit #include "readable_revents.hh" // for readable_revents #include "repr.hh" // for repr #include "thread.hh" // for get_thread_name // #undef L_DEBUG // #define L_DEBUG L_GREY // #undef L_CALL // #define L_CALL L_STACKED_DIM_GREY // #undef L_CONN // #define L_CONN L_GREEN // #undef L_TCP_ENQUEUE // #define L_TCP_ENQUEUE L_GREEN // #undef L_TCP_WIRE // #define L_TCP_WIRE L_WHITE // #undef L_EV // #define L_EV L_MEDIUM_PURPLE // #undef L_EV_BEGIN // #define L_EV_BEGIN L_DELAYED_200 // #undef L_EV_END // #define L_EV_END L_DELAYED_N_UNLOG constexpr int WRITE_QUEUE_LIMIT = 10; constexpr int WRITE_QUEUE_THRESHOLD = WRITE_QUEUE_LIMIT * 2 / 3; BaseClient::BaseClient(const std::shared_ptr<Worker>& parent_, ev::loop_ref* ev_loop_, unsigned int ev_flags_, int sock_) : Worker(std::move(parent_), ev_loop_, ev_flags_), io_read(*ev_loop), io_write(*ev_loop), write_start_async(*ev_loop), read_start_async(*ev_loop), waiting(false), running(false), shutting_down(false), sock(sock_), closed(false), writes(0), total_received_bytes(0), total_sent_bytes(0), mode(MODE::READ_BUF), write_queue(WRITE_QUEUE_LIMIT, -1, WRITE_QUEUE_THRESHOLD) { if (sock == -1) { throw std::invalid_argument("Invalid socket"); } write_start_async.set<BaseClient, &BaseClient::write_start_async_cb>(this); read_start_async.set<BaseClient, &BaseClient::read_start_async_cb>(this); io_write.set<BaseClient, &BaseClient::io_cb_write>(this); io_write.set(sock, ev::WRITE); ++XapiandManager::manager->total_clients; } BaseClient::~BaseClient() { if (XapiandManager::manager->total_clients.fetch_sub(1) == 0) { L_CRIT("Inconsistency in number of binary clients"); sig_exit(-EX_SOFTWARE); } // If shutting down and there are no more clients connected, // continue shutdown. if (XapiandManager::manager->shutdown_asap.load() != 0) { if (XapiandManager::manager->total_clients == 0) { XapiandManager::manager->shutdown_sig(0); } } io::close(sock); Worker::deinit(); if (get_thread_name()[0] != 'S') { L_CRIT("BaseClient destroyed from %s!" + TRACEBACK(), repr(get_thread_name())); // sig_exit(-EX_SOFTWARE); } } void BaseClient::close() { L_CALL("BaseClient::close()"); if (!closed.exchange(true)) { io::shutdown(sock, SHUT_RDWR); } } void BaseClient::destroy_impl() { L_CALL("BaseClient::destroy_impl()"); Worker::destroy_impl(); close(); } void BaseClient::start_impl() { L_CALL("BaseClient::start_impl()"); Worker::start_impl(); write_start_async.start(); L_EV("Start client's async update event"); read_start_async.start(); L_EV("Start client's async read start event"); io_read.start(); L_EV("Start client's read event (sock=%d)", sock); } void BaseClient::stop_impl() { L_CALL("BaseClient::stop_impl()"); Worker::stop_impl(); write_start_async.stop(); L_EV("Stop client's async update event"); read_start_async.stop(); L_EV("Stop client's async read start event"); io_write.stop(); L_EV("Stop client's write event"); io_read.stop(); L_EV("Stop client's read event"); write_queue.finish(); write_queue.clear(); } WR BaseClient::write_from_queue() { L_CALL("BaseClient::write_from_queue()"); if (closed) { L_ERR("ERROR: write error {sock:%d}: Socket already closed!", sock); L_CONN("WR:ERR.1: {sock:%d}", sock); return WR::ERROR; } std::lock_guard<std::mutex> lk(_mutex); std::shared_ptr<Buffer> buffer; if (write_queue.front(buffer)) { size_t buf_size = buffer->size(); const char *buf_data = buffer->data(); #ifdef MSG_NOSIGNAL ssize_t sent = io::send(sock, buf_data, buf_size, MSG_NOSIGNAL); #else ssize_t sent = io::write(sock, buf_data, buf_size); #endif if (sent < 0) { if (io::ignored_errno(errno, true, true, false)) { L_CONN("WR:RETRY: {sock:%d} - %s (%d): %s", sock, error::name(errno), errno, error::description(errno)); return WR::RETRY; } L_ERR("ERROR: write error {sock:%d} - %s (%d): %s", sock, error::name(errno), errno, error::description(errno)); L_CONN("WR:ERR.2: {sock:%d}", sock); close(); return WR::ERROR; } total_sent_bytes += sent; L_TCP_WIRE("{sock:%d} <<-- %s (%zu bytes)", sock, repr(buf_data, sent, true, true, 500), sent); buffer->remove_prefix(sent); if (buffer->size() == 0) { if (write_queue.pop(buffer)) { if (write_queue.empty()) { L_CONN("WR:OK: {sock:%d}", sock); return WR::OK; } } } L_CONN("WR:PENDING: {sock:%d}", sock); return WR::PENDING; } L_CONN("WR:OK.2: {sock:%d}", sock); return WR::OK; } WR BaseClient::write_from_queue(int max) { L_CALL("BaseClient::write_from_queue(%d)", max); WR status = WR::PENDING; for (int i = 0; max < 0 || i < max; ++i) { status = write_from_queue(); if (status != WR::PENDING) { return status; } } return status; } bool BaseClient::write(const char *buf, size_t buf_size) { L_CALL("BaseClient::write(<buf>, %zu)", buf_size); return write_buffer(std::make_shared<Buffer>('\0', buf, buf_size)); } bool BaseClient::write_file(std::string_view path, bool unlink) { L_CALL("BaseClient::write_file(<path>, <unlink>)"); return write_buffer(std::make_shared<Buffer>(path, unlink)); } bool BaseClient::write_buffer(const std::shared_ptr<Buffer>& buffer) { L_CALL("BaseClient::write_buffer(<buffer>)"); do { if (closed) { return false; } } while (!write_queue.push(buffer, 1)); writes += 1; L_TCP_ENQUEUE("{sock:%d} <ENQUEUE> buffer (%zu bytes)", sock, buffer->full_size()); switch (write_from_queue(-1)) { case WR::RETRY: case WR::PENDING: write_start_async.send(); /* FALLTHROUGH */ case WR::OK: return true; default: return false; } } void BaseClient::_io_cb_write(ev::io &watcher, int revents) { L_CALL("BaseClient::io_cb_write(<watcher>, 0x%x (%s)) {sock:%d}", revents, readable_revents(revents), watcher.fd); L_EV_BEGIN("BaseClient::io_cb_write:BEGIN"); L_EV_END("BaseClient::io_cb_write:END"); ASSERT(sock == -1 || sock == watcher.fd); ignore_unused(watcher); L_DEBUG_HOOK("BaseClient::io_cb_write", "BaseClient::io_cb_write(<watcher>, 0x%x (%s)) {sock:%d}", revents, readable_revents(revents), watcher.fd); if (closed) { stop(); destroy(); detach(); return; } if ((revents & EV_ERROR) != 0) { L_ERR("ERROR: got invalid event {sock:%d} - %s (%d): %s", watcher.fd, error::name(errno), errno, error::description(errno)); stop(); destroy(); detach(); return; } switch (write_from_queue(10)) { case WR::RETRY: case WR::PENDING: break; case WR::ERROR: case WR::OK: write_queue.empty([&](bool empty) { if (empty) { io_write.stop(); L_EV("Disable write event"); if (shutting_down) { detach(); } } }); break; } if (closed) { detach(); } } void BaseClient::write_start_async_cb(ev::async& /*unused*/, int revents) { L_CALL("BaseClient::write_start_async_cb(<watcher>, 0x%x (%s))", revents, readable_revents(revents)); L_EV_BEGIN("BaseClient::write_start_async_cb:BEGIN"); L_EV_END("BaseClient::write_start_async_cb:END"); ignore_unused(revents); if (!closed) { io_write.start(); L_EV("Enable write event [%d]", io_write.is_active()); } } void BaseClient::read_start_async_cb(ev::async& /*unused*/, int revents) { L_CALL("BaseClient::read_start_async_cb(<watcher>, 0x%x (%s))", revents, readable_revents(revents)); L_EV_BEGIN("BaseClient::read_start_async_cb:BEGIN"); L_EV_END("BaseClient::read_start_async_cb:END"); ignore_unused(revents); if (!closed) { io_read.start(); L_EV("Enable read event [%d]", io_read.is_active()); } } void BaseClient::read_file() { L_CALL("BaseClient::read_file()"); mode = MODE::READ_FILE_TYPE; file_size = -1; receive_checksum = false; } <commit_msg>Clients: Does it matter where clients are destroyed?<commit_after>/* * Copyright (C) 2015-2018 Dubalu LLC. All rights reserved. * * 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 "base_client.h" #include <errno.h> // for errno #include <memory> // for std::shared_ptr #include <sys/socket.h> // for SHUT_RDWR #include <sysexits.h> // for EX_SOFTWARE #include <type_traits> // for remove_reference<>::type #include <utility> // for std::move #include <xapian.h> // for SerialisationError #include "cassert.h" // for ASSERT #include "error.hh" // for error:name, error::description #include "ev/ev++.h" // for ::EV_ERROR, ::EV_READ, ::EV_WRITE #include "ignore_unused.h" // for ignore_unused #include "io.hh" // for io::read, io::close, io::lseek, io::write #include "length.h" // for serialise_length, unserialise_length #include "likely.h" // for likely, unlikely #include "log.h" // for L_CALL, L_ERR, L_EV, L_CONN, L_OBJ #include "manager.h" // for sig_exit #include "readable_revents.hh" // for readable_revents #include "repr.hh" // for repr #include "thread.hh" // for get_thread_name // #undef L_DEBUG // #define L_DEBUG L_GREY // #undef L_CALL // #define L_CALL L_STACKED_DIM_GREY // #undef L_CONN // #define L_CONN L_GREEN // #undef L_TCP_ENQUEUE // #define L_TCP_ENQUEUE L_GREEN // #undef L_TCP_WIRE // #define L_TCP_WIRE L_WHITE // #undef L_EV // #define L_EV L_MEDIUM_PURPLE // #undef L_EV_BEGIN // #define L_EV_BEGIN L_DELAYED_200 // #undef L_EV_END // #define L_EV_END L_DELAYED_N_UNLOG constexpr int WRITE_QUEUE_LIMIT = 10; constexpr int WRITE_QUEUE_THRESHOLD = WRITE_QUEUE_LIMIT * 2 / 3; BaseClient::BaseClient(const std::shared_ptr<Worker>& parent_, ev::loop_ref* ev_loop_, unsigned int ev_flags_, int sock_) : Worker(std::move(parent_), ev_loop_, ev_flags_), io_read(*ev_loop), io_write(*ev_loop), write_start_async(*ev_loop), read_start_async(*ev_loop), waiting(false), running(false), shutting_down(false), sock(sock_), closed(false), writes(0), total_received_bytes(0), total_sent_bytes(0), mode(MODE::READ_BUF), write_queue(WRITE_QUEUE_LIMIT, -1, WRITE_QUEUE_THRESHOLD) { if (sock == -1) { throw std::invalid_argument("Invalid socket"); } write_start_async.set<BaseClient, &BaseClient::write_start_async_cb>(this); read_start_async.set<BaseClient, &BaseClient::read_start_async_cb>(this); io_write.set<BaseClient, &BaseClient::io_cb_write>(this); io_write.set(sock, ev::WRITE); ++XapiandManager::manager->total_clients; } BaseClient::~BaseClient() { if (XapiandManager::manager->total_clients.fetch_sub(1) == 0) { L_CRIT("Inconsistency in number of binary clients"); sig_exit(-EX_SOFTWARE); } // If shutting down and there are no more clients connected, // continue shutdown. if (XapiandManager::manager->shutdown_asap.load() != 0) { if (XapiandManager::manager->total_clients == 0) { XapiandManager::manager->shutdown_sig(0); } } io::close(sock); Worker::deinit(); } void BaseClient::close() { L_CALL("BaseClient::close()"); if (!closed.exchange(true)) { io::shutdown(sock, SHUT_RDWR); } } void BaseClient::destroy_impl() { L_CALL("BaseClient::destroy_impl()"); Worker::destroy_impl(); close(); } void BaseClient::start_impl() { L_CALL("BaseClient::start_impl()"); Worker::start_impl(); write_start_async.start(); L_EV("Start client's async update event"); read_start_async.start(); L_EV("Start client's async read start event"); io_read.start(); L_EV("Start client's read event (sock=%d)", sock); } void BaseClient::stop_impl() { L_CALL("BaseClient::stop_impl()"); Worker::stop_impl(); write_start_async.stop(); L_EV("Stop client's async update event"); read_start_async.stop(); L_EV("Stop client's async read start event"); io_write.stop(); L_EV("Stop client's write event"); io_read.stop(); L_EV("Stop client's read event"); write_queue.finish(); write_queue.clear(); } WR BaseClient::write_from_queue() { L_CALL("BaseClient::write_from_queue()"); if (closed) { L_ERR("ERROR: write error {sock:%d}: Socket already closed!", sock); L_CONN("WR:ERR.1: {sock:%d}", sock); return WR::ERROR; } std::lock_guard<std::mutex> lk(_mutex); std::shared_ptr<Buffer> buffer; if (write_queue.front(buffer)) { size_t buf_size = buffer->size(); const char *buf_data = buffer->data(); #ifdef MSG_NOSIGNAL ssize_t sent = io::send(sock, buf_data, buf_size, MSG_NOSIGNAL); #else ssize_t sent = io::write(sock, buf_data, buf_size); #endif if (sent < 0) { if (io::ignored_errno(errno, true, true, false)) { L_CONN("WR:RETRY: {sock:%d} - %s (%d): %s", sock, error::name(errno), errno, error::description(errno)); return WR::RETRY; } L_ERR("ERROR: write error {sock:%d} - %s (%d): %s", sock, error::name(errno), errno, error::description(errno)); L_CONN("WR:ERR.2: {sock:%d}", sock); close(); return WR::ERROR; } total_sent_bytes += sent; L_TCP_WIRE("{sock:%d} <<-- %s (%zu bytes)", sock, repr(buf_data, sent, true, true, 500), sent); buffer->remove_prefix(sent); if (buffer->size() == 0) { if (write_queue.pop(buffer)) { if (write_queue.empty()) { L_CONN("WR:OK: {sock:%d}", sock); return WR::OK; } } } L_CONN("WR:PENDING: {sock:%d}", sock); return WR::PENDING; } L_CONN("WR:OK.2: {sock:%d}", sock); return WR::OK; } WR BaseClient::write_from_queue(int max) { L_CALL("BaseClient::write_from_queue(%d)", max); WR status = WR::PENDING; for (int i = 0; max < 0 || i < max; ++i) { status = write_from_queue(); if (status != WR::PENDING) { return status; } } return status; } bool BaseClient::write(const char *buf, size_t buf_size) { L_CALL("BaseClient::write(<buf>, %zu)", buf_size); return write_buffer(std::make_shared<Buffer>('\0', buf, buf_size)); } bool BaseClient::write_file(std::string_view path, bool unlink) { L_CALL("BaseClient::write_file(<path>, <unlink>)"); return write_buffer(std::make_shared<Buffer>(path, unlink)); } bool BaseClient::write_buffer(const std::shared_ptr<Buffer>& buffer) { L_CALL("BaseClient::write_buffer(<buffer>)"); do { if (closed) { return false; } } while (!write_queue.push(buffer, 1)); writes += 1; L_TCP_ENQUEUE("{sock:%d} <ENQUEUE> buffer (%zu bytes)", sock, buffer->full_size()); switch (write_from_queue(-1)) { case WR::RETRY: case WR::PENDING: write_start_async.send(); /* FALLTHROUGH */ case WR::OK: return true; default: return false; } } void BaseClient::_io_cb_write(ev::io &watcher, int revents) { L_CALL("BaseClient::io_cb_write(<watcher>, 0x%x (%s)) {sock:%d}", revents, readable_revents(revents), watcher.fd); L_EV_BEGIN("BaseClient::io_cb_write:BEGIN"); L_EV_END("BaseClient::io_cb_write:END"); ASSERT(sock == -1 || sock == watcher.fd); ignore_unused(watcher); L_DEBUG_HOOK("BaseClient::io_cb_write", "BaseClient::io_cb_write(<watcher>, 0x%x (%s)) {sock:%d}", revents, readable_revents(revents), watcher.fd); if (closed) { stop(); destroy(); detach(); return; } if ((revents & EV_ERROR) != 0) { L_ERR("ERROR: got invalid event {sock:%d} - %s (%d): %s", watcher.fd, error::name(errno), errno, error::description(errno)); stop(); destroy(); detach(); return; } switch (write_from_queue(10)) { case WR::RETRY: case WR::PENDING: break; case WR::ERROR: case WR::OK: write_queue.empty([&](bool empty) { if (empty) { io_write.stop(); L_EV("Disable write event"); if (shutting_down) { detach(); } } }); break; } if (closed) { detach(); } } void BaseClient::write_start_async_cb(ev::async& /*unused*/, int revents) { L_CALL("BaseClient::write_start_async_cb(<watcher>, 0x%x (%s))", revents, readable_revents(revents)); L_EV_BEGIN("BaseClient::write_start_async_cb:BEGIN"); L_EV_END("BaseClient::write_start_async_cb:END"); ignore_unused(revents); if (!closed) { io_write.start(); L_EV("Enable write event [%d]", io_write.is_active()); } } void BaseClient::read_start_async_cb(ev::async& /*unused*/, int revents) { L_CALL("BaseClient::read_start_async_cb(<watcher>, 0x%x (%s))", revents, readable_revents(revents)); L_EV_BEGIN("BaseClient::read_start_async_cb:BEGIN"); L_EV_END("BaseClient::read_start_async_cb:END"); ignore_unused(revents); if (!closed) { io_read.start(); L_EV("Enable read event [%d]", io_read.is_active()); } } void BaseClient::read_file() { L_CALL("BaseClient::read_file()"); mode = MODE::READ_FILE_TYPE; file_size = -1; receive_checksum = false; } <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz // // 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. // // Interface header. #include "renderingmanager.h" // appleseed.studio headers. #include "mainwindow/rendering/renderwidget.h" #include "mainwindow/statusbar.h" // appleseed.shared headers. #include "application/application.h" // appleseed.renderer headers. #include "renderer/api/aov.h" #include "renderer/api/camera.h" #include "renderer/api/frame.h" #include "renderer/api/project.h" #include "renderer/api/scene.h" // appleseed.foundation headers. #include "foundation/image/analysis.h" #include "foundation/image/image.h" #include "foundation/math/transform.h" #include "foundation/utility/string.h" // boost headers. #include "boost/filesystem/path.hpp" // Qt headers. #include <QAction> #include <QApplication> #include <QTimerEvent> using namespace appleseed::shared; using namespace boost; using namespace foundation; using namespace renderer; using namespace std; namespace appleseed { namespace studio { // // RenderingManager class implementation. // namespace { class MasterRendererThread : public QThread { public: // Constructor. explicit MasterRendererThread(MasterRenderer* master_renderer) : m_master_renderer(master_renderer) { } private: MasterRenderer* m_master_renderer; // The starting point for the thread. virtual void run() { m_master_renderer->render(); } }; } RenderingManager::RenderingManager(StatusBar& status_bar) : m_status_bar(status_bar) , m_project(0) , m_render_widget(0) , m_override_shading(false) { // // The connections below are using the Qt::BlockingQueuedConnection connection type. // // They are using a queued connection because the emitting thread is different from // the receiving thread (the emitting thread is the master renderer thread, and the // receiving thread is the UI thread of the main window (presumably). // // They are using a blocking queue connection because we need the receiving slot to // have returned in the receiving thread before the emitting thread can continue. // // See http://doc.trolltech.com/4.6/qt.html#ConnectionType-enum for more details. // connect( &m_renderer_controller, SIGNAL(signal_frame_begin()), this, SLOT(slot_frame_begin()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_frame_end()), this, SLOT(slot_frame_end()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_begin()), this, SLOT(slot_rendering_begin()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_success()), this, SLOT(slot_rendering_end()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_abort()), this, SLOT(slot_rendering_end()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_success()), this, SIGNAL(signal_rendering_end())); connect( &m_renderer_controller, SIGNAL(signal_rendering_abort()), this, SIGNAL(signal_rendering_end())); } void RenderingManager::start_rendering( Project* project, const ParamArray& params, const bool highlight_tiles, RenderWidget* render_widget) { m_project = project; m_render_widget = render_widget; m_camera_controller.reset( new CameraController( m_render_widget, m_project->get_scene())); connect( m_camera_controller.get(), SIGNAL(signal_camera_changed()), this, SLOT(slot_camera_changed())); connect( m_camera_controller.get(), SIGNAL(signal_camera_changed()), this, SIGNAL(signal_camera_changed())); m_tile_callback_factory.reset( new QtTileCallbackFactory( m_render_widget, highlight_tiles)); m_master_renderer.reset( new MasterRenderer( *m_project, params, &m_renderer_controller, m_tile_callback_factory.get())); m_master_renderer_thread.reset( new MasterRendererThread(m_master_renderer.get())); m_master_renderer_thread->start(); } bool RenderingManager::is_rendering() const { return m_master_renderer_thread.get() && m_master_renderer_thread->isRunning(); } void RenderingManager::wait_until_rendering_end() { while (is_rendering()) { QApplication::processEvents(); } } void RenderingManager::abort_rendering() { RENDERER_LOG_DEBUG("aborting rendering..."); m_renderer_controller.set_status(IRendererController::AbortRendering); } void RenderingManager::restart_rendering() { m_renderer_controller.set_status(IRendererController::RestartRendering); } void RenderingManager::reinitialize_rendering() { m_renderer_controller.set_status(IRendererController::ReinitializeRendering); } void RenderingManager::timerEvent(QTimerEvent* event) { if (event->timerId() == m_render_widget_update_timer.timerId()) m_render_widget->update(); else QObject::timerEvent(event); } void RenderingManager::print_final_rendering_time() { const double rendering_time = m_rendering_timer.get_seconds(); const string rendering_time_string = pretty_time(rendering_time, 3); RENDERER_LOG_INFO("rendering finished in %s.", rendering_time_string.c_str()); m_status_bar.set_text("Rendering finished in " + rendering_time_string); } void RenderingManager::print_average_luminance() { Image final_image(m_project->get_frame()->image()); m_project->get_frame()->transform_to_output_color_space(final_image); const double average_luminance = compute_average_luminance(final_image); RENDERER_LOG_DEBUG( "final average luminance is %s.", pretty_scalar(average_luminance, 6).c_str()); } void RenderingManager::archive_frame_to_disk() { RENDERER_LOG_INFO("archiving frame to disk..."); const filesystem::path autosave_path = filesystem::path(Application::get_root_path()) / "images/autosave/"; m_project->get_frame()->archive( autosave_path.directory_string().c_str()); } void RenderingManager::slot_rendering_begin() { assert(m_master_renderer.get()); if (m_override_shading) { m_master_renderer->get_parameters() .push("shading_engine") .push("override_shading") .insert("mode", m_override_shading_mode); } else { m_master_renderer->get_parameters() .push("shading_engine") .dictionaries().remove("override_shading"); } const int UpdateRate = 5; m_render_widget_update_timer.start(1000 / UpdateRate, this); } void RenderingManager::slot_rendering_end() { m_render_widget_update_timer.stop(); m_render_widget->update(); print_final_rendering_time(); print_average_luminance(); archive_frame_to_disk(); // Prevent manipulation of the camera after rendering has ended. m_camera_controller.reset(); } void RenderingManager::slot_frame_begin() { m_renderer_controller.set_status(IRendererController::ContinueRendering); m_camera_controller->update_camera_transform(); m_rendering_timer.start(); m_status_bar.start_rendering_time_display(&m_rendering_timer); } void RenderingManager::slot_frame_end() { m_status_bar.stop_rendering_time_display(); } void RenderingManager::slot_clear_shading_override() { m_override_shading = false; reinitialize_rendering(); } void RenderingManager::slot_set_shading_override() { QAction* action = qobject_cast<QAction*>(sender()); const string shading_mode = action->data().toString().toStdString(); m_override_shading = true; m_override_shading_mode = shading_mode; reinitialize_rendering(); } void RenderingManager::slot_camera_changed() { restart_rendering(); } } // namespace studio } // namespace appleseed <commit_msg>trigger a render widget update when the view changes.<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz // // 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. // // Interface header. #include "renderingmanager.h" // appleseed.studio headers. #include "mainwindow/rendering/renderwidget.h" #include "mainwindow/statusbar.h" // appleseed.shared headers. #include "application/application.h" // appleseed.renderer headers. #include "renderer/api/aov.h" #include "renderer/api/camera.h" #include "renderer/api/frame.h" #include "renderer/api/project.h" #include "renderer/api/scene.h" // appleseed.foundation headers. #include "foundation/image/analysis.h" #include "foundation/image/image.h" #include "foundation/math/transform.h" #include "foundation/utility/string.h" // boost headers. #include "boost/filesystem/path.hpp" // Qt headers. #include <QAction> #include <QApplication> #include <QTimerEvent> using namespace appleseed::shared; using namespace boost; using namespace foundation; using namespace renderer; using namespace std; namespace appleseed { namespace studio { // // RenderingManager class implementation. // namespace { class MasterRendererThread : public QThread { public: // Constructor. explicit MasterRendererThread(MasterRenderer* master_renderer) : m_master_renderer(master_renderer) { } private: MasterRenderer* m_master_renderer; // The starting point for the thread. virtual void run() { m_master_renderer->render(); } }; } RenderingManager::RenderingManager(StatusBar& status_bar) : m_status_bar(status_bar) , m_project(0) , m_render_widget(0) , m_override_shading(false) { // // The connections below are using the Qt::BlockingQueuedConnection connection type. // // They are using a queued connection because the emitting thread is different from // the receiving thread (the emitting thread is the master renderer thread, and the // receiving thread is the UI thread of the main window (presumably). // // They are using a blocking queue connection because we need the receiving slot to // have returned in the receiving thread before the emitting thread can continue. // // See http://doc.trolltech.com/4.6/qt.html#ConnectionType-enum for more details. // connect( &m_renderer_controller, SIGNAL(signal_frame_begin()), this, SLOT(slot_frame_begin()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_frame_end()), this, SLOT(slot_frame_end()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_begin()), this, SLOT(slot_rendering_begin()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_success()), this, SLOT(slot_rendering_end()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_abort()), this, SLOT(slot_rendering_end()), Qt::BlockingQueuedConnection); connect( &m_renderer_controller, SIGNAL(signal_rendering_success()), this, SIGNAL(signal_rendering_end())); connect( &m_renderer_controller, SIGNAL(signal_rendering_abort()), this, SIGNAL(signal_rendering_end())); } void RenderingManager::start_rendering( Project* project, const ParamArray& params, const bool highlight_tiles, RenderWidget* render_widget) { m_project = project; m_render_widget = render_widget; m_camera_controller.reset( new CameraController( m_render_widget, m_project->get_scene())); connect( m_camera_controller.get(), SIGNAL(signal_camera_changed()), this, SLOT(slot_camera_changed())); connect( m_camera_controller.get(), SIGNAL(signal_camera_changed()), this, SIGNAL(signal_camera_changed())); m_tile_callback_factory.reset( new QtTileCallbackFactory( m_render_widget, highlight_tiles)); m_master_renderer.reset( new MasterRenderer( *m_project, params, &m_renderer_controller, m_tile_callback_factory.get())); m_master_renderer_thread.reset( new MasterRendererThread(m_master_renderer.get())); m_master_renderer_thread->start(); } bool RenderingManager::is_rendering() const { return m_master_renderer_thread.get() && m_master_renderer_thread->isRunning(); } void RenderingManager::wait_until_rendering_end() { while (is_rendering()) { QApplication::processEvents(); } } void RenderingManager::abort_rendering() { RENDERER_LOG_DEBUG("aborting rendering..."); m_renderer_controller.set_status(IRendererController::AbortRendering); } void RenderingManager::restart_rendering() { m_renderer_controller.set_status(IRendererController::RestartRendering); } void RenderingManager::reinitialize_rendering() { m_renderer_controller.set_status(IRendererController::ReinitializeRendering); } void RenderingManager::timerEvent(QTimerEvent* event) { if (event->timerId() == m_render_widget_update_timer.timerId()) m_render_widget->update(); else QObject::timerEvent(event); } void RenderingManager::print_final_rendering_time() { const double rendering_time = m_rendering_timer.get_seconds(); const string rendering_time_string = pretty_time(rendering_time, 3); RENDERER_LOG_INFO("rendering finished in %s.", rendering_time_string.c_str()); m_status_bar.set_text("Rendering finished in " + rendering_time_string); } void RenderingManager::print_average_luminance() { Image final_image(m_project->get_frame()->image()); m_project->get_frame()->transform_to_output_color_space(final_image); const double average_luminance = compute_average_luminance(final_image); RENDERER_LOG_DEBUG( "final average luminance is %s.", pretty_scalar(average_luminance, 6).c_str()); } void RenderingManager::archive_frame_to_disk() { RENDERER_LOG_INFO("archiving frame to disk..."); const filesystem::path autosave_path = filesystem::path(Application::get_root_path()) / "images/autosave/"; m_project->get_frame()->archive( autosave_path.directory_string().c_str()); } void RenderingManager::slot_rendering_begin() { assert(m_master_renderer.get()); if (m_override_shading) { m_master_renderer->get_parameters() .push("shading_engine") .push("override_shading") .insert("mode", m_override_shading_mode); } else { m_master_renderer->get_parameters() .push("shading_engine") .dictionaries().remove("override_shading"); } const int UpdateRate = 5; m_render_widget_update_timer.start(1000 / UpdateRate, this); } void RenderingManager::slot_rendering_end() { m_render_widget_update_timer.stop(); m_render_widget->update(); print_final_rendering_time(); print_average_luminance(); archive_frame_to_disk(); // Prevent manipulation of the camera after rendering has ended. m_camera_controller.reset(); } void RenderingManager::slot_frame_begin() { m_renderer_controller.set_status(IRendererController::ContinueRendering); m_camera_controller->update_camera_transform(); m_rendering_timer.start(); m_status_bar.start_rendering_time_display(&m_rendering_timer); } void RenderingManager::slot_frame_end() { m_status_bar.stop_rendering_time_display(); m_render_widget->update(); } void RenderingManager::slot_clear_shading_override() { m_override_shading = false; reinitialize_rendering(); } void RenderingManager::slot_set_shading_override() { QAction* action = qobject_cast<QAction*>(sender()); const string shading_mode = action->data().toString().toStdString(); m_override_shading = true; m_override_shading_mode = shading_mode; reinitialize_rendering(); } void RenderingManager::slot_camera_changed() { restart_rendering(); } } // namespace studio } // namespace appleseed <|endoftext|>
<commit_before>//UPCOMING BOOST LOCALE! //http://cppcms.sourceforge.net/boost_locale/html/index.html //#include <unicode/ustring.h> //#include <boost/regex/icu.hpp> /* http://www.unicode.org/versions/Unicode5.0.0/ch02.pdf#G13708 boost reg expressions and icu http://www.boost.org/libs/regex/doc/icu_strings.html http://en.wikipedia.org/wiki/UTF-8 http://unicode.org/faq/utf_bom.html Test words (this document is saved as UTF8 unicode) Iñtërnâtiônàlizætiøn windows cp1252 في اليونا web page to try out multilingual http://www.unicode.org/iuc/iuc10/x-utf8.html notes: 0. bytes c0 c1 f5-ff never appear in utf8 1. postgres bytea can be treated as UTF8 for comparisons/indexing etc without conversion 2. icu likes everything to be in utf16 3. icu offers a fast conversion between utf8 and utf16 but can only replace illegal bytes with one character fast (neosys uses a modified one that converts between F8-FF and u2558-u255F) icu conversion functions allow custom function be convert illegal UTF8 pick field character bytes with some arbitrary unicode code points but what speed? this was not found/used ... maybe better than the custom function mentioned above Strategy 1: Store utf16 in postgres bytea and provide convertion to bytea(utf16)->utf8->text/number/date etc for sql comparisons/indexing etc pros: no codeconversion during read/write/calculate cons: continuous conversion on database operations with/by clauses double database size double data traffic read/write/calculate Strategy 2: Store utf8 in postgres bytea and convert to/from utf16 in the client program on read/write/calculate pros: no code conversion during database operations with/by clauses smallest database size smallest data traffic read/write/calculate pros: codeconversion during every read/write/calculate UTF8 versus UTF16 implementation discussion ------------------------------------------- this 2005 document advocates UTF8 but more for documents/interchange than implementations http://www-128.ibm.com/developerworks/xml/library/x-utf8/ size issue is NOT the main thing - compatibility with api is the main problem size issue is important for memory throughput and therefore processing speed UTF16 is 100% larger for non ascii (0-127) characters UTF8 is 50% larger than UTF16 for asian and CJK characters (but one CJK char = one word = many characters) UTF8 can be thought of as a non-adaptive huffman compression format(ie "common" ascii requires fewer bits) UTF8 is the only format not to have the endian issue ORACLE/DB2/JBASE/POSTGRES is UTF8, SAP is UTF32, Windows/MSSQL is UTF16 UTF16 is very poorly supported on std Linux libraries since wchar_t is 4 bytes (gcc has compiler option for 2 bytes) icu offers UTF16 string replacement but then we are intimately tied to icu library UTF8 is supported very broadly in unix/linux libraries windows/java/icu/iisjavascript is UTF16 (unavoidable conversion into UTF16 in IIS even if web page is sent as UTF8!) i18n web pages are UTF8 in the end UTF8 negatives character indexing/iteration using integers is slow (until code migrates to proper iterators) slower for asian and CJK complicated bit pattern doesnt handle binary (lots of illegal characters/UTF16 doesnt have this problem IF you ignore surrogates as Java does) UTF16 negatives probably become highly dependent on icu (string instead of std::wstring) slower for ascii doesnt work with c std strings (unless you use java style encoding c0 80 to represent nulls) endian issues not a problem for implementations only for transmissions so in the end this is a compatibility issue Unicode in DB2 version 9 (UTF8) http://publib.boulder.ibm.com/infocenter/db2luw/v9/topic/com.ibm.db2.udb.admin.doc/doc/c0004821.htm lots of good explanation including - during utf16->utf8 conversion surrogate pairs used to be converted to two x three byte sequences but no more. - they treat combining characters separately - implements UCA for collation qt strings are unicode */ //#include <boost/algorithm/string.hpp> #include <wctype.h> #if defined(_MSC_VER) #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include <string.h> #endif #include <boost/scoped_array.hpp> #include <locale.h> #define MV_NO_NARROW #include <exodus/mv.h> #include <exodus/mvexceptions.h> namespace exodus { int var::localeAwareCompare(const std::wstring& str1, const std::wstring& str2) const { if (str1.length()==0&&str2.length()==0) return 0; #if defined(_MSC_VER) && defined(UNICODE) /* Now of course this points to what may be the best solution for a single function that will let you pass string length, ignore case, choose an appropriate locale, and work in different versions of Windows -- the master NLS collation function, CompareStringW! */ int comparison; //CompareStringW //comparison=CompareStringW(GetUserDefaultLCID(), 0, comparison=CompareStringW(GetThreadLocale(), 0, (TCHAR*)str1.data(), int(str1.length()), (TCHAR*)str2.data(), int(str2.length())); switch (comparison) { case CSTR_LESS_THAN: return -1; case CSTR_GREATER_THAN: return 1; default: return 0; } #elif defined(_MACOS) // order strings the same way as native applications do, and also respects // the "Order for sorted lists" setting in the International preferences panel const CFStringRef thisString=CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault, reinterpret_cast<const UniChar *>(str1.data()),str1.length(),kCFAllocatorNull); const CFStringRef otherString=CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault, reinterpret_cast<const UniChar *>(data2), length2, kCFAllocatorNull); const int result = CFStringCompare(thisString, otherString, kCFCompareLocalized); CFRelease(thisString); CFRelease(otherString); return result; //why not collate::compare? //#elseif defined(_UNIX) #elif defined(strcoll) #elif !defined(XYZZZZ) // setlocale (LC_COLLATE, "en_US.UTF-8"); return wcscoll(str1.c_str(),str2.c_str()); #else #error stop here return str1.compare(str2); #endif } var& var::localeAwareChangeCase(const int lowerupper) { if (var_mvstr.length()==0) return *this; #if defined(_MSC_VER) && defined(UNICODE) //TODO http://stackoverflow.com/questions/1767946/getthreadlocale-returns-different-value-than-getuserdefaultlcid //Microsoft is deprecating the Locale ID in favor of the Locale Name from Vista onwards /* http://msdn.microsoft.com/en-us/library/dd318700%28v=VS.85%29.aspx int LCMapString( __in LCID Locale, __in DWORD dwMapFlags, __in LPCTSTR lpSrcStr, __in int cchSrc, __out LPTSTR lpDestStr, __in int cchDest ); return 0 if it DOESNT succeed GetLastError() * ERROR_INSUFFICIENT_BUFFER. A supplied buffer size was not large enough, or it was incorrectly set to NULL. * ERROR_INVALID_FLAGS. The values supplied for flags were not valid. * ERROR_INVALID_PARAMETER. Any of the parameter values was invalid. */ //uppercasing can double the number of characters (eg german b to SS) can it triple? int buffersize=(int) var_mvstr.length()*2+2; boost::scoped_array<TCHAR> buffer( new TCHAR [buffersize]); if (buffer==0) throw MVException(var(L"Out of memory in changecase(). Need ")^int(buffersize)^L" characters"); int tolowerupper=LCMAP_LINGUISTIC_CASING; if (lowerupper==1) tolowerupper+=LCMAP_LOWERCASE; else if (lowerupper==2) tolowerupper+=LCMAP_UPPERCASE; //LCMapStringW int outputsize=LCMapStringW( GetThreadLocale(), tolowerupper, (TCHAR*)var_mvstr.data(), (int) var_mvstr.length(), buffer.get(), (int) buffersize); //cant convert for some reason. see above if (!outputsize) { //for now only ascii conversion if (lowerupper==1) return converter(UPPERCASE_,LOWERCASE_); else if (lowerupper==2) return converter(LOWERCASE_, UPPERCASE_); } var_mvstr=std::wstring(buffer.get(),outputsize); return *this; #elif 1 //for now only ascii conversion //if (lowerupper==1) // converter(UPPERCASE_,LOWERCASE_); //else if (lowerupper==2) // converter(LOWERCASE_, UPPERCASE_); //for now only fairly simple one for one conversion //if (lowerupper==1) // boost::to_lower(var_mvstr); //else if (lowerupper==2) // boost::to_upper(var_mvstr); size_t length=var_mvstr.length(); if (lowerupper==1) for (size_t ptr=0; ptr<length; ++ptr) var_mvstr[ptr]=towlower(var_mvstr[ptr]); else if (lowerupper==2) for (size_t ptr=0; ptr<length; ++ptr) var_mvstr[ptr]=towupper(var_mvstr[ptr]); return *this; #elif defined(_MACOS) //why not collate::compare? //#elseif defined(_UNIX) #elif defined(strcoll) #elif !defined(XYZZZZ) //// setlocale (LC_COLLATE, "en_US.UTF-8"); // return wcscoll(str1.c_str(),str2.c_str()); //TODO unicode/native conversion converter(LOWERCASE_, UPPERCASE_); #else #error stop here return str1.compare(str2); #endif } bool var::setxlocale() const { #if defined(_MSC_VER) && defined(UNICODE) /* http://msdn.microsoft.com/en-us/library/dd374051%28v=VS.85%29.aspx //locale list //XP 2003 http://msdn.microsoft.com/en-us/goglobal/bb895996.aspx //http://msdn.microsoft.com/en-us/goglobal/bb964664.aspx BOOL SetThreadLocale( __in LCID Locale ); */ //GetSystemDefaultLCID() //GetUserDefaultLCID() //LCID locale_lcid=1031;//German Standard //LCID locale_lcid=1032;//Greek //LCID locale_lcid=1055;//Turkish return SetThreadLocale((*this).toInt())!=NULL; //#elif defined(_MACOS) #else THISIS(L"bool var::setxlocale() const") THISISSTRING() //make a thread local locale if not done already //TODO do this in thread creation //TODO destroy threalocale in thread destruction *OTHERWISE MEMORY LEAK //to avoid checking on every setxlocale if (uselocale(NULL)==uselocale(LC_GLOBAL_LOCALE)) uselocale(duplocale(uselocale(LC_GLOBAL_LOCALE))); return setlocale(LC_ALL,(*this).tostring().c_str())!=NULL; #endif } var& var::getxlocale() { #if defined(_MSC_VER) && defined(UNICODE) *this=(int)GetThreadLocale(); return *this; //#elif defined(_MACOS) #else //return ""; *this=var(setlocale(LC_ALL,NULL)); return *this; #endif } } // namespace exodus <commit_msg>minor update of localeAwareCompare()<commit_after>//UPCOMING BOOST LOCALE! //http://cppcms.sourceforge.net/boost_locale/html/index.html //#include <unicode/ustring.h> //#include <boost/regex/icu.hpp> /* http://www.unicode.org/versions/Unicode5.0.0/ch02.pdf#G13708 boost reg expressions and icu http://www.boost.org/libs/regex/doc/icu_strings.html http://en.wikipedia.org/wiki/UTF-8 http://unicode.org/faq/utf_bom.html Test words (this document is saved as UTF8 unicode) Iñtërnâtiônàlizætiøn windows cp1252 في اليونا web page to try out multilingual http://www.unicode.org/iuc/iuc10/x-utf8.html notes: 0. bytes c0 c1 f5-ff never appear in utf8 1. postgres bytea can be treated as UTF8 for comparisons/indexing etc without conversion 2. icu likes everything to be in utf16 3. icu offers a fast conversion between utf8 and utf16 but can only replace illegal bytes with one character fast (neosys uses a modified one that converts between F8-FF and u2558-u255F) icu conversion functions allow custom function be convert illegal UTF8 pick field character bytes with some arbitrary unicode code points but what speed? this was not found/used ... maybe better than the custom function mentioned above Strategy 1: Store utf16 in postgres bytea and provide convertion to bytea(utf16)->utf8->text/number/date etc for sql comparisons/indexing etc pros: no codeconversion during read/write/calculate cons: continuous conversion on database operations with/by clauses double database size double data traffic read/write/calculate Strategy 2: Store utf8 in postgres bytea and convert to/from utf16 in the client program on read/write/calculate pros: no code conversion during database operations with/by clauses smallest database size smallest data traffic read/write/calculate pros: codeconversion during every read/write/calculate UTF8 versus UTF16 implementation discussion ------------------------------------------- this 2005 document advocates UTF8 but more for documents/interchange than implementations http://www-128.ibm.com/developerworks/xml/library/x-utf8/ size issue is NOT the main thing - compatibility with api is the main problem size issue is important for memory throughput and therefore processing speed UTF16 is 100% larger for non ascii (0-127) characters UTF8 is 50% larger than UTF16 for asian and CJK characters (but one CJK char = one word = many characters) UTF8 can be thought of as a non-adaptive huffman compression format(ie "common" ascii requires fewer bits) UTF8 is the only format not to have the endian issue ORACLE/DB2/JBASE/POSTGRES is UTF8, SAP is UTF32, Windows/MSSQL is UTF16 UTF16 is very poorly supported on std Linux libraries since wchar_t is 4 bytes (gcc has compiler option for 2 bytes) icu offers UTF16 string replacement but then we are intimately tied to icu library UTF8 is supported very broadly in unix/linux libraries windows/java/icu/iisjavascript is UTF16 (unavoidable conversion into UTF16 in IIS even if web page is sent as UTF8!) i18n web pages are UTF8 in the end UTF8 negatives character indexing/iteration using integers is slow (until code migrates to proper iterators) slower for asian and CJK complicated bit pattern doesnt handle binary (lots of illegal characters/UTF16 doesnt have this problem IF you ignore surrogates as Java does) UTF16 negatives probably become highly dependent on icu (string instead of std::wstring) slower for ascii doesnt work with c std strings (unless you use java style encoding c0 80 to represent nulls) endian issues not a problem for implementations only for transmissions so in the end this is a compatibility issue Unicode in DB2 version 9 (UTF8) http://publib.boulder.ibm.com/infocenter/db2luw/v9/topic/com.ibm.db2.udb.admin.doc/doc/c0004821.htm lots of good explanation including - during utf16->utf8 conversion surrogate pairs used to be converted to two x three byte sequences but no more. - they treat combining characters separately - implements UCA for collation qt strings are unicode */ //#include <boost/algorithm/string.hpp> #include <wctype.h> #if defined(_MSC_VER) #define WIN32_LEAN_AND_MEAN #include <windows.h> #else #include <string.h> #endif #include <boost/scoped_array.hpp> #include <locale.h> #define MV_NO_NARROW #include <exodus/mv.h> #include <exodus/mvexceptions.h> namespace exodus { int var::localeAwareCompare(const std::wstring& str1, const std::wstring& str2) const { if (str1.length()==0&&str2.length()==0) return 0; #if defined(_MSC_VER) && defined(UNICODE) /* Now of course this points to what may be the best solution for a single function that will let you pass string length, ignore case, choose an appropriate locale, and work in different versions of Windows -- the master NLS collation function, CompareStringW ! */ int comparison; //CompareStringW //comparison=CompareStringW(GetUserDefaultLCID(), 0, // UNICODE is always defined so CompareString is CompareStringW. comparison=CompareString(GetThreadLocale(), 0, (TCHAR*)str1.data(), int(str1.length()), (TCHAR*)str2.data(), int(str2.length())); switch (comparison) { case CSTR_LESS_THAN: return -1; case CSTR_GREATER_THAN: return 1; case CSTR_EQUAL: return 0; default: throw MVException( L"localeAwareCompare(" ^ str1 ^ L", " ^ str2 ^ L")\n"); } #elif defined(_MACOS) // order strings the same way as native applications do, and also respects // the "Order for sorted lists" setting in the International preferences panel const CFStringRef thisString=CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault, reinterpret_cast<const UniChar *>(str1.data()),str1.length(),kCFAllocatorNull); const CFStringRef otherString=CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault, reinterpret_cast<const UniChar *>(data2), length2, kCFAllocatorNull); const int result = CFStringCompare(thisString, otherString, kCFCompareLocalized); CFRelease(thisString); CFRelease(otherString); return result; //why not collate::compare? //#elseif defined(_UNIX) #elif defined(strcoll) #elif !defined(XYZZZZ) // setlocale (LC_COLLATE, "en_US.UTF-8"); return wcscoll(str1.c_str(),str2.c_str()); #else #error stop here return str1.compare(str2); #endif } var& var::localeAwareChangeCase(const int lowerupper) { if (var_mvstr.length()==0) return *this; #if defined(_MSC_VER) && defined(UNICODE) //TODO http://stackoverflow.com/questions/1767946/getthreadlocale-returns-different-value-than-getuserdefaultlcid //Microsoft is deprecating the Locale ID in favor of the Locale Name from Vista onwards /* http://msdn.microsoft.com/en-us/library/dd318700%28v=VS.85%29.aspx int LCMapString( __in LCID Locale, __in DWORD dwMapFlags, __in LPCTSTR lpSrcStr, __in int cchSrc, __out LPTSTR lpDestStr, __in int cchDest ); return 0 if it DOESNT succeed GetLastError() * ERROR_INSUFFICIENT_BUFFER. A supplied buffer size was not large enough, or it was incorrectly set to NULL. * ERROR_INVALID_FLAGS. The values supplied for flags were not valid. * ERROR_INVALID_PARAMETER. Any of the parameter values was invalid. */ //uppercasing can double the number of characters (eg german b to SS) can it triple? int buffersize=(int) var_mvstr.length()*2+2; boost::scoped_array<TCHAR> buffer( new TCHAR [buffersize]); if (buffer==0) throw MVException(var(L"Out of memory in changecase(). Need ")^int(buffersize)^L" characters"); int tolowerupper=LCMAP_LINGUISTIC_CASING; if (lowerupper==1) tolowerupper+=LCMAP_LOWERCASE; else if (lowerupper==2) tolowerupper+=LCMAP_UPPERCASE; //LCMapStringW int outputsize=LCMapStringW( GetThreadLocale(), tolowerupper, (TCHAR*)var_mvstr.data(), (int) var_mvstr.length(), buffer.get(), (int) buffersize); //cant convert for some reason. see above if (!outputsize) { //for now only ascii conversion if (lowerupper==1) return converter(UPPERCASE_,LOWERCASE_); else if (lowerupper==2) return converter(LOWERCASE_, UPPERCASE_); } var_mvstr=std::wstring(buffer.get(),outputsize); return *this; #elif 1 //for now only ascii conversion //if (lowerupper==1) // converter(UPPERCASE_,LOWERCASE_); //else if (lowerupper==2) // converter(LOWERCASE_, UPPERCASE_); //for now only fairly simple one for one conversion //if (lowerupper==1) // boost::to_lower(var_mvstr); //else if (lowerupper==2) // boost::to_upper(var_mvstr); size_t length=var_mvstr.length(); if (lowerupper==1) for (size_t ptr=0; ptr<length; ++ptr) var_mvstr[ptr]=towlower(var_mvstr[ptr]); else if (lowerupper==2) for (size_t ptr=0; ptr<length; ++ptr) var_mvstr[ptr]=towupper(var_mvstr[ptr]); return *this; #elif defined(_MACOS) //why not collate::compare? //#elseif defined(_UNIX) #elif defined(strcoll) #elif !defined(XYZZZZ) //// setlocale (LC_COLLATE, "en_US.UTF-8"); // return wcscoll(str1.c_str(),str2.c_str()); //TODO unicode/native conversion converter(LOWERCASE_, UPPERCASE_); #else #error stop here return str1.compare(str2); #endif } bool var::setxlocale() const { #if defined(_MSC_VER) && defined(UNICODE) /* http://msdn.microsoft.com/en-us/library/dd374051%28v=VS.85%29.aspx //locale list //XP 2003 http://msdn.microsoft.com/en-us/goglobal/bb895996.aspx //http://msdn.microsoft.com/en-us/goglobal/bb964664.aspx BOOL SetThreadLocale( __in LCID Locale ); */ //GetSystemDefaultLCID() //GetUserDefaultLCID() //LCID locale_lcid=1031;//German Standard //LCID locale_lcid=1032;//Greek //LCID locale_lcid=1055;//Turkish return SetThreadLocale((*this).toInt())!=NULL; //#elif defined(_MACOS) #else THISIS(L"bool var::setxlocale() const") THISISSTRING() //make a thread local locale if not done already //TODO do this in thread creation //TODO destroy threalocale in thread destruction *OTHERWISE MEMORY LEAK //to avoid checking on every setxlocale if (uselocale(NULL)==uselocale(LC_GLOBAL_LOCALE)) uselocale(duplocale(uselocale(LC_GLOBAL_LOCALE))); return setlocale(LC_ALL,(*this).tostring().c_str())!=NULL; #endif } var& var::getxlocale() { #if defined(_MSC_VER) && defined(UNICODE) *this=(int)GetThreadLocale(); return *this; //#elif defined(_MACOS) #else //return ""; *this=var(setlocale(LC_ALL,NULL)); return *this; #endif } } // namespace exodus <|endoftext|>
<commit_before>/* $Id: alara.C,v 1.15 2002-05-06 18:03:24 wilsonp Exp $ */ #include "alara.h" #include "Input/Input.h" #include "Chains/Root.h" #include "Util/Statistics.h" #include "Output/Result.h" /* See why Paul is using these silly STL things? */ int chainCode = 0; /*! This list of elemental symbols is specially formatted to be used for looking up the atomic number of a given element. For each element with atomic number, Z, and symbol, CC, the string " CC " exists at index Z-1. */ const char *SYMBOLS=" h he li be b c n o f ne na mg al si p s cl ar \ k ca sc ti v cr mn fe co ni cu zn ga ge as se br kr rb sr y zr nb mo tc ru \ rh pd ag cd in sn sb te i xe cs ba la ce pr nd pm sm eu gd tb dy ho er tm \ yb lu hf ta w re os ir pt au hg tl pb bi po at rn fr ra ac th pa u np \ pu am cm bk cf es fm md no lr "; /// This is derived from a CVS variable to determine the version string static char *id="$Name: not supported by cvs2svn $"; /*! This is the standard help/usage message that is printed when an incorrect command-line option is used, or when -h is used. */ static char *helpmsg="\ usage: %s [-h] [-r] [-t <tree_filename>] [-V] [-v <n>] [<input_filename>] \n\ \t -h Show this message\n\ \t -r Restart option for calculating new respones\n\ \t -t <tree_filename> Create tree file with given name\n\ \t -V Show version\n\ \t -v <n> Set verbosity level\n\ \t <input_filename> Name of input file\n\ See Users' Guide for more info.\n\ (http://www.cae.wisc.edu/~wilsonp/projects/ALARA/users.guide.html/)\n"; int main(int argc, char *argv[]) { int argNum = 1; int solved = FALSE; char *inFname = NULL; Root* rootList = new Root; topSchedule* schedule; verbose(-1,"ALARA %s",id); while (argNum<argc) { if (argv[argNum][0] != '-') if (inFname == NULL) { inFname = new char[strlen(argv[argNum])+1]; strcpy(inFname,argv[argNum]); argNum++; /* get next argument */ continue; } else error(1,"Only one input filename can be specified: %s.",inFname); while (argv[argNum][0] == '-') argv[argNum]++; switch (argv[argNum][0]) { #ifdef DVLPR case 'd': if (argv[argNum][1] == '\0') { debug_level = atoi(argv[argNum+1]); argNum+=2; } else { debug_level = atoi(argv[argNum]+1); argNum++; } debug(0,"Set debug level to %d.",debug_level); break; #endif case 'v': if (argv[argNum][1] == '\0') { verb_level = atoi(argv[argNum+1]); argNum+=2; } else { verb_level = atoi(argv[argNum]+1); argNum++; } verbose(0,"Set verbose level to %d.",verb_level); break; case 'r': verbose(0,"Reusing binary dump data."); solved=TRUE; argNum+=1; break; case 't': if (argv[argNum][1] == '\0') { Statistics::initTree(argv[argNum+1]); verbose(0,"Openned tree file %s.",argv[argNum+1]); argNum+=2; } else { Statistics::initTree(argv[argNum]+1); verbose(0,"Openned tree file %s.",argv[argNum]+1); argNum++; } break; case 'h': verbose(-1,helpmsg,argv[0]); case 'V': exit(0); break; default: { verbose(-1,helpmsg,argv[0]); error(0,"Invlaid option: %s.",argv[argNum]); } } } Input problemInput(inFname); /* INPUT */ verbose(0,"Starting problem input processing."); verbose(1,"Reading input."); problemInput.read(); verbose(1,"Cross-checking input for completeness and self-consistency."); problemInput.xCheck(); verbose(1,"Preprocessing input."); problemInput.preProc(rootList,schedule); if (!solved) { verbose(0,"Starting problem solution."); rootList->solve(schedule); verbose(1,"Solved problem."); } Result::resetBinDump(); problemInput.postProc(rootList); verbose(0,"Output."); Result::closeBinDump(); delete rootList; delete inFname; } <commit_msg>Added option to skip post-processing.<commit_after>/* $Id: alara.C,v 1.16 2002-05-06 19:10:38 wilsonp Exp $ */ #include "alara.h" #include "Input/Input.h" #include "Chains/Root.h" #include "Util/Statistics.h" #include "Output/Result.h" /* See why Paul is using these silly STL things? */ int chainCode = 0; /*! This list of elemental symbols is specially formatted to be used for looking up the atomic number of a given element. For each element with atomic number, Z, and symbol, CC, the string " CC " exists at index Z-1. */ const char *SYMBOLS=" h he li be b c n o f ne na mg al si p s cl ar \ k ca sc ti v cr mn fe co ni cu zn ga ge as se br kr rb sr y zr nb mo tc ru \ rh pd ag cd in sn sb te i xe cs ba la ce pr nd pm sm eu gd tb dy ho er tm \ yb lu hf ta w re os ir pt au hg tl pb bi po at rn fr ra ac th pa u np \ pu am cm bk cf es fm md no lr "; /// This is derived from a CVS variable to determine the version string static char *id="$Name: not supported by cvs2svn $"; /*! This is the standard help/usage message that is printed when an incorrect command-line option is used, or when -h is used. */ static char *helpmsg="\ usage: %s [-h] [-r] [-t <tree_filename>] [-V] [-v <n>] [<input_filename>] \n\ \t -h Show this message\n\ \t -c Option to only calculate chains and skip post-processing\n\ \t -r \"Restart\" option to skip chain calculation and only post-process\n\ \t -t <tree_filename> Create tree file with given name\n\ \t -V Show version\n\ \t -v <n> Set verbosity level\n\ \t <input_filename> Name of input file\n\ See Users' Guide for more info.\n\ (http://www.cae.wisc.edu/~wilsonp/projects/ALARA/users.guide.html/)\n"; int main(int argc, char *argv[]) { int argNum = 1; int solved = FALSE; int doOutput = TRUE; char *inFname = NULL; Root* rootList = new Root; topSchedule* schedule; verbose(-1,"ALARA %s",id); while (argNum<argc) { if (argv[argNum][0] != '-') if (inFname == NULL) { inFname = new char[strlen(argv[argNum])+1]; strcpy(inFname,argv[argNum]); argNum++; /* get next argument */ continue; } else error(1,"Only one input filename can be specified: %s.",inFname); while (argv[argNum][0] == '-') argv[argNum]++; switch (argv[argNum][0]) { #ifdef DVLPR case 'd': if (argv[argNum][1] == '\0') { debug_level = atoi(argv[argNum+1]); argNum+=2; } else { debug_level = atoi(argv[argNum]+1); argNum++; } debug(0,"Set debug level to %d.",debug_level); break; #endif case 'v': if (argv[argNum][1] == '\0') { verb_level = atoi(argv[argNum+1]); argNum+=2; } else { verb_level = atoi(argv[argNum]+1); argNum++; } verbose(0,"Set verbose level to %d.",verb_level); break; case 'c': verbose(0,"Calculating chains ONLY."); doOutput=FALSE; argNum+=1; break; case 'r': verbose(0,"Reusing binary dump data."); solved=TRUE; argNum+=1; break; case 't': if (argv[argNum][1] == '\0') { Statistics::initTree(argv[argNum+1]); verbose(0,"Openned tree file %s.",argv[argNum+1]); argNum+=2; } else { Statistics::initTree(argv[argNum]+1); verbose(0,"Openned tree file %s.",argv[argNum]+1); argNum++; } break; case 'h': verbose(-1,helpmsg,argv[0]); case 'V': exit(0); break; default: { verbose(-1,helpmsg,argv[0]); error(0,"Invlaid option: %s.",argv[argNum]); } } } Input problemInput(inFname); /* INPUT */ verbose(0,"Starting problem input processing."); verbose(1,"Reading input."); problemInput.read(); verbose(1,"Cross-checking input for completeness and self-consistency."); problemInput.xCheck(); verbose(1,"Preprocessing input."); problemInput.preProc(rootList,schedule); if (!solved) { verbose(0,"Starting problem solution."); rootList->solve(schedule); verbose(1,"Solved problem."); } if (doOutput) { Result::resetBinDump(); problemInput.postProc(rootList); verbose(0,"Output."); } Result::closeBinDump(); delete rootList; delete inFname; } <|endoftext|>
<commit_before>/* * Copyright 2007-2022 CM4all GmbH * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION 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. */ #pragma once #include "SliceAllocation.hxx" #include "util/ForeignFifoBuffer.hxx" #include <stdint.h> class SlicePool; class SliceArea; class SliceFifoBuffer : public ForeignFifoBuffer<std::byte> { SliceAllocation allocation; public: SliceFifoBuffer() noexcept:ForeignFifoBuffer<std::byte>(nullptr) {} explicit SliceFifoBuffer(SlicePool &pool) noexcept :ForeignFifoBuffer<std::byte>(nullptr) { Allocate(pool); } SliceFifoBuffer(SliceFifoBuffer &&src) noexcept :ForeignFifoBuffer(std::move(src)), allocation(std::move(src.allocation)) { src.SetNull(); } void swap(SliceFifoBuffer &other) noexcept { using std::swap; ForeignFifoBuffer<std::byte>::swap(other); swap(allocation, other.allocation); } friend void swap(SliceFifoBuffer &a, SliceFifoBuffer &b) noexcept { a.swap(b); } void Allocate(SlicePool &pool) noexcept; void Free() noexcept; bool IsDefinedAndFull() const noexcept { return IsDefined() && IsFull(); } void AllocateIfNull(SlicePool &pool) noexcept { if (IsNull()) Allocate(pool); } void FreeIfDefined() noexcept { if (IsDefined()) Free(); } void FreeIfEmpty() noexcept { if (empty()) FreeIfDefined(); } /** * If this buffer is empty, free the buffer and reallocate a new * one. This is useful to work around #SliceArea fragmentation. */ void CycleIfEmpty(SlicePool &pool) noexcept { if (IsDefined() && empty()) { Free(); Allocate(pool); } } using ForeignFifoBuffer<std::byte>::MoveFrom; /** * Move as much data as possible from the specified buffer. If * the destination buffer is empty, the buffers are swapped. Care * is taken that neither buffer suddenly becomes nulled * afterwards, because some callers may not be prepared for this. */ void MoveFrom(SliceFifoBuffer &src) noexcept { if (empty() && !IsNull() && !src.IsNull()) /* optimized special case: swap buffer pointers instead of copying data */ swap(src); else ForeignFifoBuffer<std::byte>::MoveFrom(src); } /** * Like MoveFrom(), but allow the destination to be nulled. This * is useful when #src can be freed, but this object cannot. */ void MoveFromAllowNull(SliceFifoBuffer &src) noexcept { if (empty() && (!src.empty() || !IsNull())) /* optimized special case: swap buffer pointers instead of copying data */ swap(src); else ForeignFifoBuffer<std::byte>::MoveFrom(src); } /** * Like MoveFrom(), but allow the source to be nulled. This is * useful when this object can be freed, but #src cannot. */ void MoveFromAllowSrcNull(SliceFifoBuffer &src) noexcept { if (empty() && (!src.empty() || IsNull())) /* optimized special case: swap buffer pointers instead of copying data */ swap(src); else ForeignFifoBuffer<std::byte>::MoveFrom(src); } /** * Like MoveFrom(), but allow both to be nulled. */ void MoveFromAllowBothNull(SliceFifoBuffer &src) noexcept { if (empty()) /* optimized special case: swap buffer pointers instead of copying data */ swap(src); else ForeignFifoBuffer<std::byte>::MoveFrom(src); } /** * Swaps the two buffers if #src is nulled. This is useful when * #src can be freed, but this object cannot. */ void SwapIfNull(SliceFifoBuffer &src) noexcept { if (src.IsNull() && empty() && !IsNull()) swap(src); } }; <commit_msg>memory/SliceFifoBuffer: remove method MoveFrom(SliceFifoBuffer)<commit_after>/* * Copyright 2007-2022 CM4all GmbH * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION 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. */ #pragma once #include "SliceAllocation.hxx" #include "util/ForeignFifoBuffer.hxx" #include <stdint.h> class SlicePool; class SliceArea; class SliceFifoBuffer : public ForeignFifoBuffer<std::byte> { SliceAllocation allocation; public: SliceFifoBuffer() noexcept:ForeignFifoBuffer<std::byte>(nullptr) {} explicit SliceFifoBuffer(SlicePool &pool) noexcept :ForeignFifoBuffer<std::byte>(nullptr) { Allocate(pool); } SliceFifoBuffer(SliceFifoBuffer &&src) noexcept :ForeignFifoBuffer(std::move(src)), allocation(std::move(src.allocation)) { src.SetNull(); } void swap(SliceFifoBuffer &other) noexcept { using std::swap; ForeignFifoBuffer<std::byte>::swap(other); swap(allocation, other.allocation); } friend void swap(SliceFifoBuffer &a, SliceFifoBuffer &b) noexcept { a.swap(b); } void Allocate(SlicePool &pool) noexcept; void Free() noexcept; bool IsDefinedAndFull() const noexcept { return IsDefined() && IsFull(); } void AllocateIfNull(SlicePool &pool) noexcept { if (IsNull()) Allocate(pool); } void FreeIfDefined() noexcept { if (IsDefined()) Free(); } void FreeIfEmpty() noexcept { if (empty()) FreeIfDefined(); } /** * If this buffer is empty, free the buffer and reallocate a new * one. This is useful to work around #SliceArea fragmentation. */ void CycleIfEmpty(SlicePool &pool) noexcept { if (IsDefined() && empty()) { Free(); Allocate(pool); } } using ForeignFifoBuffer<std::byte>::MoveFrom; /** * Move as much data as possible from the specified buffer. If * the destination buffer is empty, the buffers are swapped. Care * is taken that neither buffer suddenly becomes nulled * afterwards, because some callers may not be prepared for this. * * Note: this method has been removed because it was not * possible to implement it to be safe against unallocated * instances. Use MoveFromAllow*() instead. */ void MoveFrom(SliceFifoBuffer &src) noexcept = delete; /** * Like MoveFrom(), but allow the destination to be nulled. This * is useful when #src can be freed, but this object cannot. */ void MoveFromAllowNull(SliceFifoBuffer &src) noexcept { if (empty() && (!src.empty() || !IsNull())) /* optimized special case: swap buffer pointers instead of copying data */ swap(src); else ForeignFifoBuffer<std::byte>::MoveFrom(src); } /** * Like MoveFrom(), but allow the source to be nulled. This is * useful when this object can be freed, but #src cannot. */ void MoveFromAllowSrcNull(SliceFifoBuffer &src) noexcept { if (empty() && (!src.empty() || IsNull())) /* optimized special case: swap buffer pointers instead of copying data */ swap(src); else ForeignFifoBuffer<std::byte>::MoveFrom(src); } /** * Like MoveFrom(), but allow both to be nulled. */ void MoveFromAllowBothNull(SliceFifoBuffer &src) noexcept { if (empty()) /* optimized special case: swap buffer pointers instead of copying data */ swap(src); else ForeignFifoBuffer<std::byte>::MoveFrom(src); } /** * Swaps the two buffers if #src is nulled. This is useful when * #src can be freed, but this object cannot. */ void SwapIfNull(SliceFifoBuffer &src) noexcept { if (src.IsNull() && empty() && !IsNull()) swap(src); } }; <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 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 "modules/canbus/vehicle/lincoln/protocol/throttle_63.h" #include "gtest/gtest.h" namespace apollo { namespace canbus { namespace lincoln { TEST(Throttle63Test, General) { uint8_t data = 0x01; int32_t length = 8; ChassisDetail cd; Throttle63 throttle; throttle.Parse(&data, length, &cd); EXPECT_FALSE(cd.gas().throttle_enabled()); } } // namespace lincoln } // namespace apollo } // namespace canbus <commit_msg>fixed data in throttle_63_test. #120<commit_after>/****************************************************************************** * Copyright 2017 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 "modules/canbus/vehicle/lincoln/protocol/throttle_63.h" #include "gtest/gtest.h" namespace apollo { namespace canbus { namespace lincoln { TEST(Throttle63Test, General) { uint8_t data[8] = {0x67, 0x62, 0x63, 0x64, 0x51, 0x52, 0x53, 0x54}; int32_t length = 8; ChassisDetail cd; Throttle63 throttle; throttle.Parse(data, length, &cd); EXPECT_DOUBLE_EQ(cd.gas().throttle_input(), 38.439002059967905); EXPECT_DOUBLE_EQ(cd.gas().throttle_cmd(), 39.21416037232008); EXPECT_DOUBLE_EQ(cd.gas().throttle_output(), 32.155336842908326); EXPECT_EQ(cd.gas().watchdog_source(), 5); EXPECT_FALSE(cd.gas().throttle_enabled()); EXPECT_FALSE(cd.gas().driver_override()); EXPECT_TRUE(cd.gas().driver_activity()); EXPECT_FALSE(cd.gas().watchdog_fault()); EXPECT_TRUE(cd.gas().channel_1_fault()); EXPECT_FALSE(cd.gas().channel_2_fault()); EXPECT_FALSE(cd.gas().connector_fault()); EXPECT_TRUE(cd.check_response().is_vcu_online()); } } // namespace lincoln } // namespace apollo } // namespace canbus <|endoftext|>
<commit_before>/** @file Chunk decoding. @section license License 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 <algorithm> #include <cassert> #include "chunk-decoder.h" void ChunkDecoder::parseSizeCharacter(const char a) { assert(state_ == State::kSize); if (a >= '0' && a <= '9') { size_ = (size_ << 4) | (a - '0'); } else if (a >= 'A' && a <= 'F') { size_ = (size_ << 4) | (a - 'A' + 10); } else if (a >= 'a' && a <= 'f') { size_ = (size_ << 4) | (a - 'a' + 10); } else if (a == '\r') { state_ = size_ == 0 ? State::kEndN : State::kDataN; } else { assert(false); // invalid input } } int ChunkDecoder::parseSize(const char *p, const int64_t s) { assert(p != nullptr); assert(s > 0); int length = 0; while (state_ != State::kData && *p != '\0' && length < s) { assert(state_ < State::kUpperBound); // VALID RANGE switch (state_) { case State::kData: case State::kInvalid: case State::kEnd: case State::kUpperBound: assert(false); break; case State::kDataN: assert(*p == '\n'); state_ = (*p == '\n') ? State::kData : State::kInvalid; break; case State::kEndN: assert(*p == '\n'); state_ = (*p == '\n') ? State::kEnd : State::kInvalid; return length; case State::kSizeR: assert(*p == '\r'); state_ = (*p == '\r') ? State::kSizeN : State::kInvalid; break; case State::kSizeN: assert(*p == '\n'); state_ = (*p == '\n') ? State::kSize : State::kInvalid; break; case State::kSize: parseSizeCharacter(*p); break; } ++length; ++p; assert(state_ != State::kInvalid); } return length; } bool ChunkDecoder::isSizeState() const { return state_ == State::kDataN || state_ == State::kEndN || state_ == State::kSize || state_ == State::kSizeN || state_ == State::kSizeR; } int ChunkDecoder::decode(const TSIOBufferReader &r) { assert(r != nullptr); if (state_ == State::kEnd) { return 0; } { const int l = TSIOBufferReaderAvail(r); if (l < size_) { size_ -= l; return l; } } int64_t size; TSIOBufferBlock block = TSIOBufferReaderStart(r); // Trying to parse a size. if (isSizeState()) { while (block != nullptr && size_ == 0) { const char *p = TSIOBufferBlockReadStart(block, r, &size); assert(p != nullptr); const int i = parseSize(p, size); size -= i; TSIOBufferReaderConsume(r, i); if (state_ == State::kEnd) { assert(size_ == 0); return 0; } if (isSizeState()) { assert(size == 0); block = TSIOBufferBlockNext(block); } } } int length = 0; while (block != nullptr && state_ == State::kData) { assert(size_ > 0); const char *p = TSIOBufferBlockReadStart(block, r, &size); if (p != nullptr) { if (size >= size_) { length += size_; size_ = 0; state_ = State::kSizeR; break; } else { length += size; size_ -= size; } } block = TSIOBufferBlockNext(block); } return length; } <commit_msg>Fix for when multiplexer gets a 0 byte read event<commit_after>/** @file Chunk decoding. @section license License 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 <algorithm> #include <cassert> #include "chunk-decoder.h" void ChunkDecoder::parseSizeCharacter(const char a) { assert(state_ == State::kSize); if (a >= '0' && a <= '9') { size_ = (size_ << 4) | (a - '0'); } else if (a >= 'A' && a <= 'F') { size_ = (size_ << 4) | (a - 'A' + 10); } else if (a >= 'a' && a <= 'f') { size_ = (size_ << 4) | (a - 'a' + 10); } else if (a == '\r') { state_ = size_ == 0 ? State::kEndN : State::kDataN; } else { assert(false); // invalid input } } int ChunkDecoder::parseSize(const char *p, const int64_t s) { assert(p != nullptr); assert(s > 0); int length = 0; while (state_ != State::kData && *p != '\0' && length < s) { assert(state_ < State::kUpperBound); // VALID RANGE switch (state_) { case State::kData: case State::kInvalid: case State::kEnd: case State::kUpperBound: assert(false); break; case State::kDataN: assert(*p == '\n'); state_ = (*p == '\n') ? State::kData : State::kInvalid; break; case State::kEndN: assert(*p == '\n'); state_ = (*p == '\n') ? State::kEnd : State::kInvalid; return length; case State::kSizeR: assert(*p == '\r'); state_ = (*p == '\r') ? State::kSizeN : State::kInvalid; break; case State::kSizeN: assert(*p == '\n'); state_ = (*p == '\n') ? State::kSize : State::kInvalid; break; case State::kSize: parseSizeCharacter(*p); break; } ++length; ++p; assert(state_ != State::kInvalid); } return length; } bool ChunkDecoder::isSizeState() const { return state_ == State::kDataN || state_ == State::kEndN || state_ == State::kSize || state_ == State::kSizeN || state_ == State::kSizeR; } int ChunkDecoder::decode(const TSIOBufferReader &r) { assert(r != nullptr); if (state_ == State::kEnd) { return 0; } { const int l = TSIOBufferReaderAvail(r); if (l == 0) { return 0; } else if (l < size_) { size_ -= l; return l; } } int64_t size; TSIOBufferBlock block = TSIOBufferReaderStart(r); // Trying to parse a size. if (isSizeState()) { while (block != nullptr && size_ == 0) { const char *p = TSIOBufferBlockReadStart(block, r, &size); assert(p != nullptr); const int i = parseSize(p, size); size -= i; TSIOBufferReaderConsume(r, i); if (state_ == State::kEnd) { assert(size_ == 0); return 0; } if (isSizeState()) { assert(size == 0); block = TSIOBufferBlockNext(block); } } } int length = 0; while (block != nullptr && state_ == State::kData) { assert(size_ > 0); const char *p = TSIOBufferBlockReadStart(block, r, &size); if (p != nullptr) { if (size >= size_) { length += size_; size_ = 0; state_ = State::kSizeR; break; } else { length += size; size_ -= size; } } block = TSIOBufferBlockNext(block); } return length; } <|endoftext|>
<commit_before>#include "MeshLodTests.h" #include "OgreDefaultHardwareBufferManager.h" #include "OgreVertexIndexData.h" #include "OgreEdgeListBuilder.h" #include "OgreMesh.h" #include "OgreMeshManager.h" #include "OgreSubMesh.h" #include "OgreMeshSerializer.h" #include "OgreRoot.h" #include "OgreException.h" #include "OgreArchive.h" #include "OgreArchiveManager.h" #include "OgreFileSystem.h" #include "OgreConfigFile.h" #include "OgreMeshLodGenerator.h" #include "OgrePixelCountLodStrategy.h" #include "OgreLodCollapseCostQuadric.h" #include "OgreRenderWindow.h" #include "OgreLodConfigSerializer.h" CPPUNIT_TEST_SUITE_REGISTRATION(MeshLodTests); #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE #include "macUtils.h" #endif void MeshLodTests::setUp() { OGRE_DELETE LogManager::getSingletonPtr(); mLogManager = OGRE_NEW LogManager(); mLogManager->createLog("MeshWithoutIndexDataTests.log", false); mLogManager->setLogDetail(LL_LOW); #if OGRE_STATIC mStaticPluginLoader = OGRE_NEW StaticPluginLoader(); #endif #ifdef OGRE_STATIC_LIB Root* root = OGRE_NEW Root(StringUtil::BLANK); mStaticPluginLoader.load(); #else Root* root = OGRE_NEW Root(); #endif CPPUNIT_ASSERT(!root->getAvailableRenderers().empty()); root->setRenderSystem(root->getAvailableRenderers().back()); root->initialise(false); // Needed for setting up HardwareBufferManager root->createRenderWindow("", 320, 240, false, NULL)->setHidden(true); new MeshLodGenerator; // Load resource paths from config file ConfigFile cf; #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE cf.load(macBundlePath() + "/Contents/Resources/resources.cfg"); #elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 #if OGRE_DEBUG_MODE cf.load("resources_d.cfg"); #else cf.load("resources.cfg"); #endif #else #ifdef OGRE_STATIC_LIB cf.load("bin/resources.cfg"); #else cf.load("resources.cfg"); #endif #endif /* if OGRE_PLATFORM == OGRE_PLATFORM_APPLE */ // Go through all sections & settings in the file ConfigFile::SectionIterator seci = cf.getSectionIterator(); String secName, typeName, archName; while (seci.hasMoreElements()) { secName = seci.peekNextKey(); ConfigFile::SettingsMultiMap* settings = seci.getNext(); ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; archName = i->second; ResourceGroupManager::getSingleton().addResourceLocation( archName, typeName, secName); } } // +++++++++++++++++++++++++++++++ // Create the mesh for testing { mMesh = MeshManager::getSingleton().load("Sinbad.mesh", ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); } // +++++++++++++++++++++++++++++++ } void MeshLodTests::tearDown() { if (!mMesh.isNull()) { mMesh->unload(); mMesh.setNull(); } OGRE_DELETE MeshLodGenerator::getSingletonPtr(); OGRE_DELETE Root::getSingletonPtr(); OGRE_DELETE mLogManager; } void MeshLodTests::addProfile(LodConfig& config) { // Get the first two vertices and put the edge into the profile // It doesn't matter if there is no such edge, because edges are removed and created dynamically. // The vertex positions should exist or you get an assert. VertexData* vertexData = config.mesh->getSubMesh(0)->vertexData; const VertexElement* elemPos = vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); HardwareVertexBufferSharedPtr vbuf = vertexData->vertexBufferBinding->getBuffer(elemPos->getSource()); assert(vbuf->getNumVertices() > 2); unsigned char* vertex = static_cast<unsigned char*>(vbuf->lock(HardwareBuffer::HBL_READ_ONLY)); float* pFloat; elemPos->baseVertexPointerToElement(vertex, &pFloat); ProfiledEdge edge; edge.src.x = *pFloat++; edge.src.y = *pFloat++; edge.src.z = *pFloat; vertex += vbuf->getVertexSize(); elemPos->baseVertexPointerToElement(vertex, &pFloat); edge.dst.x = *pFloat++; edge.dst.y = *pFloat++; edge.dst.z = *pFloat; edge.cost = LodData::NEVER_COLLAPSE_COST; config.advanced.profile.push_back(edge); vbuf->unlock(); } void MeshLodTests::testMeshLodGenerator() { LodConfig config; setTestLodConfig(config); MeshLodGenerator& gen = MeshLodGenerator::getSingleton(); gen.generateLodLevels(config); addProfile(config); config.advanced.useBackgroundQueue = false; config.advanced.useCompression = false; config.advanced.useVertexNormals = false; gen.generateLodLevels(config); LodConfig config2(config); config2.advanced.useBackgroundQueue = true; config2.mesh->removeLodLevels(); gen.generateLodLevels(config); blockedWaitForLodGeneration(config.mesh); CPPUNIT_ASSERT(config.levels.size() == config2.levels.size()); for (size_t i = 0; i < config.levels.size(); i++) { CPPUNIT_ASSERT(config.levels[i].outSkipped == config2.levels[i].outSkipped); CPPUNIT_ASSERT(config.levels[i].outUniqueVertexCount == config2.levels[i].outUniqueVertexCount); } } void MeshLodTests::blockedWaitForLodGeneration(const MeshPtr& mesh) { bool success = false; const int timeout = 5000; WorkQueue* wq = Root::getSingleton().getWorkQueue(); for (int i = 0; i < timeout; i++) { OGRE_THREAD_SLEEP(1); wq->processResponses(); // Injects the Lod if ready if (mesh->getNumLodLevels() != 1) { success = true; break; } } // timeout CPPUNIT_ASSERT(success); } void MeshLodTests::testLodConfigSerializer() { LodConfig config, config2; setTestLodConfig(config); addProfile(config); LodConfigSerializer serializer; serializer.exportLodConfig(config, "testLodConfigSerializer.lodconfig"); serializer.importLodConfig(&config2, "testLodConfigSerializer.lodconfig"); CPPUNIT_ASSERT(config.mesh->getHandle() == config2.mesh->getHandle()); CPPUNIT_ASSERT(config.strategy == config2.strategy); CPPUNIT_ASSERT(config.advanced.outsideWalkAngle == config.advanced.outsideWalkAngle); CPPUNIT_ASSERT(config.advanced.outsideWeight == config.advanced.outsideWeight); CPPUNIT_ASSERT(config.advanced.useBackgroundQueue == config.advanced.useBackgroundQueue); CPPUNIT_ASSERT(config.advanced.useCompression == config.advanced.useCompression); CPPUNIT_ASSERT(config.advanced.useVertexNormals == config.advanced.useVertexNormals); { // Compare profiles LodProfile& p1 = config.advanced.profile; LodProfile& p2 = config2.advanced.profile; bool isProfileSameSize = (p1.size() == p2.size()); CPPUNIT_ASSERT(isProfileSameSize); if (isProfileSameSize) { for (size_t i = 0; i < p1.size(); i++) { CPPUNIT_ASSERT(p1[i].src == p2[i].src); CPPUNIT_ASSERT(p1[i].dst == p2[i].dst); CPPUNIT_ASSERT(isEqual(p1[i].cost, p2[i].cost)); } } } { // Compare Lod Levels LodConfig::LodLevelList& l1 = config.levels; LodConfig::LodLevelList& l2 = config2.levels; bool isLevelsSameSize = (l1.size() == l2.size()); CPPUNIT_ASSERT(isLevelsSameSize); if (isLevelsSameSize) { for (size_t i = 0; i < l1.size(); i++) { CPPUNIT_ASSERT(l1[i].distance == l2[i].distance); CPPUNIT_ASSERT(l1[i].manualMeshName == l2[i].manualMeshName); CPPUNIT_ASSERT(l1[i].reductionMethod == l2[i].reductionMethod); CPPUNIT_ASSERT(isEqual(l1[i].reductionValue, l2[i].reductionValue)); } } } } void MeshLodTests::testManualLodLevels() { MeshLodGenerator& gen = MeshLodGenerator::getSingleton(); LodConfig config; setTestLodConfig(config); gen.generateLodLevels(config, LodCollapseCostPtr(new LodCollapseCostQuadric())); } void MeshLodTests::testQuadricError() { LodConfig config; setTestLodConfig(config); MeshLodGenerator& gen = MeshLodGenerator::getSingleton(); gen.generateLodLevels(config, LodCollapseCostPtr(new LodCollapseCostQuadric())); } void MeshLodTests::setTestLodConfig(LodConfig& config) { config.mesh = mMesh; config.strategy = PixelCountLodStrategy::getSingletonPtr(); config.levels.clear(); config.createGeneratedLodLevel(10, 0.1); config.createGeneratedLodLevel(9, 0.2); config.createGeneratedLodLevel(8, 0.3); config.advanced.outsideWeight = 1.0; config.advanced.useCompression = true; config.advanced.useVertexNormals = true; config.advanced.useBackgroundQueue = false; } bool MeshLodTests::isEqual(Real a, Real b) { Real absoluteError = std::abs(a * 0.05); return ((a - absoluteError) <= b) && ((a + absoluteError) >= b); } <commit_msg>Use cocoa API by default.<commit_after>#include "MeshLodTests.h" #include "OgreDefaultHardwareBufferManager.h" #include "OgreVertexIndexData.h" #include "OgreEdgeListBuilder.h" #include "OgreMesh.h" #include "OgreMeshManager.h" #include "OgreSubMesh.h" #include "OgreMeshSerializer.h" #include "OgreRoot.h" #include "OgreException.h" #include "OgreArchive.h" #include "OgreArchiveManager.h" #include "OgreFileSystem.h" #include "OgreConfigFile.h" #include "OgreMeshLodGenerator.h" #include "OgrePixelCountLodStrategy.h" #include "OgreLodCollapseCostQuadric.h" #include "OgreRenderWindow.h" #include "OgreLodConfigSerializer.h" CPPUNIT_TEST_SUITE_REGISTRATION(MeshLodTests); #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE #include "macUtils.h" #endif void MeshLodTests::setUp() { OGRE_DELETE LogManager::getSingletonPtr(); mLogManager = OGRE_NEW LogManager(); mLogManager->createLog("MeshWithoutIndexDataTests.log", false); mLogManager->setLogDetail(LL_LOW); #if OGRE_STATIC mStaticPluginLoader = OGRE_NEW StaticPluginLoader(); #endif #ifdef OGRE_STATIC_LIB Root* root = OGRE_NEW Root(StringUtil::BLANK); mStaticPluginLoader.load(); #else Root* root = OGRE_NEW Root(); #endif CPPUNIT_ASSERT(!root->getAvailableRenderers().empty()); root->setRenderSystem(root->getAvailableRenderers().back()); root->initialise(false); // Needed for setting up HardwareBufferManager #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE Ogre::NameValuePairList misc; // Tell OGRE that we're using cocoa, so it doesn't need to make a window for us misc["macAPI"] = "cocoa"; root->createRenderWindow("", 320, 240, false, &misc)->setHidden(true); #else root->createRenderWindow("", 320, 240, false, NULL)->setHidden(true); #endif new MeshLodGenerator; // Load resource paths from config file ConfigFile cf; #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE cf.load(macBundlePath() + "/Contents/Resources/resources.cfg"); #elif OGRE_PLATFORM == OGRE_PLATFORM_WIN32 #if OGRE_DEBUG_MODE cf.load("resources_d.cfg"); #else cf.load("resources.cfg"); #endif #else #ifdef OGRE_STATIC_LIB cf.load("bin/resources.cfg"); #else cf.load("resources.cfg"); #endif #endif /* if OGRE_PLATFORM == OGRE_PLATFORM_APPLE */ // Go through all sections & settings in the file ConfigFile::SectionIterator seci = cf.getSectionIterator(); String secName, typeName, archName; while (seci.hasMoreElements()) { secName = seci.peekNextKey(); ConfigFile::SettingsMultiMap* settings = seci.getNext(); ConfigFile::SettingsMultiMap::iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; archName = i->second; ResourceGroupManager::getSingleton().addResourceLocation( archName, typeName, secName); } } // +++++++++++++++++++++++++++++++ // Create the mesh for testing { mMesh = MeshManager::getSingleton().load("Sinbad.mesh", ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME); } // +++++++++++++++++++++++++++++++ } void MeshLodTests::tearDown() { if (!mMesh.isNull()) { mMesh->unload(); mMesh.setNull(); } OGRE_DELETE MeshLodGenerator::getSingletonPtr(); OGRE_DELETE Root::getSingletonPtr(); OGRE_DELETE mLogManager; } void MeshLodTests::addProfile(LodConfig& config) { // Get the first two vertices and put the edge into the profile // It doesn't matter if there is no such edge, because edges are removed and created dynamically. // The vertex positions should exist or you get an assert. VertexData* vertexData = config.mesh->getSubMesh(0)->vertexData; const VertexElement* elemPos = vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); HardwareVertexBufferSharedPtr vbuf = vertexData->vertexBufferBinding->getBuffer(elemPos->getSource()); assert(vbuf->getNumVertices() > 2); unsigned char* vertex = static_cast<unsigned char*>(vbuf->lock(HardwareBuffer::HBL_READ_ONLY)); float* pFloat; elemPos->baseVertexPointerToElement(vertex, &pFloat); ProfiledEdge edge; edge.src.x = *pFloat++; edge.src.y = *pFloat++; edge.src.z = *pFloat; vertex += vbuf->getVertexSize(); elemPos->baseVertexPointerToElement(vertex, &pFloat); edge.dst.x = *pFloat++; edge.dst.y = *pFloat++; edge.dst.z = *pFloat; edge.cost = LodData::NEVER_COLLAPSE_COST; config.advanced.profile.push_back(edge); vbuf->unlock(); } void MeshLodTests::testMeshLodGenerator() { LodConfig config; setTestLodConfig(config); MeshLodGenerator& gen = MeshLodGenerator::getSingleton(); gen.generateLodLevels(config); addProfile(config); config.advanced.useBackgroundQueue = false; config.advanced.useCompression = false; config.advanced.useVertexNormals = false; gen.generateLodLevels(config); LodConfig config2(config); config2.advanced.useBackgroundQueue = true; config2.mesh->removeLodLevels(); gen.generateLodLevels(config); blockedWaitForLodGeneration(config.mesh); CPPUNIT_ASSERT(config.levels.size() == config2.levels.size()); for (size_t i = 0; i < config.levels.size(); i++) { CPPUNIT_ASSERT(config.levels[i].outSkipped == config2.levels[i].outSkipped); CPPUNIT_ASSERT(config.levels[i].outUniqueVertexCount == config2.levels[i].outUniqueVertexCount); } } void MeshLodTests::blockedWaitForLodGeneration(const MeshPtr& mesh) { bool success = false; const int timeout = 5000; WorkQueue* wq = Root::getSingleton().getWorkQueue(); for (int i = 0; i < timeout; i++) { OGRE_THREAD_SLEEP(1); wq->processResponses(); // Injects the Lod if ready if (mesh->getNumLodLevels() != 1) { success = true; break; } } // timeout CPPUNIT_ASSERT(success); } void MeshLodTests::testLodConfigSerializer() { LodConfig config, config2; setTestLodConfig(config); addProfile(config); LodConfigSerializer serializer; serializer.exportLodConfig(config, "testLodConfigSerializer.lodconfig"); serializer.importLodConfig(&config2, "testLodConfigSerializer.lodconfig"); CPPUNIT_ASSERT(config.mesh->getHandle() == config2.mesh->getHandle()); CPPUNIT_ASSERT(config.strategy == config2.strategy); CPPUNIT_ASSERT(config.advanced.outsideWalkAngle == config.advanced.outsideWalkAngle); CPPUNIT_ASSERT(config.advanced.outsideWeight == config.advanced.outsideWeight); CPPUNIT_ASSERT(config.advanced.useBackgroundQueue == config.advanced.useBackgroundQueue); CPPUNIT_ASSERT(config.advanced.useCompression == config.advanced.useCompression); CPPUNIT_ASSERT(config.advanced.useVertexNormals == config.advanced.useVertexNormals); { // Compare profiles LodProfile& p1 = config.advanced.profile; LodProfile& p2 = config2.advanced.profile; bool isProfileSameSize = (p1.size() == p2.size()); CPPUNIT_ASSERT(isProfileSameSize); if (isProfileSameSize) { for (size_t i = 0; i < p1.size(); i++) { CPPUNIT_ASSERT(p1[i].src == p2[i].src); CPPUNIT_ASSERT(p1[i].dst == p2[i].dst); CPPUNIT_ASSERT(isEqual(p1[i].cost, p2[i].cost)); } } } { // Compare Lod Levels LodConfig::LodLevelList& l1 = config.levels; LodConfig::LodLevelList& l2 = config2.levels; bool isLevelsSameSize = (l1.size() == l2.size()); CPPUNIT_ASSERT(isLevelsSameSize); if (isLevelsSameSize) { for (size_t i = 0; i < l1.size(); i++) { CPPUNIT_ASSERT(l1[i].distance == l2[i].distance); CPPUNIT_ASSERT(l1[i].manualMeshName == l2[i].manualMeshName); CPPUNIT_ASSERT(l1[i].reductionMethod == l2[i].reductionMethod); CPPUNIT_ASSERT(isEqual(l1[i].reductionValue, l2[i].reductionValue)); } } } } void MeshLodTests::testManualLodLevels() { MeshLodGenerator& gen = MeshLodGenerator::getSingleton(); LodConfig config; setTestLodConfig(config); gen.generateLodLevels(config, LodCollapseCostPtr(new LodCollapseCostQuadric())); } void MeshLodTests::testQuadricError() { LodConfig config; setTestLodConfig(config); MeshLodGenerator& gen = MeshLodGenerator::getSingleton(); gen.generateLodLevels(config, LodCollapseCostPtr(new LodCollapseCostQuadric())); } void MeshLodTests::setTestLodConfig(LodConfig& config) { config.mesh = mMesh; config.strategy = PixelCountLodStrategy::getSingletonPtr(); config.levels.clear(); config.createGeneratedLodLevel(10, 0.1); config.createGeneratedLodLevel(9, 0.2); config.createGeneratedLodLevel(8, 0.3); config.advanced.outsideWeight = 1.0; config.advanced.useCompression = true; config.advanced.useVertexNormals = true; config.advanced.useBackgroundQueue = false; } bool MeshLodTests::isEqual(Real a, Real b) { Real absoluteError = std::abs(a * 0.05); return ((a - absoluteError) <= b) && ((a + absoluteError) >= b); } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreGLES2DefaultHardwareBufferManager.h" #include "OgreRoot.h" #include "OgreGLES2RenderSystem.h" #include "OgreGLES2Util.h" namespace Ogre { GLES2DefaultHardwareVertexBuffer::GLES2DefaultHardwareVertexBuffer(size_t vertexSize, size_t numVertices, HardwareBuffer::Usage usage) : HardwareVertexBuffer(0, vertexSize, numVertices, usage, true, false) { mData = static_cast<unsigned char*>(OGRE_MALLOC_SIMD(mSizeInBytes, MEMCATEGORY_GEOMETRY)); } GLES2DefaultHardwareVertexBuffer::GLES2DefaultHardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize, size_t numVertices, HardwareBuffer::Usage usage) : HardwareVertexBuffer(mgr, vertexSize, numVertices, usage, true, false) { mData = static_cast<unsigned char*>(OGRE_MALLOC_SIMD(mSizeInBytes, MEMCATEGORY_GEOMETRY)); } GLES2DefaultHardwareVertexBuffer::~GLES2DefaultHardwareVertexBuffer() { OGRE_FREE_SIMD(mData, MEMCATEGORY_GEOMETRY); } void* GLES2DefaultHardwareVertexBuffer::lockImpl(size_t offset, size_t length, LockOptions options) { return mData + offset; } void GLES2DefaultHardwareVertexBuffer::unlockImpl(void) { // Nothing to do } void* GLES2DefaultHardwareVertexBuffer::lock(size_t offset, size_t length, LockOptions options, UploadOptions uploadOpt) { mIsLocked = true; return mData + offset; } void GLES2DefaultHardwareVertexBuffer::unlock(void) { mIsLocked = false; // Nothing to do } void GLES2DefaultHardwareVertexBuffer::readData(size_t offset, size_t length, void* pDest) { assert((offset + length) <= mSizeInBytes); memcpy(pDest, mData + offset, length); } void GLES2DefaultHardwareVertexBuffer::writeData(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer) { assert((offset + length) <= mSizeInBytes); // ignore discard, memory is not guaranteed to be zeroised memcpy(mData + offset, pSource, length); } GLES2DefaultHardwareIndexBuffer::GLES2DefaultHardwareIndexBuffer(IndexType idxType, size_t numIndexes, HardwareBuffer::Usage usage) : HardwareIndexBuffer(0, idxType, numIndexes, usage, true, false) // always software, never shadowed { #if OGRE_NO_GLES3_SUPPORT == 1 if (!Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_32BIT_INDEX) && idxType == HardwareIndexBuffer::IT_32BIT) { OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "32 bit hardware buffers are not allowed in OpenGL ES.", "GLES2DefaultHardwareIndexBuffer"); } #endif mData = new unsigned char[mSizeInBytes]; } GLES2DefaultHardwareIndexBuffer::~GLES2DefaultHardwareIndexBuffer() { delete [] mData; } void* GLES2DefaultHardwareIndexBuffer::lockImpl(size_t offset, size_t length, LockOptions options) { // Only for use internally, no 'locking' as such return mData + offset; } void GLES2DefaultHardwareIndexBuffer::unlockImpl(void) { // Nothing to do } void* GLES2DefaultHardwareIndexBuffer::lock(size_t offset, size_t length, LockOptions options, UploadOptions uploadOpt) { mIsLocked = true; return mData + offset; } void GLES2DefaultHardwareIndexBuffer::unlock(void) { mIsLocked = false; // Nothing to do } void GLES2DefaultHardwareIndexBuffer::readData(size_t offset, size_t length, void* pDest) { assert((offset + length) <= mSizeInBytes); memcpy(pDest, mData + offset, length); } void GLES2DefaultHardwareIndexBuffer::writeData(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer) { assert((offset + length) <= mSizeInBytes); // ignore discard, memory is not guaranteed to be zeroised memcpy(mData + offset, pSource, length); } GLES2DefaultHardwareUniformBuffer::GLES2DefaultHardwareUniformBuffer(size_t bufferSize, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name) : HardwareUniformBuffer(0, bufferSize, usage, useShadowBuffer, name) { mData = static_cast<unsigned char*>(OGRE_MALLOC_SIMD(mSizeInBytes, MEMCATEGORY_GEOMETRY)); } GLES2DefaultHardwareUniformBuffer::GLES2DefaultHardwareUniformBuffer(HardwareBufferManagerBase* mgr, size_t bufferSize, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name) : HardwareUniformBuffer(mgr, bufferSize, usage, useShadowBuffer, name) { mData = static_cast<unsigned char*>(OGRE_MALLOC_SIMD(mSizeInBytes, MEMCATEGORY_GEOMETRY)); } GLES2DefaultHardwareUniformBuffer::~GLES2DefaultHardwareUniformBuffer() { OGRE_FREE_SIMD(mData, MEMCATEGORY_GEOMETRY); } void* GLES2DefaultHardwareUniformBuffer::lockImpl(size_t offset, size_t length, LockOptions options) { return mData + offset; } void GLES2DefaultHardwareUniformBuffer::unlockImpl(void) { // Nothing to do } void* GLES2DefaultHardwareUniformBuffer::lock(size_t offset, size_t length, LockOptions options, UploadOptions uploadOpt) { mIsLocked = true; return mData + offset; } void GLES2DefaultHardwareUniformBuffer::unlock(void) { mIsLocked = false; // Nothing to do } void GLES2DefaultHardwareUniformBuffer::readData(size_t offset, size_t length, void* pDest) { assert((offset + length) <= mSizeInBytes); memcpy(pDest, mData + offset, length); } void GLES2DefaultHardwareUniformBuffer::writeData(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer) { assert((offset + length) <= mSizeInBytes); // ignore discard, memory is not guaranteed to be zeroised memcpy(mData + offset, pSource, length); } GLES2DefaultHardwareBufferManagerBase::GLES2DefaultHardwareBufferManagerBase() { } GLES2DefaultHardwareBufferManagerBase::~GLES2DefaultHardwareBufferManagerBase() { destroyAllDeclarations(); destroyAllBindings(); } HardwareVertexBufferSharedPtr GLES2DefaultHardwareBufferManagerBase::createVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer) { return HardwareVertexBufferSharedPtr( OGRE_NEW GLES2DefaultHardwareVertexBuffer(vertexSize, numVerts, usage)); } HardwareIndexBufferSharedPtr GLES2DefaultHardwareBufferManagerBase::createIndexBuffer(HardwareIndexBuffer::IndexType itype, size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer) { return HardwareIndexBufferSharedPtr( OGRE_NEW GLES2DefaultHardwareIndexBuffer(itype, numIndexes, usage)); } HardwareUniformBufferSharedPtr GLES2DefaultHardwareBufferManagerBase::createUniformBuffer(size_t sizeBytes, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name) { if(!gleswIsSupported(3, 0)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "GLES2 does not support uniform buffer objects", "GLES2DefaultHardwareBufferManager::createUniformBuffer"); } return HardwareUniformBufferSharedPtr(new GLES2DefaultHardwareUniformBuffer(this, sizeBytes, usage, useShadowBuffer, name)); } Ogre::RenderToVertexBufferSharedPtr GLES2DefaultHardwareBufferManagerBase::createRenderToVertexBuffer( void ) { if(!gleswIsSupported(3, 0)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Cannot create RenderToVertexBuffer in GLES2DefaultHardwareBufferManagerBase", "GLES2DefaultHardwareBufferManagerBase::createRenderToVertexBuffer"); } // return HardwareUniformBufferSharedPtr(new GLES2DefaultHardwareRenderToVertexBuffer(this, sizeBytes, usage, useShadowBuffer, name)); } } <commit_msg>[iOS] fixed "control may reach end of non-void function" compiler warning / logic error<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreGLES2DefaultHardwareBufferManager.h" #include "OgreRoot.h" #include "OgreGLES2RenderSystem.h" #include "OgreGLES2Util.h" namespace Ogre { GLES2DefaultHardwareVertexBuffer::GLES2DefaultHardwareVertexBuffer(size_t vertexSize, size_t numVertices, HardwareBuffer::Usage usage) : HardwareVertexBuffer(0, vertexSize, numVertices, usage, true, false) { mData = static_cast<unsigned char*>(OGRE_MALLOC_SIMD(mSizeInBytes, MEMCATEGORY_GEOMETRY)); } GLES2DefaultHardwareVertexBuffer::GLES2DefaultHardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize, size_t numVertices, HardwareBuffer::Usage usage) : HardwareVertexBuffer(mgr, vertexSize, numVertices, usage, true, false) { mData = static_cast<unsigned char*>(OGRE_MALLOC_SIMD(mSizeInBytes, MEMCATEGORY_GEOMETRY)); } GLES2DefaultHardwareVertexBuffer::~GLES2DefaultHardwareVertexBuffer() { OGRE_FREE_SIMD(mData, MEMCATEGORY_GEOMETRY); } void* GLES2DefaultHardwareVertexBuffer::lockImpl(size_t offset, size_t length, LockOptions options) { return mData + offset; } void GLES2DefaultHardwareVertexBuffer::unlockImpl(void) { // Nothing to do } void* GLES2DefaultHardwareVertexBuffer::lock(size_t offset, size_t length, LockOptions options, UploadOptions uploadOpt) { mIsLocked = true; return mData + offset; } void GLES2DefaultHardwareVertexBuffer::unlock(void) { mIsLocked = false; // Nothing to do } void GLES2DefaultHardwareVertexBuffer::readData(size_t offset, size_t length, void* pDest) { assert((offset + length) <= mSizeInBytes); memcpy(pDest, mData + offset, length); } void GLES2DefaultHardwareVertexBuffer::writeData(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer) { assert((offset + length) <= mSizeInBytes); // ignore discard, memory is not guaranteed to be zeroised memcpy(mData + offset, pSource, length); } GLES2DefaultHardwareIndexBuffer::GLES2DefaultHardwareIndexBuffer(IndexType idxType, size_t numIndexes, HardwareBuffer::Usage usage) : HardwareIndexBuffer(0, idxType, numIndexes, usage, true, false) // always software, never shadowed { #if OGRE_NO_GLES3_SUPPORT == 1 if (!Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_32BIT_INDEX) && idxType == HardwareIndexBuffer::IT_32BIT) { OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "32 bit hardware buffers are not allowed in OpenGL ES.", "GLES2DefaultHardwareIndexBuffer"); } #endif mData = new unsigned char[mSizeInBytes]; } GLES2DefaultHardwareIndexBuffer::~GLES2DefaultHardwareIndexBuffer() { delete [] mData; } void* GLES2DefaultHardwareIndexBuffer::lockImpl(size_t offset, size_t length, LockOptions options) { // Only for use internally, no 'locking' as such return mData + offset; } void GLES2DefaultHardwareIndexBuffer::unlockImpl(void) { // Nothing to do } void* GLES2DefaultHardwareIndexBuffer::lock(size_t offset, size_t length, LockOptions options, UploadOptions uploadOpt) { mIsLocked = true; return mData + offset; } void GLES2DefaultHardwareIndexBuffer::unlock(void) { mIsLocked = false; // Nothing to do } void GLES2DefaultHardwareIndexBuffer::readData(size_t offset, size_t length, void* pDest) { assert((offset + length) <= mSizeInBytes); memcpy(pDest, mData + offset, length); } void GLES2DefaultHardwareIndexBuffer::writeData(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer) { assert((offset + length) <= mSizeInBytes); // ignore discard, memory is not guaranteed to be zeroised memcpy(mData + offset, pSource, length); } GLES2DefaultHardwareUniformBuffer::GLES2DefaultHardwareUniformBuffer(size_t bufferSize, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name) : HardwareUniformBuffer(0, bufferSize, usage, useShadowBuffer, name) { mData = static_cast<unsigned char*>(OGRE_MALLOC_SIMD(mSizeInBytes, MEMCATEGORY_GEOMETRY)); } GLES2DefaultHardwareUniformBuffer::GLES2DefaultHardwareUniformBuffer(HardwareBufferManagerBase* mgr, size_t bufferSize, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name) : HardwareUniformBuffer(mgr, bufferSize, usage, useShadowBuffer, name) { mData = static_cast<unsigned char*>(OGRE_MALLOC_SIMD(mSizeInBytes, MEMCATEGORY_GEOMETRY)); } GLES2DefaultHardwareUniformBuffer::~GLES2DefaultHardwareUniformBuffer() { OGRE_FREE_SIMD(mData, MEMCATEGORY_GEOMETRY); } void* GLES2DefaultHardwareUniformBuffer::lockImpl(size_t offset, size_t length, LockOptions options) { return mData + offset; } void GLES2DefaultHardwareUniformBuffer::unlockImpl(void) { // Nothing to do } void* GLES2DefaultHardwareUniformBuffer::lock(size_t offset, size_t length, LockOptions options, UploadOptions uploadOpt) { mIsLocked = true; return mData + offset; } void GLES2DefaultHardwareUniformBuffer::unlock(void) { mIsLocked = false; // Nothing to do } void GLES2DefaultHardwareUniformBuffer::readData(size_t offset, size_t length, void* pDest) { assert((offset + length) <= mSizeInBytes); memcpy(pDest, mData + offset, length); } void GLES2DefaultHardwareUniformBuffer::writeData(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer) { assert((offset + length) <= mSizeInBytes); // ignore discard, memory is not guaranteed to be zeroised memcpy(mData + offset, pSource, length); } GLES2DefaultHardwareBufferManagerBase::GLES2DefaultHardwareBufferManagerBase() { } GLES2DefaultHardwareBufferManagerBase::~GLES2DefaultHardwareBufferManagerBase() { destroyAllDeclarations(); destroyAllBindings(); } HardwareVertexBufferSharedPtr GLES2DefaultHardwareBufferManagerBase::createVertexBuffer(size_t vertexSize, size_t numVerts, HardwareBuffer::Usage usage, bool useShadowBuffer) { return HardwareVertexBufferSharedPtr( OGRE_NEW GLES2DefaultHardwareVertexBuffer(vertexSize, numVerts, usage)); } HardwareIndexBufferSharedPtr GLES2DefaultHardwareBufferManagerBase::createIndexBuffer(HardwareIndexBuffer::IndexType itype, size_t numIndexes, HardwareBuffer::Usage usage, bool useShadowBuffer) { return HardwareIndexBufferSharedPtr( OGRE_NEW GLES2DefaultHardwareIndexBuffer(itype, numIndexes, usage)); } HardwareUniformBufferSharedPtr GLES2DefaultHardwareBufferManagerBase::createUniformBuffer(size_t sizeBytes, HardwareBuffer::Usage usage, bool useShadowBuffer, const String& name) { if(!gleswIsSupported(3, 0)) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "GLES2 does not support uniform buffer objects", "GLES2DefaultHardwareBufferManager::createUniformBuffer"); } return HardwareUniformBufferSharedPtr(new GLES2DefaultHardwareUniformBuffer(this, sizeBytes, usage, useShadowBuffer, name)); } Ogre::RenderToVertexBufferSharedPtr GLES2DefaultHardwareBufferManagerBase::createRenderToVertexBuffer( void ) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Cannot create RenderToVertexBuffer in GLES2DefaultHardwareBufferManagerBase", "GLES2DefaultHardwareBufferManagerBase::createRenderToVertexBuffer"); } } <|endoftext|>
<commit_before>/** \file generate_vufind_translation_files.cc * \brief A tool for creating the ".ini" files VuFind uses based on data in the SQL translations table. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2016,2017, Library of the University of Tübingen 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/>. */ #include <algorithm> #include <iostream> #include <map> #include <tuple> #include <utility> #include <vector> #include <cstring> #include "File.h" #include "FileUtil.h" #include "TranslationUtil.h" #include "DbConnection.h" #include "DbResultSet.h" #include "DbRow.h" #include "IniFile.h" #include "StringUtil.h" #include "util.h" void Usage() { std::cerr << "Usage: " << ::progname << " [--verbose] output_directory_path\n"; std::exit(EXIT_FAILURE); } // Generates a XX.ini output file with entries like the original file. The XX is a 2-letter language code. void ProcessLanguage(const bool verbose, const std::string &output_file_path, const std::string &_3letter_code, DbConnection * const db_connection) { if (verbose) std::cerr << "Processing language code: " << _3letter_code << '\n'; std::unordered_map<std::string, std::pair<unsigned, std::string>> token_to_line_no_and_other_map; if (::access(output_file_path.c_str(), R_OK) != 0) logger->warning("\"" + output_file_path + "\" is not readable, maybe it doesn't exist?"); else { TranslationUtil::ReadIniFile(output_file_path, &token_to_line_no_and_other_map); if (unlikely(not FileUtil::RenameFile(output_file_path, output_file_path + ".bak", /* remove_target = */true))) logger->error("failed to rename \"" + output_file_path + "\" to \"" + output_file_path + ".bak\"! (" + std::string(::strerror(errno)) + ")"); } File output(output_file_path, "w"); if (unlikely(output.fail())) logger->error("failed to open \"" + output_file_path + "\" for writing!"); db_connection->queryOrDie("SELECT token,translation FROM vufind_translations WHERE language_code='" + _3letter_code + "'"); DbResultSet result_set(db_connection->getLastResultSet()); if (unlikely(result_set.empty())) logger->error("found no translations for language code \"" + _3letter_code + "\"!"); if (verbose) std::cerr << "\tFound " << result_set.size() << " (token,translation) pairs.\n"; std::vector<std::tuple<unsigned, std::string, std::string>> line_nos_tokens_and_translations; while (const DbRow row = result_set.getNextRow()) { const auto &token_to_line_no_and_other(token_to_line_no_and_other_map.find(row[0])); if (token_to_line_no_and_other != token_to_line_no_and_other_map.cend()) line_nos_tokens_and_translations.emplace_back(token_to_line_no_and_other->second.first, row[0], row[1]); else line_nos_tokens_and_translations.emplace_back(token_to_line_no_and_other_map.size() + 1, row[0], row[1]); } std::sort(line_nos_tokens_and_translations.begin(), line_nos_tokens_and_translations.end(), [](const std::tuple<unsigned, std::string,std::string> &left, const std::tuple<unsigned, std::string,std::string> &right) { return std::get<0>(left) < std::get<0>(right); }); for (const auto &line_no_token_and_translation : line_nos_tokens_and_translations) { const std::string token(std::get<1>(line_no_token_and_translation)); const std::string translation(std::get<2>(line_no_token_and_translation)); if (not translation.empty()) output << token << " = \"" << StringUtil::TrimWhite(translation) << "\"\n"; } if (verbose) std::cerr << "Wrote " << line_nos_tokens_and_translations.size() << " language mappings to \"" << output_file_path << "\"\n"; } void GetLanguageCodes(const bool verbose, DbConnection * const db_connection, std::map<std::string, std::string> * language_codes) { db_connection->queryOrDie("SELECT DISTINCT language_code FROM vufind_translations"); DbResultSet language_codes_result_set(db_connection->getLastResultSet()); if (unlikely(language_codes_result_set.empty())) logger->error("no language codes found, expected multiple!"); while (const DbRow row = language_codes_result_set.getNextRow()) { const std::string german_language_code( TranslationUtil::MapFake3LetterEnglishLanguagesCodesToGermanLanguageCodes(row[0])); if (german_language_code == "???") continue; const std::string international_language_code( TranslationUtil::MapGerman3Or4LetterCodeToInternational2LetterCode(german_language_code)); language_codes->emplace(international_language_code, row[0]); } if (verbose) std::cerr << "Found " << language_codes->size() << " distinct language code in the \"vufind_translations\" table.\n"; } const std::string CONF_FILE_PATH("/usr/local/var/lib/tuelib/translations.conf"); int main(int argc, char **argv) { ::progname = argv[0]; if (argc < 2) Usage(); bool verbose(false); if (std::strcmp(argv[1], "--verbose") == 0) { verbose = true; --argc, ++argv; } if (argc != 2) Usage(); const std::string output_directory(argv[1]); if (unlikely(not FileUtil::IsDirectory(output_directory))) logger->error("\"" + output_directory + "\" is not a directory or can't be read!"); try { const IniFile ini_file(CONF_FILE_PATH); const std::string sql_database(ini_file.getString("Database", "sql_database")); const std::string sql_username(ini_file.getString("Database", "sql_username")); const std::string sql_password(ini_file.getString("Database", "sql_password")); DbConnection db_connection(sql_database, sql_username, sql_password); std::map<std::string, std::string> _2letter_and_3letter_codes; GetLanguageCodes(verbose, &db_connection, &_2letter_and_3letter_codes); for (const auto &_2letter_intl_code_and_fake_3letter_english_code : _2letter_and_3letter_codes) ProcessLanguage(verbose, output_directory + "/" + _2letter_intl_code_and_fake_3letter_english_code.first + ".ini", _2letter_intl_code_and_fake_3letter_english_code.second, &db_connection); } catch (const std::exception &x) { logger->error("caught exception: " + std::string(x.what())); } } <commit_msg>Normalize brackets<commit_after>/** \file generate_vufind_translation_files.cc * \brief A tool for creating the ".ini" files VuFind uses based on data in the SQL translations table. * \author Dr. Johannes Ruscheinski */ /* Copyright (C) 2016,2017, Library of the University of Tübingen 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/>. */ #include <algorithm> #include <iostream> #include <map> #include <tuple> #include <utility> #include <vector> #include <cstring> #include "File.h" #include "FileUtil.h" #include "TranslationUtil.h" #include "DbConnection.h" #include "DbResultSet.h" #include "DbRow.h" #include "IniFile.h" #include "StringUtil.h" #include "util.h" void Usage() { std::cerr << "Usage: " << ::progname << " [--verbose] output_directory_path\n"; std::exit(EXIT_FAILURE); } // Needed since no consistent convention was used for brackets std::string NormalizeBrackets(const std::string string_to_normalize) { return StringUtil::Map(string_to_normalize, "<>", "()"); } // Generates a XX.ini output file with entries like the original file. The XX is a 2-letter language code. void ProcessLanguage(const bool verbose, const std::string &output_file_path, const std::string &_3letter_code, DbConnection * const db_connection) { if (verbose) std::cerr << "Processing language code: " << _3letter_code << '\n'; std::unordered_map<std::string, std::pair<unsigned, std::string>> token_to_line_no_and_other_map; if (::access(output_file_path.c_str(), R_OK) != 0) logger->warning("\"" + output_file_path + "\" is not readable, maybe it doesn't exist?"); else { TranslationUtil::ReadIniFile(output_file_path, &token_to_line_no_and_other_map); if (unlikely(not FileUtil::RenameFile(output_file_path, output_file_path + ".bak", /* remove_target = */true))) logger->error("failed to rename \"" + output_file_path + "\" to \"" + output_file_path + ".bak\"! (" + std::string(::strerror(errno)) + ")"); } File output(output_file_path, "w"); if (unlikely(output.fail())) logger->error("failed to open \"" + output_file_path + "\" for writing!"); db_connection->queryOrDie("SELECT token,translation FROM vufind_translations WHERE language_code='" + _3letter_code + "'"); DbResultSet result_set(db_connection->getLastResultSet()); if (unlikely(result_set.empty())) logger->error("found no translations for language code \"" + _3letter_code + "\"!"); if (verbose) std::cerr << "\tFound " << result_set.size() << " (token,translation) pairs.\n"; std::vector<std::tuple<unsigned, std::string, std::string>> line_nos_tokens_and_translations; while (const DbRow row = result_set.getNextRow()) { const auto &token_to_line_no_and_other(token_to_line_no_and_other_map.find(row[0])); if (token_to_line_no_and_other != token_to_line_no_and_other_map.cend()) line_nos_tokens_and_translations.emplace_back(token_to_line_no_and_other->second.first, row[0], row[1]); else line_nos_tokens_and_translations.emplace_back(token_to_line_no_and_other_map.size() + 1, row[0], row[1]); } std::sort(line_nos_tokens_and_translations.begin(), line_nos_tokens_and_translations.end(), [](const std::tuple<unsigned, std::string,std::string> &left, const std::tuple<unsigned, std::string,std::string> &right) { return std::get<0>(left) < std::get<0>(right); }); for (const auto &line_no_token_and_translation : line_nos_tokens_and_translations) { const std::string token(std::get<1>(line_no_token_and_translation)); const std::string translation(std::get<2>(line_no_token_and_translation)); if (not translation.empty()) output << token << " = \"" << StringUtil::TrimWhite(NormalizeBrackets(translation)) << "\"\n"; } if (verbose) std::cerr << "Wrote " << line_nos_tokens_and_translations.size() << " language mappings to \"" << output_file_path << "\"\n"; } void GetLanguageCodes(const bool verbose, DbConnection * const db_connection, std::map<std::string, std::string> * language_codes) { db_connection->queryOrDie("SELECT DISTINCT language_code FROM vufind_translations"); DbResultSet language_codes_result_set(db_connection->getLastResultSet()); if (unlikely(language_codes_result_set.empty())) logger->error("no language codes found, expected multiple!"); while (const DbRow row = language_codes_result_set.getNextRow()) { const std::string german_language_code( TranslationUtil::MapFake3LetterEnglishLanguagesCodesToGermanLanguageCodes(row[0])); if (german_language_code == "???") continue; const std::string international_language_code( TranslationUtil::MapGerman3Or4LetterCodeToInternational2LetterCode(german_language_code)); language_codes->emplace(international_language_code, row[0]); } if (verbose) std::cerr << "Found " << language_codes->size() << " distinct language code in the \"vufind_translations\" table.\n"; } const std::string CONF_FILE_PATH("/usr/local/var/lib/tuelib/translations.conf"); int main(int argc, char **argv) { ::progname = argv[0]; if (argc < 2) Usage(); bool verbose(false); if (std::strcmp(argv[1], "--verbose") == 0) { verbose = true; --argc, ++argv; } if (argc != 2) Usage(); const std::string output_directory(argv[1]); if (unlikely(not FileUtil::IsDirectory(output_directory))) logger->error("\"" + output_directory + "\" is not a directory or can't be read!"); try { const IniFile ini_file(CONF_FILE_PATH); const std::string sql_database(ini_file.getString("Database", "sql_database")); const std::string sql_username(ini_file.getString("Database", "sql_username")); const std::string sql_password(ini_file.getString("Database", "sql_password")); DbConnection db_connection(sql_database, sql_username, sql_password); std::map<std::string, std::string> _2letter_and_3letter_codes; GetLanguageCodes(verbose, &db_connection, &_2letter_and_3letter_codes); for (const auto &_2letter_intl_code_and_fake_3letter_english_code : _2letter_and_3letter_codes) ProcessLanguage(verbose, output_directory + "/" + _2letter_intl_code_and_fake_3letter_english_code.first + ".ini", _2letter_intl_code_and_fake_3letter_english_code.second, &db_connection); } catch (const std::exception &x) { logger->error("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>#include <irrlicht.h> #include <iostream> namespace ic = irr::core; namespace iv = irr::video; // Serialize an irrlicht vector3df std::ostream& operator<<(std::ostream& out, const ic::vector3df vec) { out << "(" << vec.X << "," << vec.Y << "," << vec.Z << ")"; return out; } // Serialize an irrlicht vector3df std::ostream& operator<<(std::ostream& out, const ic::vector3di vec) { out << "(" << vec.X << "," << vec.Y << "," << vec.Z << ")"; return out; } // Serialize an irrlicht vector3df std::ostream& operator<<(std::ostream& out, const ic::vector2df vec) { out << "(" << vec.X << "," << vec.Y << ")"; return out; } // Serialize an irrlicht vector3df std::ostream& operator<<(std::ostream& out, const ic::vector2di vec) { out << "(" << vec.X << "," << vec.Y << ")"; return out; } // Serialize an irrlicht matrix4 std::ostream& operator<<(std::ostream& out, const ic::matrix4 mat) { for(int i=0 ; i<4 ; ++i) { for(int j=0 ; j<4 ; ++j) { out << mat(j,i) << " "; } out << std::endl; } return out; } // Serialize an irrlicht SColor std::ostream& operator<<(std::ostream& out, const iv::SColor color) { out << "(" << color.getAlpha() << "," << color.getRed() << "," << color.getGreen() << "," << color.getBlue() << ")"; return out; } // Serialize an irrlicht SColorf std::ostream& operator<<(std::ostream& out, const iv::SColorf color) { out << "(" << color.getAlpha() << "," << color.getRed() << "," << color.getGreen() << "," << color.getBlue() << ")"; return out; } <commit_msg>ENH: Add a function to flip along X axis meshes loaded from OBJ<commit_after>#include <irrlicht.h> #include <iostream> namespace ic = irr::core; namespace iv = irr::video; namespace is = irr::scene; // Serialize an irrlicht vector3df std::ostream& operator<<(std::ostream& out, const ic::vector3df vec) { out << "(" << vec.X << "," << vec.Y << "," << vec.Z << ")"; return out; } // Serialize an irrlicht vector3df std::ostream& operator<<(std::ostream& out, const ic::vector3di vec) { out << "(" << vec.X << "," << vec.Y << "," << vec.Z << ")"; return out; } // Serialize an irrlicht vector3df std::ostream& operator<<(std::ostream& out, const ic::vector2df vec) { out << "(" << vec.X << "," << vec.Y << ")"; return out; } // Serialize an irrlicht vector3df std::ostream& operator<<(std::ostream& out, const ic::vector2di vec) { out << "(" << vec.X << "," << vec.Y << ")"; return out; } // Serialize an irrlicht matrix4 std::ostream& operator<<(std::ostream& out, const ic::matrix4 mat) { for(int i=0 ; i<4 ; ++i) { for(int j=0 ; j<4 ; ++j) { out << mat(j,i) << " "; } out << std::endl; } return out; } // Serialize an irrlicht SColor std::ostream& operator<<(std::ostream& out, const iv::SColor color) { out << "(" << color.getAlpha() << "," << color.getRed() << "," << color.getGreen() << "," << color.getBlue() << ")"; return out; } // Serialize an irrlicht SColorf std::ostream& operator<<(std::ostream& out, const iv::SColorf color) { out << "(" << color.getAlpha() << "," << color.getRed() << "," << color.getGreen() << "," << color.getBlue() << ")"; return out; } // Load a mesh from an obj file, make an X symmetry, and flip the triangles // This is to avoid the mesh to be misplaced, because of irrlicht left-hand convention. is::IMesh * loadIMeshFromOBJ(is::ISceneManager * smgr, const char * filepath) { is::IMesh * mesh = smgr->getMesh(filepath); iv::S3DVertex* vertexArray = (iv::S3DVertex*)mesh->getMeshBuffer(0)->getVertices(); for(int i=0 ; i < mesh->getMeshBuffer(0)->getVertexCount() ; i++) { vertexArray[i].Pos.X = -vertexArray[i].Pos.X; } smgr->getMeshManipulator()->flipSurfaces(mesh); return mesh; } <|endoftext|>