text
stringlengths
54
60.6k
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // RUN: %cling %s "globalinit(\"%s\")" | FileCheck %s #include "cling/Interpreter/Interpreter.h" void globalinit(const std::string& location) { gCling->loadFile(location + ".h", false); // CHECK: A::S() gCling->loadFile(location + "2.h", false); // CHECK: B::S() } // CHECK: B::~S() // CHECK: A::~S() <commit_msg>Windows: Fix test failure because path has backslashes.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ // RUN: %cling %s -I%p | FileCheck %s #include "cling/Interpreter/Interpreter.h" void globalinit() { gCling->loadFile("globalinit.C.h", false); // CHECK: A::S() gCling->loadFile("globalinit.C2.h", false); // CHECK: B::S() } // CHECK: B::~S() // CHECK: A::~S() <|endoftext|>
<commit_before>/* - Fahre zu Position A - Mache dann Wandverfolgung bis Position B erreicht wird -- Falls Wandverfolgung nicht möglich, fahre direkt zu Position B - Wenn Position B erreicht, beende Wallfollowing und beende Task oder beginne von vorn */ #include "taskwallnavigation.h" #include "taskwallnavigationform.h" #include <QtGui> #include <Module_Simulation/module_simulation.h> TaskWallNavigation::TaskWallNavigation(QString id, Module_Simulation *sim, Behaviour_WallFollowing *w, Module_Navigation *n) : RobotBehaviour(id) { this->sim = sim; this->wall = w; this->wall->setEnabled(false); this->navi = n; setEnabled(false); running = false; // Default settings this->setDefaultValue("forwardSpeed",0.5); this->setDefaultValue("angularSpeed",0.3); this->setDefaultValue("desiredDistance",1.5); this->setDefaultValue("corridorWidth",0.2); this->setDefaultValue("description", ""); this->setDefaultValue("taskStopTime",120000); this->setDefaultValue("signalTimer",1000); this->setDefaultValue("startNavigation", "startN"); this->setDefaultValue("targetNavigation", "targetN"); this->setDefaultValue("targetTolerance", 10); this->setDefaultValue("timerActivated", true); this->setDefaultValue("loopActivated", true); this->setDefaultValue("initHeading", 0); taskTimer.setSingleShot(true); taskTimer.moveToThread(this); distanceToTarget = 0; connect(this, SIGNAL(enabled(bool)), this, SLOT(controlEnabledChanged(bool))); connect(navi, SIGNAL(reachedWaypoint(QString)), this, SLOT(seReached(QString))); } bool TaskWallNavigation::isActive(){ return isEnabled(); } void TaskWallNavigation::init(){ logger->debug("taskwallnavigation init"); } void TaskWallNavigation::startBehaviour(){ if (this->isEnabled() == true){ logger->info("Already enabled/started!"); return; } this->reset(); logger->info("Taskwallnavigation started" ); running = true; setHealthToOk(); setEnabled(true); emit started(this); running = true; emit newStateOverview("Move to start"); emit newStateOverview("Do wallfollowing"); emit newStateOverview("until end reached"); if(this->getSettingsValue("loopActivated").toBool()){ emit newStateOverview("...in a loop"); } // Enable all components if(!this->navi->isEnabled()){ this->navi->setEnabled(true); } addData("loop", this->getSettingsValue("loopActivated").toBool()); addData("stoptimer", this->getSettingsValue("timerActivated").toBool()); addData("state", "Start TaskWallNavigation"); emit dataChanged(this); emit newState("Start TaskWallNavigation"); emit updateSettings(); if(this->getSettingsValue("timerActivated").toBool()){ logger->debug("Taskwallnavigation with timer stop"); taskTimer.singleShot(this->getSettingsValue("taskStopTime").toInt(),this, SLOT(timeoutStop())); taskTimer.start(); } QTimer::singleShot(0, this, SLOT(moveToStart())); } void TaskWallNavigation::moveToStart(){ if(this->isEnabled() && this->navi->getHealthStatus().isHealthOk()){ logger->info("Move to start"); addData("state", "Move to start"); emit newState("Move to start"); emit dataChanged(this); this->navi->gotoWayPoint(this->getSettingsValue("startNavigation").toString()); } else { logger->info("Something is wrong with navigation/task, abort..."); QTimer::singleShot(0, this, SLOT(emergencyStop())); } } void TaskWallNavigation::seReached(QString waypoint){ if(this->isEnabled() == true){ if(waypoint == this->getSettingsValue("startNavigation").toString()){ // Start reached, do wallfollowing qDebug("Start reached"); QTimer::singleShot(0, navi, SLOT(clearGoal())); QTimer::singleShot(0, this, SLOT(doWallFollow())); } else if(waypoint == this->getSettingsValue("targetNavigation").toString()){ // End reached, control next state qDebug("End reached"); QTimer::singleShot(0, navi, SLOT(clearGoal())); QTimer::singleShot(0, this, SLOT(controlNextState())); } else { // Error! logger->info("Something is wrong with navigation waypoints, abort..."); QTimer::singleShot(0, this, SLOT(emergencyStop())); } } } void TaskWallNavigation::doWallFollow(){ if(this->isEnabled()){ logger->info("Do wallfollowing"); addData("state", "Do wallfollowing"); emit newState("Do wallfollowing"); emit dataChanged(this); this->wall->setSettingsValue("corridorWidth",this->getSettingsValue("corridorWidth").toFloat()); this->wall->setSettingsValue("desiredDistance",this->getSettingsValue("desiredDistance").toFloat()); this->wall->setSettingsValue("initHeading",this->getSettingsValue("initHeading").toFloat()); this->wall->setSettingsValue("loopActivated",this->getSettingsValue("loopActivated").toBool()); if(!this->wall->isEnabled()){ logger->debug("enable wallfollow and echo"); QTimer::singleShot(0, wall, SLOT(startBehaviour())); } else { QTimer::singleShot(0, wall, SLOT(reset())); } // Now do wallfollowing until target position is reached distanceToTarget = this->navi->getDistance(this->getSettingsValue("targetNavigation").toString()); addData("remaining distance",distanceToTarget); while(distanceToTarget > this->getSettingsValue("targetTolerance").toDouble()){ qDebug()<<"remaining distance"<<distanceToTarget; addData("remaining distance",distanceToTarget); emit dataChanged(this); msleep(100); } addData("remaining distance", "-"); emit dataChanged(this); addData("state", "Wallfollowing finished"); emit dataChanged(this); // Target position reached, stop wallfollow if(this->wall->isEnabled()){ logger->debug("Disable wallfollow and echo"); QTimer::singleShot(0, wall, SLOT(stop())); this->wall->echo->setEnabled(false); } QTimer::singleShot(0, this, SLOT(controlNextState())); } else { logger->info("Something is wrong with wallfollow/task, moveToEnd..."); QTimer::singleShot(0, this, SLOT(moveToEnd())); } } void TaskWallNavigation::moveToEnd(){ if(this->isEnabled() && this->navi->getHealthStatus().isHealthOk()){ logger->info("Move to end"); addData("state", "Move to end"); emit dataChanged(this); emit newState("Move to end"); this->navi->gotoWayPoint(this->getSettingsValue("startNavigation").toString()); } else { logger->info("Something is wrong with navigation, abort..."); QTimer::singleShot(0, this, SLOT(emergencyStop())); } } void TaskWallNavigation::controlNextState(){ if(this->isEnabled()){ logger->debug("idle, controlNextState"); addData("state", "Idle, control next state"); emit dataChanged(this); emit newState("Idle, control next state"); if(this->getSettingsValue("loopActivated").toBool()){ logger->debug("start again"); QTimer::singleShot(0, this, SLOT(moveToStart())); } else { // Task finished, stop QTimer::singleShot(0, this, SLOT(stop())); } } else { logger->info("Something is wrong with the task, abort..."); QTimer::singleShot(0, this, SLOT(emergencyStop())); } } void TaskWallNavigation::stop(){ if(this->isEnabled()){ running = false; logger->info("Taskwallnavigation stopped"); if (this->isActive()) { this->taskTimer.stop(); this->navi->setEnabled(false); this->wall->echo->setEnabled(false); QTimer::singleShot(0, wall, SLOT(stop())); this->setEnabled(false); emit finished(this,true); } } else { logger->info("Something is really wrong..."); emit finished(this,false); } } void TaskWallNavigation::timeoutStop(){ if(this->isEnabled()){ running = false; logger->info("Taskwallnavigation timeout stopped"); if (this->isActive()) { QTimer::singleShot(0, navi, SLOT(clearGoal())); this->taskTimer.stop(); this->navi->setEnabled(false); this->wall->echo->setEnabled(false); QTimer::singleShot(0, wall, SLOT(stop())); this->setEnabled(false); emit finished(this,false); } } } void TaskWallNavigation::emergencyStop(){ if (this->isEnabled() == false){ logger->info("Not enabled!"); return; } running = false; logger->info( "Taskwallnavigation emergency stopped" ); if (this->isActive()) { QTimer::singleShot(0, navi, SLOT(clearGoal())); this->taskTimer.stop(); this->navi->setEnabled(false); this->wall->echo->setEnabled(false); QTimer::singleShot(0, wall, SLOT(stop())); this->setEnabled(false); emit finished(this,false); } } void TaskWallNavigation::terminate() { this->stop(); RobotModule::terminate(); } QWidget* TaskWallNavigation::createView(QWidget *parent) { return new TaskWallNavigationForm(this, parent); } QList<RobotModule*> TaskWallNavigation::getDependencies() { QList<RobotModule*> ret; ret.append(wall); ret.append(sim); return ret; } void TaskWallNavigation::controlEnabledChanged(bool b){ if(b == false){ logger->info("No longer enabled!"); QTimer::singleShot(0, this, SLOT(emergencyStop())); } } <commit_msg>taskwallnavi bugfix<commit_after>/* - Fahre zu Position A - Mache dann Wandverfolgung bis Position B erreicht wird -- Falls Wandverfolgung nicht möglich, fahre direkt zu Position B - Wenn Position B erreicht, beende Wallfollowing und beende Task oder beginne von vorn */ #include "taskwallnavigation.h" #include "taskwallnavigationform.h" #include <QtGui> #include <Module_Simulation/module_simulation.h> TaskWallNavigation::TaskWallNavigation(QString id, Module_Simulation *sim, Behaviour_WallFollowing *w, Module_Navigation *n) : RobotBehaviour(id) { this->sim = sim; this->wall = w; this->wall->setEnabled(false); this->navi = n; setEnabled(false); running = false; // Default settings this->setDefaultValue("forwardSpeed",0.5); this->setDefaultValue("angularSpeed",0.3); this->setDefaultValue("desiredDistance",1.5); this->setDefaultValue("corridorWidth",0.2); this->setDefaultValue("description", ""); this->setDefaultValue("taskStopTime",120000); this->setDefaultValue("signalTimer",1000); this->setDefaultValue("startNavigation", "startN"); this->setDefaultValue("targetNavigation", "targetN"); this->setDefaultValue("targetTolerance", 10); this->setDefaultValue("timerActivated", true); this->setDefaultValue("loopActivated", true); this->setDefaultValue("initHeading", 0); taskTimer.setSingleShot(true); taskTimer.moveToThread(this); distanceToTarget = 0; connect(this, SIGNAL(enabled(bool)), this, SLOT(controlEnabledChanged(bool))); connect(navi, SIGNAL(reachedWaypoint(QString)), this, SLOT(seReached(QString))); } bool TaskWallNavigation::isActive(){ return isEnabled(); } void TaskWallNavigation::init(){ logger->debug("taskwallnavigation init"); } void TaskWallNavigation::startBehaviour(){ if (this->isEnabled() == true){ logger->info("Already enabled/started!"); return; } this->reset(); logger->info("Taskwallnavigation started" ); running = true; setHealthToOk(); setEnabled(true); emit started(this); running = true; emit newStateOverview("Move to start"); emit newStateOverview("Do wallfollowing"); emit newStateOverview("until end reached"); if(this->getSettingsValue("loopActivated").toBool()){ emit newStateOverview("...in a loop"); } // Enable all components if(!this->navi->isEnabled()){ this->navi->setEnabled(true); } addData("loop", this->getSettingsValue("loopActivated").toBool()); addData("stoptimer", this->getSettingsValue("timerActivated").toBool()); addData("state", "Start TaskWallNavigation"); emit dataChanged(this); emit newState("Start TaskWallNavigation"); emit updateSettings(); if(this->getSettingsValue("timerActivated").toBool()){ logger->debug("Taskwallnavigation with timer stop"); taskTimer.singleShot(this->getSettingsValue("taskStopTime").toInt(),this, SLOT(timeoutStop())); taskTimer.start(); } QTimer::singleShot(0, this, SLOT(moveToStart())); } void TaskWallNavigation::moveToStart(){ if(this->isEnabled() && this->navi->getHealthStatus().isHealthOk()){ logger->info("Move to start"); addData("state", "Move to start"); emit newState("Move to start"); emit dataChanged(this); this->navi->gotoWayPoint(this->getSettingsValue("startNavigation").toString()); } else { logger->info("Something is wrong with navigation/task, abort..."); QTimer::singleShot(0, this, SLOT(emergencyStop())); } } void TaskWallNavigation::seReached(QString waypoint){ if(this->isEnabled() == true){ if(waypoint == this->getSettingsValue("startNavigation").toString()){ // Start reached, do wallfollowing qDebug("Start reached"); QTimer::singleShot(0, navi, SLOT(clearGoal())); QTimer::singleShot(0, this, SLOT(doWallFollow())); } else if(waypoint == this->getSettingsValue("targetNavigation").toString()){ // End reached, control next state qDebug("End reached"); QTimer::singleShot(0, navi, SLOT(clearGoal())); QTimer::singleShot(0, this, SLOT(controlNextState())); } else { // Error! logger->info("Something is wrong with navigation waypoints, abort..."); QTimer::singleShot(0, this, SLOT(emergencyStop())); } } } void TaskWallNavigation::doWallFollow(){ if(this->isEnabled()){ logger->info("Do wallfollowing"); addData("state", "Do wallfollowing"); emit newState("Do wallfollowing"); emit dataChanged(this); this->wall->setSettingsValue("corridorWidth",this->getSettingsValue("corridorWidth").toFloat()); this->wall->setSettingsValue("desiredDistance",this->getSettingsValue("desiredDistance").toFloat()); this->wall->setSettingsValue("initHeading",this->getSettingsValue("initHeading").toFloat()); this->wall->setSettingsValue("loopActivated",this->getSettingsValue("loopActivated").toBool()); if(!this->wall->isEnabled()){ logger->debug("enable wallfollow and echo"); QTimer::singleShot(0, wall, SLOT(startBehaviour())); } else { QTimer::singleShot(0, wall, SLOT(reset())); } // Now do wallfollowing until target position is reached distanceToTarget = this->navi->getDistance(this->getSettingsValue("targetNavigation").toString()); logger->debug("remaining distance", distanceToTarget, "",""); while(distanceToTarget > this->getSettingsValue("targetTolerance").toDouble()){ distanceToTarget = this->navi->getDistance(this->getSettingsValue("targetNavigation").toString()); logger->debug("remaining distance", distanceToTarget, "",""); addData("remaining distance",distanceToTarget); emit dataChanged(this); msleep(100); } addData("remaining distance", "-"); emit dataChanged(this); addData("state", "Wallfollowing finished"); emit dataChanged(this); // Target position reached, stop wallfollow if(this->wall->isEnabled()){ logger->debug("Disable wallfollow and echo"); QTimer::singleShot(0, wall, SLOT(stop())); this->wall->echo->setEnabled(false); } QTimer::singleShot(0, this, SLOT(controlNextState())); } else { logger->info("Something is wrong with wallfollow/task, moveToEnd..."); QTimer::singleShot(0, this, SLOT(moveToEnd())); } } void TaskWallNavigation::moveToEnd(){ if(this->isEnabled() && this->navi->getHealthStatus().isHealthOk()){ logger->info("Move to end"); addData("state", "Move to end"); emit dataChanged(this); emit newState("Move to end"); this->navi->gotoWayPoint(this->getSettingsValue("startNavigation").toString()); } else { logger->info("Something is wrong with navigation, abort..."); QTimer::singleShot(0, this, SLOT(emergencyStop())); } } void TaskWallNavigation::controlNextState(){ if(this->isEnabled()){ logger->debug("idle, controlNextState"); addData("state", "Idle, control next state"); emit dataChanged(this); emit newState("Idle, control next state"); if(this->getSettingsValue("loopActivated").toBool()){ logger->debug("start again"); QTimer::singleShot(0, this, SLOT(moveToStart())); } else { // Task finished, stop QTimer::singleShot(0, this, SLOT(stop())); } } else { logger->info("Something is wrong with the task, abort..."); QTimer::singleShot(0, this, SLOT(emergencyStop())); } } void TaskWallNavigation::stop(){ if(this->isEnabled()){ running = false; logger->info("Taskwallnavigation stopped"); if (this->isActive()) { this->taskTimer.stop(); this->navi->setEnabled(false); this->wall->echo->setEnabled(false); QTimer::singleShot(0, wall, SLOT(stop())); this->setEnabled(false); emit finished(this,true); } } else { logger->info("Something is really wrong..."); emit finished(this,false); } } void TaskWallNavigation::timeoutStop(){ if(this->isEnabled()){ running = false; logger->info("Taskwallnavigation timeout stopped"); if (this->isActive()) { QTimer::singleShot(0, navi, SLOT(clearGoal())); this->taskTimer.stop(); this->navi->setEnabled(false); this->wall->echo->setEnabled(false); QTimer::singleShot(0, wall, SLOT(stop())); this->setEnabled(false); emit finished(this,false); } } } void TaskWallNavigation::emergencyStop(){ if (this->isEnabled() == false){ logger->info("Not enabled!"); return; } running = false; logger->info( "Taskwallnavigation emergency stopped" ); if (this->isActive()) { QTimer::singleShot(0, navi, SLOT(clearGoal())); this->taskTimer.stop(); this->navi->setEnabled(false); this->wall->echo->setEnabled(false); QTimer::singleShot(0, wall, SLOT(stop())); this->setEnabled(false); emit finished(this,false); } } void TaskWallNavigation::terminate() { this->stop(); RobotModule::terminate(); } QWidget* TaskWallNavigation::createView(QWidget *parent) { return new TaskWallNavigationForm(this, parent); } QList<RobotModule*> TaskWallNavigation::getDependencies() { QList<RobotModule*> ret; ret.append(wall); ret.append(sim); return ret; } void TaskWallNavigation::controlEnabledChanged(bool b){ if(b == false){ logger->info("No longer enabled!"); QTimer::singleShot(0, this, SLOT(emergencyStop())); } } <|endoftext|>
<commit_before>/** * \file affordance_safari.cpp * \brief * * \author Andrew Price * \date November 27, 2013 * * \copyright * * Copyright (c) 2013, Georgia Tech Research Corporation * All rights reserved. * * This file is provided under the following "BSD-style" License: * 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. */ #define _USE_MATH_DEFINES // for MS C++ #include <cmath> #include <random> #include <time.h> #include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> template <class T> inline T square(const T &x) { return x*x; } inline float randbetween(float min, float max) { return (max - min) * ( (float)rand() / (float)RAND_MAX ) + min; } class Distribution { public: Distribution(double mu, double s, double w) { mean = mu; covariance = s; setWeight(w); } double mean; double covariance; inline void setWeight(const double w) { weight = w; l_weight = log(w); } double probability(const double x) const { double delta = (x-mean); return exp(-(delta*delta)/(2.0*covariance) + l_weight); } friend std::ostream& operator <<(std::ostream& s, const Distribution& d) { s << "{ Mean: " << d.mean << " Covar: " << d.covariance << " Weight: " << d.weight << " }"; return s; } protected: double weight; double l_weight; }; const int MAP_HEIGHT = 100; const int MAP_WIDTH = 100; const float COLOR_STDDEV = 10.0f; const int NUM_SEARCHERS = 5; const int MAX_ITERS = 1000; class World { public: World() { srand((unsigned int)time(NULL)); goal = cv::Point2i(rand()%MAP_WIDTH, rand()%MAP_HEIGHT); distribution = std::normal_distribution<float>(0.0, COLOR_STDDEV); createMap(); recolorMap(); } unsigned char map[MAP_HEIGHT][MAP_WIDTH]; float colorMap[MAP_HEIGHT][MAP_WIDTH]; cv::Point2i goal; std::default_random_engine generator; std::normal_distribution<float> distribution; void createMap() { for (int y = 0; y < MAP_HEIGHT; ++y) { for (int x = 0; x < MAP_WIDTH; ++x) { map[y][x] = (uchar)rand(); } } map[goal.y][goal.x] = 0; } void recolorMap() { for (int y = 0; y < MAP_HEIGHT; ++y) { for (int x = 0; x < MAP_WIDTH; ++x) { colorMap[y][x] = (float)map[y][x] + distribution(generator); } } } }; class Searcher { public: Searcher(float l, cv::Point2i start, World* w) { affordanceLevel = l; location = start; world = w; } float affordanceLevel; cv::Point2i location; World* world; inline float distanceFunction(cv::Point2i& a, cv::Point2i& b) { return square(square(a.x-b.x)+square(a.y-b.y)); } std::vector<cv::Point2i> getNeighbors() { std::vector<cv::Point2i> neighbors; if (location.y > 0) { neighbors.push_back(cv::Point2i(location.x, location.y - 1)); } if (location.y < MAP_HEIGHT - 1) { neighbors.push_back(cv::Point2i(location.x, location.y + 1)); } if (location.x > 0) { neighbors.push_back(cv::Point2i(location.x - 1, location.y)); } if (location.x < MAP_WIDTH - 1) { neighbors.push_back(cv::Point2i(location.x + 1, location.y)); } return neighbors; } bool goLocation(const cv::Point2i& destination) { if ((float)world->map[destination.y][destination.x] < affordanceLevel) { location = destination; return true; } else { std::cout << "Move Failed:" << (float)world->map[destination.y][destination.x] << ">" << affordanceLevel << std::endl; return false; } } cv::Point2i proposeMove() { float neighborScores[4]; float totalScore = 0; std::vector<cv::Point2i> neighbors = getNeighbors(); for (int n = 0; n < neighbors.size(); ++n) { if (neighbors[n] == world->goal) { return neighbors[n]; } // Victory! float score = 1/distanceFunction(world->goal, neighbors[n]); neighborScores[n] = score + (n > 0 ? neighborScores[n-1] : 0); totalScore += score; } for (int n = 0; n < neighbors.size(); ++n) { neighborScores[n] /= totalScore; } float r = randbetween(0, 1); for (int n = 0; n < neighbors.size(); ++n) { if (r < neighborScores[n]) { return neighbors[n]; } } return neighbors.back(); } }; World world; cv::Vec3b displayColor(uchar val) { cv::Vec3b vec; //vec[1] = 255-val; //vec[2] = val; float a = (float)val / 255.0f * M_PI / 2.0; vec[1] = 255.0f * cos(a); vec[2] = 255.0f * sin(a); return vec; } cv::Mat drawMap() { cv::Mat mapPic(MAP_HEIGHT, MAP_WIDTH, CV_8UC1); for (int y = 0; y < MAP_HEIGHT; ++y) { for (int x = 0; x < MAP_WIDTH; ++x) { mapPic.data[y * MAP_WIDTH + x] = 255-world.map[y][x]; } } return mapPic; } cv::Mat drawColorMap(std::vector<Searcher> searchers = std::vector<Searcher>()) { cv::Mat mapPic(MAP_HEIGHT, MAP_WIDTH, CV_8UC3); for (int y = 0; y < MAP_HEIGHT; ++y) { for (int x = 0; x < MAP_WIDTH; ++x) { mapPic.at<cv::Vec3b>(cv::Point2i(x,y)) = displayColor(world.colorMap[y][x]); } } mapPic.at<cv::Vec3b>(world.goal) = cv::Vec3b(255, 255, 255); for (Searcher s : searchers) { mapPic.at<cv::Vec3b>(s.location) = cv::Vec3b(255, 0, 0); } return mapPic; } int main() { cv::Mat mapPic = drawMap(); cv::Mat mapPicColor = drawColorMap(); cv::namedWindow("True Map", cv::WINDOW_NORMAL); cv::imshow("True Map", mapPic); cv::namedWindow("Color Map", cv::WINDOW_NORMAL); cv::imshow("Color Map", mapPicColor); cv::waitKey(); std::vector<Searcher> searchers; for (int i = 0; i < NUM_SEARCHERS; ++i) { searchers.push_back(Searcher(randbetween(190, 220), cv::Point2i(rand()%MAP_WIDTH, rand()%MAP_HEIGHT), &world)); } int iters = 0; while (iters < MAX_ITERS) { for (Searcher& s : searchers) { s.goLocation(s.proposeMove()); if (s.location == world.goal) { return 0; } } mapPicColor = drawColorMap(searchers); cv::imshow("Color Map", mapPicColor); cv::waitKey(10); iters++; } } <commit_msg>Added smoothing to map.<commit_after>/** * \file affordance_safari.cpp * \brief * * \author Andrew Price * \date November 27, 2013 * * \copyright * * Copyright (c) 2013, Georgia Tech Research Corporation * All rights reserved. * * This file is provided under the following "BSD-style" License: * 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. */ #define _USE_MATH_DEFINES // for MS C++ #include <cmath> #include <random> #include <time.h> #include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> template <class T> inline T square(const T &x) { return x*x; } inline float randbetween(float min, float max) { return (max - min) * ( (float)rand() / (float)RAND_MAX ) + min; } class Distribution { public: Distribution(double mu, double s, double w) { mean = mu; covariance = s; setWeight(w); } double mean; double covariance; inline void setWeight(const double w) { weight = w; l_weight = log(w); } double probability(const double x) const { double delta = (x-mean); return exp(-(delta*delta)/(2.0*covariance) + l_weight); } friend std::ostream& operator <<(std::ostream& s, const Distribution& d) { s << "{ Mean: " << d.mean << " Covar: " << d.covariance << " Weight: " << d.weight << " }"; return s; } protected: double weight; double l_weight; }; const int MAP_HEIGHT = 300; const int MAP_WIDTH = 300; const float COLOR_STDDEV = 10.0f; const int NUM_SEARCHERS = MAP_HEIGHT * MAP_WIDTH / 5000; const int MAX_ITERS = 1000; class World { public: World() { srand((unsigned int)time(NULL)); goal = cv::Point2i(rand()%MAP_WIDTH, rand()%MAP_HEIGHT); distribution = std::normal_distribution<float>(0.0, COLOR_STDDEV); createMap(); recolorMap(); } unsigned char map[MAP_HEIGHT][MAP_WIDTH]; float colorMap[MAP_HEIGHT][MAP_WIDTH]; cv::Point2i goal; std::default_random_engine generator; std::normal_distribution<float> distribution; void createMap() { for (int y = 0; y < MAP_HEIGHT; ++y) { for (int x = 0; x < MAP_WIDTH; ++x) { map[y][x] = (uchar)rand(); } } cv::Mat temp(MAP_HEIGHT, MAP_WIDTH, CV_8UC1, map, sizeof(uchar) * MAP_WIDTH); int neighborhoodSize = (MAP_HEIGHT > MAP_WIDTH) ? MAP_WIDTH : MAP_HEIGHT; neighborhoodSize /= 40; if (neighborhoodSize % 2 == 0) { neighborhoodSize += 1; } cv::GaussianBlur(temp, temp, cv::Size(neighborhoodSize,neighborhoodSize), 3, 3); map[goal.y][goal.x] = 0; } void recolorMap() { for (int y = 0; y < MAP_HEIGHT; ++y) { for (int x = 0; x < MAP_WIDTH; ++x) { colorMap[y][x] = (float)map[y][x] + distribution(generator); } } } }; class Searcher { public: Searcher(float l, cv::Point2i start, World* w) { affordanceLevel = l; location = start; world = w; } float affordanceLevel; cv::Point2i location; World* world; inline float distanceFunction(cv::Point2i& a, cv::Point2i& b) { return square(square(a.x-b.x)+square(a.y-b.y)); } std::vector<cv::Point2i> getNeighbors() { std::vector<cv::Point2i> neighbors; if (location.y > 0) { neighbors.push_back(cv::Point2i(location.x, location.y - 1)); } if (location.y < MAP_HEIGHT - 1) { neighbors.push_back(cv::Point2i(location.x, location.y + 1)); } if (location.x > 0) { neighbors.push_back(cv::Point2i(location.x - 1, location.y)); } if (location.x < MAP_WIDTH - 1) { neighbors.push_back(cv::Point2i(location.x + 1, location.y)); } return neighbors; } bool goLocation(const cv::Point2i& destination) { if ((float)world->map[destination.y][destination.x] < affordanceLevel) { location = destination; return true; } else { std::cout << "Move Failed:" << (float)world->map[destination.y][destination.x] << ">" << affordanceLevel << std::endl; return false; } } cv::Point2i proposeMove() { float neighborScores[4]; float totalScore = 0; std::vector<cv::Point2i> neighbors = getNeighbors(); for (int n = 0; n < neighbors.size(); ++n) { if (neighbors[n] == world->goal) { return neighbors[n]; } // Victory! float score = 1/distanceFunction(world->goal, neighbors[n]); neighborScores[n] = score + (n > 0 ? neighborScores[n-1] : 0); totalScore += score; } for (int n = 0; n < neighbors.size(); ++n) { neighborScores[n] /= totalScore; } float r = randbetween(0, 1); for (int n = 0; n < neighbors.size(); ++n) { if (r < neighborScores[n]) { return neighbors[n]; } } return neighbors.back(); } }; World world; cv::Vec3b displayColor(uchar val) { cv::Vec3b vec; //vec[1] = 255-val; //vec[2] = val; float a = (float)val / 255.0f * M_PI / 2.0; vec[1] = 255.0f * cos(a); vec[2] = 255.0f * sin(a); return vec; } cv::Mat drawMap() { cv::Mat mapPic(MAP_HEIGHT, MAP_WIDTH, CV_8UC1); for (int y = 0; y < MAP_HEIGHT; ++y) { for (int x = 0; x < MAP_WIDTH; ++x) { mapPic.data[y * MAP_WIDTH + x] = 255-world.map[y][x]; } } return mapPic; } cv::Mat drawColorMap(std::vector<Searcher> searchers = std::vector<Searcher>()) { cv::Mat mapPic(MAP_HEIGHT, MAP_WIDTH, CV_8UC3); for (int y = 0; y < MAP_HEIGHT; ++y) { for (int x = 0; x < MAP_WIDTH; ++x) { mapPic.at<cv::Vec3b>(cv::Point2i(x,y)) = displayColor(world.colorMap[y][x]); } } mapPic.at<cv::Vec3b>(world.goal) = cv::Vec3b(255, 255, 255); for (Searcher s : searchers) { mapPic.at<cv::Vec3b>(s.location) = cv::Vec3b(255, 0, 0); } return mapPic; } int main() { cv::Mat mapPic = drawMap(); cv::Mat mapPicColor = drawColorMap(); cv::namedWindow("True Map", cv::WINDOW_NORMAL); cv::imshow("True Map", mapPic); cv::namedWindow("Color Map", cv::WINDOW_NORMAL); cv::imshow("Color Map", mapPicColor); cv::waitKey(); std::vector<Searcher> searchers; for (int i = 0; i < NUM_SEARCHERS; ++i) { searchers.push_back(Searcher(randbetween(150, 230), cv::Point2i(rand()%MAP_WIDTH, rand()%MAP_HEIGHT), &world)); } int iters = 0; while (iters < MAX_ITERS) { for (Searcher& s : searchers) { s.goLocation(s.proposeMove()); if (s.location == world.goal) { return 0; } } mapPicColor = drawColorMap(searchers); cv::imshow("Color Map", mapPicColor); cv::waitKey(10); iters++; } } <|endoftext|>
<commit_before> #include "stdafx.h" #include "Math.h" #include <D3dx9math.h> using namespace common; //-------------------------------- // Constructor //-------------------------------- Quaternion::Quaternion() { } //Quaternion::Quaternion //-------------------------------- // //-------------------------------- Quaternion::Quaternion( const float fX, const float fY, const float fZ, const float fW ) : x ( fX ), y ( fY ), z ( fZ ), w ( fW ) { } //Quaternion //-------------------------------- // //-------------------------------- Quaternion::Quaternion( const Vector3& vAxis, const float fAngle ) { float s = sinf( fAngle / 2 ); float c = cosf( fAngle / 2 ); x = s * vAxis.x; y = s * vAxis.y; z = s * vAxis.z; w = c; } //Quaternion::Quaternion //-------------------------------- // //-------------------------------- Quaternion::Quaternion( const Vector3& vDir1, const Vector3& vDir2 ) { SetRotationArc( vDir1, vDir2 ); } //Quaternion::Quaternion //-------------------------------- // //-------------------------------- const Quaternion& Quaternion::Interpolate( const Quaternion& qNext, const float fTime ) const { static Quaternion qC; const Quaternion& qA = *this; Quaternion qB = qNext; float fCos = qA.x * qB.x + qA.y * qB.y + qA.z * qB.z + qA.w * qB.w; if( fCos < 0.0F ) { // ʹϾ . qB.x = -qB.x; qB.y = -qB.y; qB.z = -qB.z; qB.w = -qB.w; fCos = -fCos; } //if float fAlpha = fTime; float fBeta = 1.0F - fTime; if( ( 1.0F - fCos ) > 0.001F ) { // . float fTheta = acosf( fCos ); fBeta = sinf( fTheta * ( 1.0F - fTime ) ) / sinf( fTheta ); fAlpha = sinf( fTheta * fTime ) / sinf( fTheta ); } //if // . qC.x = fBeta * qA.x + fAlpha * qB.x; qC.y = fBeta * qA.y + fAlpha * qB.y; qC.z = fBeta * qA.z + fAlpha * qB.z; qC.w = fBeta * qA.w + fAlpha * qB.w; return qC; } //Quaternion::Interpolate //-------------------------------- // //-------------------------------- const Matrix44& Quaternion::GetMatrix() const { static Matrix44 m; /* float xx = x * x; float yy = y * y; float zz = z * z; float ww = w * w; float xy = x * y; float yz = y * z; float zx = z * x; float wx = w * x; float wy = w * y; float wz = w * z; m._11 = 1.0F - 2.0F * ( yy + zz ); m._12 = 2.0F * ( xy - wz ); m._13 = 2.0F * ( zx + wy ); m._21 = 2.0F * ( xy + wz ); m._22 = 1.0F - 2.0F * ( xx + zz ); m._23 = 2.0F * ( yz - wx ); m._31 = 2.0F * ( zx - wy ); m._32 = 2.0F * ( yz + wx ); m._33 = 1.0F - 2.0F * ( xx + yy ); m._14 = m._24 = m._34 = 0.0F; m._41 = m._42 = m._43 = 0.0F; m._44 = 1.0F; /**/ D3DXMatrixRotationQuaternion( (D3DXMATRIX*)&m, (D3DXQUATERNION*)this ); return m; } //Quaternion::GetMatrix4 //-------------------------------- // //-------------------------------- Vector3 Quaternion::GetDirection() const { // Matrix44 matRot = GetMatrix4(); // return -Vector3( matRot._31, matRot._32, matRot._33 ); float xx = x * x; float yy = y * y; // float zz = z * z; // float xy = x * y; float yz = y * z; float zx = z * x; float wx = w * x; float wy = w * y; // float wz = w * z; return -Vector3( 2.0F * ( zx - wy ), 2.0F * ( yz + wx ), 1.0F - 2.0F * ( xx + yy ) ).Normal(); } //Quaternion::GetDirection //-------------------------------- // //-------------------------------- void Quaternion::SetRotationX( const float fRadian ) { float s = sinf( fRadian / 2 ); float c = cosf( fRadian / 2 ); x = s * 1.0F; y = s * 0.0F; z = s * 0.0F; w = c; } //Quaternion::SetRotationX //-------------------------------- // //-------------------------------- void Quaternion::SetRotationY( const float fRadian ) { float s = sinf( fRadian / 2 ); float c = cosf( fRadian / 2 ); x = s * 0.0F; y = s * 1.0F; z = s * 0.0F; w = c; } //Quaternion::SetRotationY //-------------------------------- // //-------------------------------- void Quaternion::SetRotationZ( const float fRadian ) { float s = sinf( fRadian / 2 ); float c = cosf( fRadian / 2 ); x = s * 0.0F; y = s * 0.0F; z = s * 1.0F; w = c; } //Quaternion::SetRotationZ //-------------------------------- // //-------------------------------- void Quaternion::SetRotationArc( const Vector3& v0, const Vector3& v1 ) { Vector3 vCross = v0.CrossProduct(v1); const float len = vCross.Length(); if (len <= 0.01f) { x = 0; y = 1; z = 0; w = 0; return; } float fDot = v0.DotProduct( v1 ); float s = (float)sqrtf((1.0f + fDot) * 2.0f); //if (0.1f > s) //{ // x = 0; y = 1; z = 0; w = 0; // return; //} x = vCross.x / s; y = vCross.y / s; z = vCross.z / s; w = s * 0.5f; } //Quaternion::SetRotationArc //-------------------------------- // //-------------------------------- void Quaternion::Normalize() { float norm = sqrtf( SQR(x) + SQR(y) + SQR(z) + SQR(w) ); if( FLOAT_EQ( 0.0F, norm ) ) { return ; } //if norm = 1.0F / norm; x = x * norm; y = y * norm; z = z * norm; w = w * norm; norm = sqrtf( SQR(x) + SQR(y) + SQR(z) + SQR(w) ); if( !FLOAT_EQ( 1.0F, norm ) ) { return ; } //if LIMIT_RANGE(-1.0f, w, 1.0f); LIMIT_RANGE(-1.0f, x, 1.0f); LIMIT_RANGE(-1.0f, y, 1.0f); LIMIT_RANGE(-1.0f, z, 1.0f); } //Quaternion::Normalize <commit_msg>update quaternion<commit_after> #include "stdafx.h" #include "Math.h" #include <D3dx9math.h> using namespace common; //-------------------------------- // Constructor //-------------------------------- Quaternion::Quaternion() { } //Quaternion::Quaternion //-------------------------------- // //-------------------------------- Quaternion::Quaternion( const float fX, const float fY, const float fZ, const float fW ) : x ( fX ), y ( fY ), z ( fZ ), w ( fW ) { } //Quaternion //-------------------------------- // //-------------------------------- Quaternion::Quaternion( const Vector3& vAxis, const float fAngle ) { float s = sinf( fAngle / 2 ); float c = cosf( fAngle / 2 ); x = s * vAxis.x; y = s * vAxis.y; z = s * vAxis.z; w = c; } //Quaternion::Quaternion //-------------------------------- // //-------------------------------- Quaternion::Quaternion( const Vector3& vDir1, const Vector3& vDir2 ) { SetRotationArc( vDir1, vDir2 ); } //Quaternion::Quaternion //-------------------------------- // //-------------------------------- const Quaternion& Quaternion::Interpolate( const Quaternion& qNext, const float fTime ) const { static Quaternion qC; const Quaternion& qA = *this; Quaternion qB = qNext; float fCos = qA.x * qB.x + qA.y * qB.y + qA.z * qB.z + qA.w * qB.w; if( fCos < 0.0F ) { // ʹϾ . qB.x = -qB.x; qB.y = -qB.y; qB.z = -qB.z; qB.w = -qB.w; fCos = -fCos; } //if float fAlpha = fTime; float fBeta = 1.0F - fTime; if( ( 1.0F - fCos ) > 0.001F ) { // . float fTheta = acosf( fCos ); fBeta = sinf( fTheta * ( 1.0F - fTime ) ) / sinf( fTheta ); fAlpha = sinf( fTheta * fTime ) / sinf( fTheta ); } //if // . qC.x = fBeta * qA.x + fAlpha * qB.x; qC.y = fBeta * qA.y + fAlpha * qB.y; qC.z = fBeta * qA.z + fAlpha * qB.z; qC.w = fBeta * qA.w + fAlpha * qB.w; return qC; } //Quaternion::Interpolate //-------------------------------- // //-------------------------------- const Matrix44& Quaternion::GetMatrix() const { static Matrix44 m; /* float xx = x * x; float yy = y * y; float zz = z * z; float ww = w * w; float xy = x * y; float yz = y * z; float zx = z * x; float wx = w * x; float wy = w * y; float wz = w * z; m._11 = 1.0F - 2.0F * ( yy + zz ); m._12 = 2.0F * ( xy - wz ); m._13 = 2.0F * ( zx + wy ); m._21 = 2.0F * ( xy + wz ); m._22 = 1.0F - 2.0F * ( xx + zz ); m._23 = 2.0F * ( yz - wx ); m._31 = 2.0F * ( zx - wy ); m._32 = 2.0F * ( yz + wx ); m._33 = 1.0F - 2.0F * ( xx + yy ); m._14 = m._24 = m._34 = 0.0F; m._41 = m._42 = m._43 = 0.0F; m._44 = 1.0F; /**/ D3DXMatrixRotationQuaternion( (D3DXMATRIX*)&m, (D3DXQUATERNION*)this ); return m; } //Quaternion::GetMatrix4 //-------------------------------- // //-------------------------------- Vector3 Quaternion::GetDirection() const { // Matrix44 matRot = GetMatrix4(); // return -Vector3( matRot._31, matRot._32, matRot._33 ); float xx = x * x; float yy = y * y; // float zz = z * z; // float xy = x * y; float yz = y * z; float zx = z * x; float wx = w * x; float wy = w * y; // float wz = w * z; return -Vector3( 2.0F * ( zx - wy ), 2.0F * ( yz + wx ), 1.0F - 2.0F * ( xx + yy ) ).Normal(); } //Quaternion::GetDirection //-------------------------------- // //-------------------------------- void Quaternion::SetRotationX( const float fRadian ) { float s = sinf( fRadian / 2 ); float c = cosf( fRadian / 2 ); x = s * 1.0F; y = s * 0.0F; z = s * 0.0F; w = c; } //Quaternion::SetRotationX //-------------------------------- // //-------------------------------- void Quaternion::SetRotationY( const float fRadian ) { float s = sinf( fRadian / 2 ); float c = cosf( fRadian / 2 ); x = s * 0.0F; y = s * 1.0F; z = s * 0.0F; w = c; } //Quaternion::SetRotationY //-------------------------------- // //-------------------------------- void Quaternion::SetRotationZ( const float fRadian ) { float s = sinf( fRadian / 2 ); float c = cosf( fRadian / 2 ); x = s * 0.0F; y = s * 0.0F; z = s * 1.0F; w = c; } //Quaternion::SetRotationZ //-------------------------------- // //-------------------------------- void Quaternion::SetRotationArc( const Vector3& v0, const Vector3& v1 ) { Vector3 vCross = v0.CrossProduct(v1); const float len = vCross.Length(); if (len <= 0.01f) { x = 0; y = 0; z = 0; w = 1; return; } float fDot = v0.DotProduct( v1 ); float s = (float)sqrtf((1.0f + fDot) * 2.0f); //if (0.1f > s) //{ // x = 0; y = 1; z = 0; w = 0; // return; //} x = vCross.x / s; y = vCross.y / s; z = vCross.z / s; w = s * 0.5f; } //Quaternion::SetRotationArc //-------------------------------- // //-------------------------------- void Quaternion::Normalize() { float norm = sqrtf( SQR(x) + SQR(y) + SQR(z) + SQR(w) ); if( FLOAT_EQ( 0.0F, norm ) ) { return ; } //if norm = 1.0F / norm; x = x * norm; y = y * norm; z = z * norm; w = w * norm; norm = sqrtf( SQR(x) + SQR(y) + SQR(z) + SQR(w) ); if( !FLOAT_EQ( 1.0F, norm ) ) { return ; } //if LIMIT_RANGE(-1.0f, w, 1.0f); LIMIT_RANGE(-1.0f, x, 1.0f); LIMIT_RANGE(-1.0f, y, 1.0f); LIMIT_RANGE(-1.0f, z, 1.0f); } //Quaternion::Normalize <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: mergedcomponentdata.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2003-03-19 16:18:48 $ * * 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: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "mergedcomponentdata.hxx" #ifndef CONFIGMGR_TREE_NODEFACTORY_HXX #include "treenodefactory.hxx" #endif namespace configmgr { // ----------------------------------------------------------------------------- namespace backend { // ----------------------------------------------------------------------------- MergedComponentData::MergedComponentData( ) : m_pSchemaTree() , m_pTemplatesTree() { } // ----------------------------------------------------------------------------- MergedComponentData::~MergedComponentData( ) { } // ----------------------------------------------------------------------------- void MergedComponentData::clear( ) { m_pTemplatesTree.reset(); m_pSchemaTree.reset(); } // ----------------------------------------------------------------------------- bool MergedComponentData::hasSchema()const { return m_pSchemaTree.get() != NULL; } // ----------------------------------------------------------------------------- bool MergedComponentData::hasTemplates() const { return m_pTemplatesTree.get() != NULL; } // ----------------------------------------------------------------------------- OUString MergedComponentData::getTemplateAccessor (TemplateIdentifier const & _aTemplateName) const { return _aTemplateName.Name; } // ----------------------------------------------------------------------------- bool MergedComponentData::hasTemplate(OUString const & _aTemplateName) const { return m_pTemplatesTree.get() != NULL && m_pTemplatesTree->getChild( _aTemplateName ) != NULL; } // ----------------------------------------------------------------------------- std::auto_ptr<ISubtree> MergedComponentData::extractSchemaTree() { return m_pSchemaTree; } // ----------------------------------------------------------------------------- std::auto_ptr<ISubtree> MergedComponentData::extractTemplatesTree() { return m_pTemplatesTree; } // ----------------------------------------------------------------------------- std::auto_ptr<INode> MergedComponentData::extractTemplateNode(OUString const & _aTemplateName) { if (m_pTemplatesTree.get() == NULL) return std::auto_ptr<INode>(); return m_pTemplatesTree->removeChild(_aTemplateName); } // ----------------------------------------------------------------------------- ISubtree const * MergedComponentData::getSchemaTree() const { return m_pSchemaTree.get(); } // ----------------------------------------------------------------------------- ISubtree const * MergedComponentData::findTemplate(OUString const & _aTemplateName) const { INode const * pTemplateNode = m_pTemplatesTree->getChild(_aTemplateName); ISubtree const * pTemplateTree = pTemplateNode ? pTemplateNode->asISubtree() : NULL; OSL_ENSURE(pTemplateTree || !pTemplateNode, "ERROR: Template is not a subtree"); return pTemplateTree; } // ----------------------------------------------------------------------------- std::auto_ptr<INode> MergedComponentData::instantiateTemplate(OUString const & _aName, OUString const & _aTemplateName) const { if (INode const * pTemplateNode = m_pTemplatesTree->getChild(_aTemplateName)) { std::auto_ptr<INode> aResult = pTemplateNode->clone(); aResult->setName(_aName); return aResult; } else { return std::auto_ptr<INode>(); } } // ----------------------------------------------------------------------------- ISubtree * MergedComponentData::setSchemaRoot(std::auto_ptr<ISubtree> _aSchemaRoot) { OSL_PRECOND(_aSchemaRoot.get(),"ERROR: Setting a NULL schema root."); OSL_PRECOND(!hasSchema(),"ERROR: Schema root already set"); m_pSchemaTree = _aSchemaRoot; return m_pSchemaTree.get(); } // ----------------------------------------------------------------------------- ISubtree * MergedComponentData::addTemplate(std::auto_ptr<ISubtree> _aNode, TemplateIdentifier const & aTemplate) { OSL_PRECOND(_aNode.get(), "ERROR: Adding a NULL template"); if (!m_pTemplatesTree.get()) { m_pTemplatesTree = getDefaultTreeNodeFactory().createGroupNode( aTemplate.Component, node::Attributes() ); } else { OSL_ENSURE(m_pTemplatesTree->getName().equals(aTemplate.Component), "Template Component names do not match"); } return m_pTemplatesTree->addChild( base_ptr(_aNode) )->asISubtree(); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- } // namespace backend // ------------------------------------------------------------------------- } // namespace configmgr <commit_msg>INTEGRATION: CWS cfg02 (1.4.8); FILE MERGED 2003/05/21 13:02:14 jb 1.4.8.2: #108160# Rework design after review 2003/05/12 12:43:53 ssmith 1.4.8.1: #108160# added support for binary cache<commit_after>/************************************************************************* * * $RCSfile: mergedcomponentdata.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2003-05-26 08:05:31 $ * * 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: 2002 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "mergedcomponentdata.hxx" #ifndef CONFIGMGR_TREE_NODEFACTORY_HXX #include "treenodefactory.hxx" #endif namespace configmgr { // ----------------------------------------------------------------------------- namespace backend { // ----------------------------------------------------------------------------- MergedComponentData::MergedComponentData( ) : m_pSchemaTree() , m_pTemplatesTree() { } // ----------------------------------------------------------------------------- MergedComponentData::~MergedComponentData( ) { } // ----------------------------------------------------------------------------- void MergedComponentData::clear( ) { m_pTemplatesTree.reset(); m_pSchemaTree.reset(); } // ----------------------------------------------------------------------------- bool MergedComponentData::hasSchema()const { return m_pSchemaTree.get() != NULL; } // ----------------------------------------------------------------------------- bool MergedComponentData::hasTemplates() const { return m_pTemplatesTree.get() != NULL; } // ----------------------------------------------------------------------------- OUString MergedComponentData::getTemplateAccessor (TemplateIdentifier const & _aTemplateName) const { return _aTemplateName.Name; } // ----------------------------------------------------------------------------- bool MergedComponentData::hasTemplate(OUString const & _aTemplateName) const { return m_pTemplatesTree.get() != NULL && m_pTemplatesTree->getChild( _aTemplateName ) != NULL; } // ----------------------------------------------------------------------------- std::auto_ptr<ISubtree> MergedComponentData::extractSchemaTree() { return m_pSchemaTree; } // ----------------------------------------------------------------------------- std::auto_ptr<ISubtree> MergedComponentData::extractTemplatesTree() { return m_pTemplatesTree; } // ----------------------------------------------------------------------------- std::auto_ptr<INode> MergedComponentData::extractTemplateNode(OUString const & _aTemplateName) { if (m_pTemplatesTree.get() == NULL) return std::auto_ptr<INode>(); return m_pTemplatesTree->removeChild(_aTemplateName); } // ----------------------------------------------------------------------------- ISubtree const * MergedComponentData::findTemplate(OUString const & _aTemplateName) const { INode const * pTemplateNode = m_pTemplatesTree->getChild(_aTemplateName); ISubtree const * pTemplateTree = pTemplateNode ? pTemplateNode->asISubtree() : NULL; OSL_ENSURE(pTemplateTree || !pTemplateNode, "ERROR: Template is not a subtree"); return pTemplateTree; } // ----------------------------------------------------------------------------- std::auto_ptr<INode> MergedComponentData::instantiateTemplate(OUString const & _aName, OUString const & _aTemplateName) const { if (INode const * pTemplateNode = m_pTemplatesTree->getChild(_aTemplateName)) { std::auto_ptr<INode> aResult = pTemplateNode->clone(); aResult->setName(_aName); return aResult; } else { return std::auto_ptr<INode>(); } } // ----------------------------------------------------------------------------- ISubtree * MergedComponentData::setSchemaRoot(std::auto_ptr<ISubtree> _aSchemaRoot) { OSL_PRECOND(_aSchemaRoot.get(),"ERROR: Setting a NULL schema root."); OSL_PRECOND(!hasSchema(),"ERROR: Schema root already set"); m_pSchemaTree = _aSchemaRoot; return m_pSchemaTree.get(); } // ----------------------------------------------------------------------------- void MergedComponentData::setTemplatesTree(std::auto_ptr<ISubtree> _aTemplateTree) { OSL_PRECOND(!hasTemplates(),"ERROR: Template Tree already set"); m_pTemplatesTree = _aTemplateTree; } // ----------------------------------------------------------------------------- ISubtree * MergedComponentData::addTemplate(std::auto_ptr<ISubtree> _aNode, TemplateIdentifier const & aTemplate) { OSL_PRECOND(_aNode.get(), "ERROR: Adding a NULL template"); if (!m_pTemplatesTree.get()) { m_pTemplatesTree = getDefaultTreeNodeFactory().createGroupNode( aTemplate.Component, node::Attributes() ); } else { OSL_ENSURE(m_pTemplatesTree->getName().equals(aTemplate.Component), "Template Component names do not match"); } return m_pTemplatesTree->addChild( base_ptr(_aNode) )->asISubtree(); } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- } // namespace backend // ------------------------------------------------------------------------- } // namespace configmgr <|endoftext|>
<commit_before>#ifndef TOPAZ_ALGO_STATIC_HPP #define TOPAZ_ALGO_STATIC_HPP #include <cstddef> #include <tuple> namespace tz::algo { template<std::size_t Begin, std::size_t End, typename Functor> constexpr void static_for(const Functor& function) { if constexpr(Begin < End) { function(std::integral_constant<std::size_t, Begin>{}); static_for<Begin + 1, End>(function); } } template<typename Needle, typename... Haystack> constexpr bool static_find() { bool b = false; static_for<0, sizeof...(Haystack)>([&b]([[maybe_unused]] auto i) constexpr { if constexpr(std::is_same<std::decay_t<decltype(std::get<i.value>(std::declval<std::tuple<Haystack...>>()))>, Needle>::value) { b = true; } }); return b; } template<class T> constexpr bool moveable() { return std::is_move_constructible_v<T> && std::is_move_assignable_v<T>; } template<class T> constexpr bool copyable() { return std::is_copy_constructible_v<T> && std::is_copy_assignable_v<T>; } } #endif // TOPAZ_ALGO_STATIC_HPP<commit_msg>* Documentation pass for tz::algo static utility<commit_after>#ifndef TOPAZ_ALGO_STATIC_HPP #define TOPAZ_ALGO_STATIC_HPP #include <cstddef> #include <tuple> namespace tz::algo { /** * \addtogroup tz_algo Topaz Algorithms Library (tz::algo) * Contains common algorithms used in Topaz modules that aren't available in the C++ standard library. * @{ */ /** * Invoke the given functor with a single std::size_t parameter End - Begin times, incrementing the parameter each time. * This should be used to iterate at compile-time. * @tparam Begin Value at first iteration. * @tparam End Value at last iteration. * @tparam Functor Functor type to invoke. Must be of the signature X(std::size_t) where X is any type. This is recommended to be void as the return value will always be discarded. * @param function Specific function to invoke. It's signature must match the tparam Functor. */ template<std::size_t Begin, std::size_t End, typename Functor> constexpr void static_for(const Functor& function) { if constexpr(Begin < End) { function(std::integral_constant<std::size_t, Begin>{}); static_for<Begin + 1, End>(function); } } /** * Check if a Needle is found in a Haystack at compile-time. * @tparam Needle Needle type to check exists within Haystack... * @tparam Haystack Parameter pack which may or may not contain the type Needle. * @return True if the template parameter pack 'Haystack' contains a type such that std::is_same<Needle, Type> is true. Otherwise, returns false. */ template<typename Needle, typename... Haystack> constexpr bool static_find() { bool b = false; static_for<0, sizeof...(Haystack)>([&b]([[maybe_unused]] auto i) constexpr { if constexpr(std::is_same<std::decay_t<decltype(std::get<i.value>(std::declval<std::tuple<Haystack...>>()))>, Needle>::value) { b = true; } }); return b; } /** * Query as to whether the given type is move-constructible and move-assignable. * @tparam T Type to query. * @return True if T is move-constructible and move-assignable. */ template<class T> constexpr bool moveable() { return std::is_move_constructible_v<T> && std::is_move_assignable_v<T>; } /** * Query as to whether the given type is copy-constructible and copt-assignable. * @tparam T Type to query. * @return True if T is copy-constructible and copy-assignable. */ template<class T> constexpr bool copyable() { return std::is_copy_constructible_v<T> && std::is_copy_assignable_v<T>; } /** * @} */ } #endif // TOPAZ_ALGO_STATIC_HPP<|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <af/array.h> #include <af/defines.h> #include <af/arith.h> #include <af/data.h> #include <ArrayInfo.hpp> #include <optypes.hpp> #include <implicit.hpp> #include <err_common.hpp> #include <handle.hpp> #include <backend.hpp> #include <unary.hpp> #include <implicit.hpp> #include <complex.hpp> #include <cast.hpp> #include <arith.hpp> using namespace detail; template<typename T, af_op_t op> static inline af_array unaryOp(const af_array in) { af_array res = getHandle(unaryOp<T, op>(castArray<T>(in))); return res; } template<af_op_t op> static af_err af_unary(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); ARG_ASSERT(1, in_info.isReal()); af_dtype in_type = in_info.getType(); af_array res; // Convert all inputs to floats / doubles af_dtype type = implicit(in_type, f32); switch (type) { case f32 : res = unaryOp<float , op>(in); break; case f64 : res = unaryOp<double , op>(in); break; default: TYPE_ERROR(1, in_type); break; } std::swap(*out, res); } CATCHALL; return AF_SUCCESS; } #define UNARY(fn) \ af_err af_##fn(af_array *out, const af_array in) \ { \ return af_unary<af_##fn##_t>(out, in); \ } UNARY(sin) UNARY(cos) UNARY(tan) UNARY(asin) UNARY(acos) UNARY(atan) UNARY(sinh) UNARY(cosh) UNARY(tanh) UNARY(asinh) UNARY(acosh) UNARY(atanh) UNARY(trunc) UNARY(sign) UNARY(round) UNARY(floor) UNARY(ceil) UNARY(sigmoid) UNARY(expm1) UNARY(erf) UNARY(erfc) UNARY(log) UNARY(log10) UNARY(log1p) UNARY(log2) UNARY(sqrt) UNARY(cbrt) UNARY(tgamma) UNARY(lgamma) template<typename Tc, typename Tr> af_array expCplx(const af_array a) { Array<Tc> In = getArray<Tc>(a); Array<Tr> Real = real<Tr, Tc>(In); Array<Tr> Imag = imag<Tr, Tc>(In); Array<Tr> ExpReal = unaryOp<Tr, af_exp_t>(Real); Array<Tr> CosImag = unaryOp<Tr, af_cos_t>(Imag); Array<Tr> SinImag = unaryOp<Tr, af_sin_t>(Imag); Array<Tc> Unit = cplx<Tc, Tr>(CosImag, SinImag, CosImag.dims()); Array<Tc> Scale = cast<Tc, Tr>(ExpReal); Array<Tc> Result = arithOp<Tc, af_mul_t>(Scale, Unit, Scale.dims()); return getHandle(Result); } af_err af_exp(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); af_dtype in_type = in_info.getType(); af_array res; // Convert all inputs to floats / doubles af_dtype type = implicit(in_type, f32); switch (type) { case f32 : res = unaryOp<float , af_exp_t>(in); break; case f64 : res = unaryOp<double , af_exp_t>(in); break; case c32 : res = expCplx<cfloat , float >(in); break; case c64 : res = expCplx<cdouble, double>(in); break; default: TYPE_ERROR(1, in_type); break; } std::swap(*out, res); } CATCHALL; return AF_SUCCESS; } af_err af_not(af_array *out, const af_array in) { try { af_array tmp; ArrayInfo in_info = getInfo(in); AF_CHECK(af_constant(&tmp, 0, in_info.ndims(), in_info.dims().get(), in_info.getType())); AF_CHECK(af_eq(out, in, tmp, false)); AF_CHECK(af_release_array(tmp)); } CATCHALL; return AF_SUCCESS; } af_err af_arg(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); if (!in_info.isComplex()) { return af_constant(out, 0, in_info.ndims(), in_info.dims().get(), in_info.getType()); } af_array real; af_array imag; AF_CHECK(af_real(&real, in)); AF_CHECK(af_imag(&imag, in)); AF_CHECK(af_atan2(out, imag, real, false)); AF_CHECK(af_release_array(real)); AF_CHECK(af_release_array(imag)); } CATCHALL; return AF_SUCCESS; } af_err af_pow2(af_array *out, const af_array in) { try { af_array two; ArrayInfo in_info = getInfo(in); AF_CHECK(af_constant(&two, 2, in_info.ndims(), in_info.dims().get(), in_info.getType())); AF_CHECK(af_pow(out, two, in, false)); AF_CHECK(af_release_array(two)); } CATCHALL; return AF_SUCCESS; } af_err af_factorial(af_array *out, const af_array in) { try { af_array one; ArrayInfo in_info = getInfo(in); AF_CHECK(af_constant(&one, 1, in_info.ndims(), in_info.dims().get(), in_info.getType())); af_array inp1; AF_CHECK(af_add(&inp1, one, in, false)); AF_CHECK(af_tgamma(out, inp1)); AF_CHECK(af_release_array(one)); AF_CHECK(af_release_array(inp1)); } CATCHALL; return AF_SUCCESS; } template<typename T, af_op_t op> static inline af_array checkOp(const af_array in) { af_array res = getHandle(checkOp<T, op>(castArray<T>(in))); return res; } template<af_op_t op> static af_err af_check(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); ARG_ASSERT(1, in_info.isReal()); af_dtype in_type = in_info.getType(); af_array res; // Convert all inputs to floats / doubles af_dtype type = implicit(in_type, f32); switch (type) { case f32 : res = checkOp<float , op>(in); break; case f64 : res = checkOp<double , op>(in); break; default: TYPE_ERROR(1, in_type); break; } std::swap(*out, res); } CATCHALL; return AF_SUCCESS; } #define CHECK(fn) \ af_err af_##fn(af_array *out, const af_array in) \ { \ return af_check<af_##fn##_t>(out, in); \ } CHECK(isinf) CHECK(isnan) CHECK(iszero) <commit_msg>Add support for c32/c64 for isInf, isNaN, iszero<commit_after>/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <af/array.h> #include <af/defines.h> #include <af/arith.h> #include <af/data.h> #include <ArrayInfo.hpp> #include <optypes.hpp> #include <implicit.hpp> #include <err_common.hpp> #include <handle.hpp> #include <backend.hpp> #include <unary.hpp> #include <implicit.hpp> #include <complex.hpp> #include <logic.hpp> #include <cast.hpp> #include <arith.hpp> using namespace detail; template<typename T, af_op_t op> static inline af_array unaryOp(const af_array in) { af_array res = getHandle(unaryOp<T, op>(castArray<T>(in))); return res; } template<af_op_t op> static af_err af_unary(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); ARG_ASSERT(1, in_info.isReal()); af_dtype in_type = in_info.getType(); af_array res; // Convert all inputs to floats / doubles af_dtype type = implicit(in_type, f32); switch (type) { case f32 : res = unaryOp<float , op>(in); break; case f64 : res = unaryOp<double , op>(in); break; default: TYPE_ERROR(1, in_type); break; } std::swap(*out, res); } CATCHALL; return AF_SUCCESS; } #define UNARY(fn) \ af_err af_##fn(af_array *out, const af_array in) \ { \ return af_unary<af_##fn##_t>(out, in); \ } UNARY(sin) UNARY(cos) UNARY(tan) UNARY(asin) UNARY(acos) UNARY(atan) UNARY(sinh) UNARY(cosh) UNARY(tanh) UNARY(asinh) UNARY(acosh) UNARY(atanh) UNARY(trunc) UNARY(sign) UNARY(round) UNARY(floor) UNARY(ceil) UNARY(sigmoid) UNARY(expm1) UNARY(erf) UNARY(erfc) UNARY(log) UNARY(log10) UNARY(log1p) UNARY(log2) UNARY(sqrt) UNARY(cbrt) UNARY(tgamma) UNARY(lgamma) template<typename Tc, typename Tr> af_array expCplx(const af_array a) { Array<Tc> In = getArray<Tc>(a); Array<Tr> Real = real<Tr, Tc>(In); Array<Tr> Imag = imag<Tr, Tc>(In); Array<Tr> ExpReal = unaryOp<Tr, af_exp_t>(Real); Array<Tr> CosImag = unaryOp<Tr, af_cos_t>(Imag); Array<Tr> SinImag = unaryOp<Tr, af_sin_t>(Imag); Array<Tc> Unit = cplx<Tc, Tr>(CosImag, SinImag, CosImag.dims()); Array<Tc> Scale = cast<Tc, Tr>(ExpReal); Array<Tc> Result = arithOp<Tc, af_mul_t>(Scale, Unit, Scale.dims()); return getHandle(Result); } af_err af_exp(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); af_dtype in_type = in_info.getType(); af_array res; // Convert all inputs to floats / doubles af_dtype type = implicit(in_type, f32); switch (type) { case f32 : res = unaryOp<float , af_exp_t>(in); break; case f64 : res = unaryOp<double , af_exp_t>(in); break; case c32 : res = expCplx<cfloat , float >(in); break; case c64 : res = expCplx<cdouble, double>(in); break; default: TYPE_ERROR(1, in_type); break; } std::swap(*out, res); } CATCHALL; return AF_SUCCESS; } af_err af_not(af_array *out, const af_array in) { try { af_array tmp; ArrayInfo in_info = getInfo(in); AF_CHECK(af_constant(&tmp, 0, in_info.ndims(), in_info.dims().get(), in_info.getType())); AF_CHECK(af_eq(out, in, tmp, false)); AF_CHECK(af_release_array(tmp)); } CATCHALL; return AF_SUCCESS; } af_err af_arg(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); if (!in_info.isComplex()) { return af_constant(out, 0, in_info.ndims(), in_info.dims().get(), in_info.getType()); } af_array real; af_array imag; AF_CHECK(af_real(&real, in)); AF_CHECK(af_imag(&imag, in)); AF_CHECK(af_atan2(out, imag, real, false)); AF_CHECK(af_release_array(real)); AF_CHECK(af_release_array(imag)); } CATCHALL; return AF_SUCCESS; } af_err af_pow2(af_array *out, const af_array in) { try { af_array two; ArrayInfo in_info = getInfo(in); AF_CHECK(af_constant(&two, 2, in_info.ndims(), in_info.dims().get(), in_info.getType())); AF_CHECK(af_pow(out, two, in, false)); AF_CHECK(af_release_array(two)); } CATCHALL; return AF_SUCCESS; } af_err af_factorial(af_array *out, const af_array in) { try { af_array one; ArrayInfo in_info = getInfo(in); AF_CHECK(af_constant(&one, 1, in_info.ndims(), in_info.dims().get(), in_info.getType())); af_array inp1; AF_CHECK(af_add(&inp1, one, in, false)); AF_CHECK(af_tgamma(out, inp1)); AF_CHECK(af_release_array(one)); AF_CHECK(af_release_array(inp1)); } CATCHALL; return AF_SUCCESS; } template<typename T, af_op_t op> static inline af_array checkOp(const af_array in) { af_array res = getHandle(checkOp<T, op>(castArray<T>(in))); return res; } template<af_op_t op> struct cplxLogicOp { af_array operator()(Array<char> resR, Array<char> resI, dim4 dims) { return getHandle(logicOp<char, af_or_t>(resR, resI, dims)); } }; template <> struct cplxLogicOp<af_iszero_t> { af_array operator()(Array<char> resR, Array<char> resI, dim4 dims) { return getHandle(logicOp<char, af_and_t>(resR, resI, dims)); } }; template<typename T, typename BT, af_op_t op> static inline af_array checkOpCplx(const af_array in) { Array<BT> R = real<BT, T>(getArray<T>(in)); Array<BT> I = imag<BT, T>(getArray<T>(in)); Array<char> resR = checkOp<BT, op>(R); Array<char> resI = checkOp<BT, op>(I); ArrayInfo in_info = getInfo(in); dim4 dims = in_info.dims(); cplxLogicOp<op> cplxLogic; af_array res = cplxLogic(resR, resI, dims); return res; } template<af_op_t op> static af_err af_check(af_array *out, const af_array in) { try { ArrayInfo in_info = getInfo(in); af_dtype in_type = in_info.getType(); af_array res; // Convert all inputs to floats / doubles / complex af_dtype type = implicit(in_type, f32); switch (type) { case f32 : res = checkOp<float , op>(in); break; case f64 : res = checkOp<double , op>(in); break; case c32 : res = checkOpCplx<cfloat , float , op>(in); break; case c64 : res = checkOpCplx<cdouble, double, op>(in); break; default: TYPE_ERROR(1, in_type); break; } std::swap(*out, res); } CATCHALL; return AF_SUCCESS; } #define CHECK(fn) \ af_err af_##fn(af_array *out, const af_array in) \ { \ return af_check<af_##fn##_t>(out, in); \ } CHECK(isinf) CHECK(isnan) CHECK(iszero) <|endoftext|>
<commit_before>#include "factory.h" #include "opencv_video_source.h" #include "opencv_video_target.h" #ifdef USE_FFMPEG #include "ffmpeg_video_target.h" #endif namespace gg { IVideoSource * Factory::_sources[2] = { NULL, NULL }; IVideoSource * Factory::connect(enum Device type) { int device_id = -1; // default value makes no sense switch (type) { case DVI2PCIeDuo_DVI: device_id = 0; // always /dev/video0 break; case DVI2PCIeDuo_SDI: device_id = 1; // always /dev/video1 break; default: std::string msg; msg.append("Device ") .append(std::to_string(type)) .append(" not recognised"); throw DeviceNotFound(msg); } if (_sources[(int) type] == NULL) { IVideoSource * src = new VideoSourceOpenCV(device_id); // check querying frame dimensions int width = -1, height = -1; if (not src->get_frame_dimensions(width, height)) { std::string error; error.append("Device ") .append(std::to_string(device_id)) .append(" connected, but ") .append(" does not return frame dimensions."); throw DeviceOffline(error); } // check meaningful frame dimensions if (width <= 0 or height <= 0) { std::string error; error.append("Device ") .append(std::to_string(device_id)) .append(" connected, but ") .append(" returns meaningless frame dimensions."); throw DeviceOffline(error); } // check querying frames VideoFrame_BGRA frame; if (not src->get_frame(frame)) { std::string error; error.append("Device ") .append(std::to_string(device_id)) .append(" connected, but ") .append(" does not return frames."); throw DeviceOffline(error); } // if no exception raised up to here, glory be to GiftGrab _sources[(int) type] = src; } return _sources[(int) type]; } void Factory::disconnect(enum Device type) { switch (type) { case DVI2PCIeDuo_DVI: case DVI2PCIeDuo_SDI: break; // everything up to here is recognised default: std::string msg; msg.append("Device ") .append(std::to_string(type)) .append(" not recognised"); throw DeviceNotFound(msg); } if (_sources[(int) type]) { delete _sources[(int) type]; _sources[(int) type] = NULL; } } IVideoTarget * Factory::writer(Storage type) { switch (type) { case File_XviD: return new VideoTargetOpenCV("XVID"); case File_H265: #ifdef USE_FFMPEG return new VideoTargetFFmpeg("H265"); #else // nop, see default below #endif default: std::string msg; msg.append("Video target type ") .append(std::to_string(type)) .append(" not recognised"); throw VideoTargetError(msg); } } } <commit_msg>Issue #31: factory returns new video source type if using I420<commit_after>#include "factory.h" #include "opencv_video_source.h" #include "opencv_video_target.h" #ifdef USE_FFMPEG #include "ffmpeg_video_target.h" #endif #ifdef USE_COLOUR_SPACE_I420 #include "epiphansdk_video_source.h" #endif namespace gg { IVideoSource * Factory::_sources[2] = { NULL, NULL }; IVideoSource * Factory::connect(enum Device type) { #ifdef USE_COLOUR_SPACE_I420 std::string device_id = ""; #else int device_id = -1; // default value makes no sense #endif switch (type) { case DVI2PCIeDuo_DVI: #ifdef USE_COLOUR_SPACE_I420 device_id = EpiphanSDK_DVI; #else device_id = 0; // always /dev/video0 #endif break; case DVI2PCIeDuo_SDI: #ifdef USE_COLOUR_SPACE_I420 device_id = EpiphanSDK_SDI; #else device_id = 1; // always /dev/video1 #endif break; default: std::string msg; msg.append("Device ") .append(std::to_string(type)) .append(" not recognised"); throw DeviceNotFound(msg); } if (_sources[(int) type] == NULL) { #ifdef USE_COLOUR_SPACE_I420 IVideoSource * src = nullptr; try { src = new VideoSourceEpiphanSDK(device_id, V2U_GRABFRAME_FORMAT_I420); } catch (VideoSourceError & e) { throw DeviceNotFound(e.what()); } #else IVideoSource * src = new VideoSourceOpenCV(device_id); #endif // check querying frame dimensions int width = -1, height = -1; if (not src->get_frame_dimensions(width, height)) { std::string error; error.append("Device ") #ifdef USE_COLOUR_SPACE_I420 .append(device_id) #else .append(std::to_string(device_id)) #endif .append(" connected, but ") .append(" does not return frame dimensions."); throw DeviceOffline(error); } // check meaningful frame dimensions if (width <= 0 or height <= 0) { std::string error; error.append("Device ") #ifdef USE_COLOUR_SPACE_I420 .append(device_id) #else .append(std::to_string(device_id)) #endif .append(" connected, but ") .append(" returns meaningless frame dimensions."); throw DeviceOffline(error); } // check querying frames #ifdef USE_COLOUR_SPACE_I420 VideoFrame_I420 frame; #else VideoFrame_BGRA frame; #endif if (not src->get_frame(frame)) { std::string error; error.append("Device ") #ifdef USE_COLOUR_SPACE_I420 .append(device_id) #else .append(std::to_string(device_id)) #endif .append(" connected, but ") .append(" does not return frames."); throw DeviceOffline(error); } // if no exception raised up to here, glory be to GiftGrab _sources[(int) type] = src; } return _sources[(int) type]; } void Factory::disconnect(enum Device type) { switch (type) { case DVI2PCIeDuo_DVI: case DVI2PCIeDuo_SDI: break; // everything up to here is recognised default: std::string msg; msg.append("Device ") .append(std::to_string(type)) .append(" not recognised"); throw DeviceNotFound(msg); } if (_sources[(int) type]) { delete _sources[(int) type]; _sources[(int) type] = NULL; } } IVideoTarget * Factory::writer(Storage type) { switch (type) { case File_XviD: return new VideoTargetOpenCV("XVID"); case File_H265: #ifdef USE_FFMPEG return new VideoTargetFFmpeg("H265"); #else // nop, see default below #endif default: std::string msg; msg.append("Video target type ") .append(std::to_string(type)) .append(" not recognised"); throw VideoTargetError(msg); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TColumnsHelper.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 04:58:27 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONNECTIVITY_COLUMNSHELPER_HXX #define CONNECTIVITY_COLUMNSHELPER_HXX #ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_ #include "connectivity/sdbcx/VCollection.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_ #include <com/sun/star/sdbc/XDatabaseMetaData.hpp> #endif #ifndef _CONNECTIVITY_SDBCX_IREFRESHABLE_HXX_ #include "connectivity/sdbcx/IRefreshable.hxx" #endif namespace connectivity { class OTableHelper; class OColumnsHelperImpl; /** contains generell column handling to creat default columns and default sql statements. */ class OColumnsHelper : public sdbcx::OCollection { OColumnsHelperImpl* m_pImpl; protected: OTableHelper* m_pTable; virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName); virtual void impl_refresh() throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > createEmptyObject(); virtual sdbcx::ObjectType cloneObject(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _xDescriptor); virtual void appendObject( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor ); virtual void dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName); public: OColumnsHelper( ::cppu::OWeakObject& _rParent ,sal_Bool _bCase ,::osl::Mutex& _rMutex ,const TStringVector &_rVector ,sal_Bool _bUseHardRef = sal_True ); virtual ~OColumnsHelper(); /** set the parent of the columns. Can also be <NULL/>. @param _pTable The parent. */ inline void setParent(OTableHelper* _pTable) { m_pTable = _pTable;} }; } #endif // CONNECTIVITY_COLUMNSHELPER_HXX <commit_msg>INTEGRATION: CWS qiq (1.5.104); FILE MERGED 2006/06/16 11:32:27 fs 1.5.104.1: during #i51143#:<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: TColumnsHelper.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-07-10 14:15:14 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONNECTIVITY_COLUMNSHELPER_HXX #define CONNECTIVITY_COLUMNSHELPER_HXX #ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_ #include "connectivity/sdbcx/VCollection.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_ #include <com/sun/star/sdbc/XDatabaseMetaData.hpp> #endif #ifndef _CONNECTIVITY_SDBCX_IREFRESHABLE_HXX_ #include "connectivity/sdbcx/IRefreshable.hxx" #endif namespace connectivity { class OTableHelper; class OColumnsHelperImpl; /** contains generell column handling to creat default columns and default sql statements. */ class OColumnsHelper : public sdbcx::OCollection { OColumnsHelperImpl* m_pImpl; protected: OTableHelper* m_pTable; virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName); virtual void impl_refresh() throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > createDescriptor(); virtual sdbcx::ObjectType appendObject( const ::rtl::OUString& _rForName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor ); virtual void dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName); public: OColumnsHelper( ::cppu::OWeakObject& _rParent ,sal_Bool _bCase ,::osl::Mutex& _rMutex ,const TStringVector &_rVector ,sal_Bool _bUseHardRef = sal_True ); virtual ~OColumnsHelper(); /** set the parent of the columns. Can also be <NULL/>. @param _pTable The parent. */ inline void setParent(OTableHelper* _pTable) { m_pTable = _pTable;} }; } #endif // CONNECTIVITY_COLUMNSHELPER_HXX <|endoftext|>
<commit_before>/* Copyright (C) 2000-2001 Dawit Alemayehu <adawit@kde.org> Copyright (C) 2006 Alexey Proskuryakov <ap@webkit.org> Copyright (C) 2007, 2008 Apple Inc. All rights reserved. Copyright (C) 2010 Patrick Gansterer <paroga@paroga.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. This code is based on the java implementation in HTTPClient package by Ronald Tschalär Copyright (C) 1996-1999. */ #include "config.h" #include "Base64.h" #include <limits.h> #include "wtf/StringExtras.h" #include "wtf/text/WTFString.h" namespace WTF { static const char base64EncMap[64] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2B, 0x2F }; static const char base64DecMap[128] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x3F, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00 }; String base64Encode(const char* data, unsigned length, Base64EncodePolicy policy) { Vector<char> result; base64Encode(data, length, result, policy); return String(result.data(), result.size()); } void base64Encode(const char* data, unsigned len, Vector<char>& out, Base64EncodePolicy policy) { out.clear(); if (!len) return; // If the input string is pathologically large, just return nothing. // Note: Keep this in sync with the "outLength" computation below. // Rather than being perfectly precise, this is a bit conservative. const unsigned maxInputBufferSize = UINT_MAX / 77 * 76 / 4 * 3 - 2; if (len > maxInputBufferSize) return; unsigned sidx = 0; unsigned didx = 0; unsigned outLength = ((len + 2) / 3) * 4; // Deal with the 76 character per line limit specified in RFC 2045. bool insertLFs = (policy == Base64InsertLFs && outLength > 76); if (insertLFs) outLength += ((outLength - 1) / 76); int count = 0; out.grow(outLength); // 3-byte to 4-byte conversion + 0-63 to ascii printable conversion if (len > 1) { while (sidx < len - 2) { if (insertLFs) { if (count && !(count % 76)) out[didx++] = '\n'; count += 4; } out[didx++] = base64EncMap[(data[sidx] >> 2) & 077]; out[didx++] = base64EncMap[((data[sidx + 1] >> 4) & 017) | ((data[sidx] << 4) & 077)]; out[didx++] = base64EncMap[((data[sidx + 2] >> 6) & 003) | ((data[sidx + 1] << 2) & 077)]; out[didx++] = base64EncMap[data[sidx + 2] & 077]; sidx += 3; } } if (sidx < len) { if (insertLFs && (count > 0) && !(count % 76)) out[didx++] = '\n'; out[didx++] = base64EncMap[(data[sidx] >> 2) & 077]; if (sidx < len - 1) { out[didx++] = base64EncMap[((data[sidx + 1] >> 4) & 017) | ((data[sidx] << 4) & 077)]; out[didx++] = base64EncMap[(data[sidx + 1] << 2) & 077]; } else out[didx++] = base64EncMap[(data[sidx] << 4) & 077]; } // Add padding while (didx < out.size()) { out[didx] = '='; ++didx; } } bool base64Decode(const Vector<char>& in, Vector<char>& out, Base64DecodePolicy policy) { out.clear(); // If the input string is pathologically large, just return nothing. if (in.size() > UINT_MAX) return false; return base64Decode(in.data(), in.size(), out, policy); } template<typename T> static inline bool base64DecodeInternal(const T* data, unsigned len, Vector<char>& out, Base64DecodePolicy policy) { out.clear(); if (!len) return true; out.grow(len); bool sawEqualsSign = false; unsigned outLength = 0; for (unsigned idx = 0; idx < len; ++idx) { unsigned ch = data[idx]; if (ch == '=') sawEqualsSign = true; else if (('0' <= ch && ch <= '9') || ('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z') || ch == '+' || ch == '/') { if (sawEqualsSign) return false; out[outLength] = base64DecMap[ch]; ++outLength; } else if (policy == Base64FailOnInvalidCharacter || (policy == Base64IgnoreWhitespace && !isSpaceOrNewline(ch))) return false; } if (!outLength) return !sawEqualsSign; // Valid data is (n * 4 + [0,2,3]) characters long. if ((outLength % 4) == 1) return false; // 4-byte to 3-byte conversion outLength -= (outLength + 3) / 4; if (!outLength) return false; unsigned sidx = 0; unsigned didx = 0; if (outLength > 1) { while (didx < outLength - 2) { out[didx] = (((out[sidx] << 2) & 255) | ((out[sidx + 1] >> 4) & 003)); out[didx + 1] = (((out[sidx + 1] << 4) & 255) | ((out[sidx + 2] >> 2) & 017)); out[didx + 2] = (((out[sidx + 2] << 6) & 255) | (out[sidx + 3] & 077)); sidx += 4; didx += 3; } } if (didx < outLength) out[didx] = (((out[sidx] << 2) & 255) | ((out[sidx + 1] >> 4) & 003)); if (++didx < outLength) out[didx] = (((out[sidx + 1] << 4) & 255) | ((out[sidx + 2] >> 2) & 017)); if (outLength < out.size()) out.shrink(outLength); return true; } bool base64Decode(const char* data, unsigned len, Vector<char>& out, Base64DecodePolicy policy) { return base64DecodeInternal<char>(data, len, out, policy); } bool base64Decode(const String& in, Vector<char>& out, Base64DecodePolicy policy) { return base64DecodeInternal<UChar>(in.bloatedCharacters(), in.length(), out, policy); } } // namespace WTF <commit_msg>base64Decode shouldn't use bloatedCharacters()<commit_after>/* Copyright (C) 2000-2001 Dawit Alemayehu <adawit@kde.org> Copyright (C) 2006 Alexey Proskuryakov <ap@webkit.org> Copyright (C) 2007, 2008 Apple Inc. All rights reserved. Copyright (C) 2010 Patrick Gansterer <paroga@paroga.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License (LGPL) version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU Library General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. This code is based on the java implementation in HTTPClient package by Ronald Tschalär Copyright (C) 1996-1999. */ #include "config.h" #include "Base64.h" #include <limits.h> #include "wtf/StringExtras.h" #include "wtf/text/WTFString.h" namespace WTF { static const char base64EncMap[64] = { 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x2B, 0x2F }; static const char base64DecMap[128] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x00, 0x00, 0x00, 0x3F, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00 }; String base64Encode(const char* data, unsigned length, Base64EncodePolicy policy) { Vector<char> result; base64Encode(data, length, result, policy); return String(result.data(), result.size()); } void base64Encode(const char* data, unsigned len, Vector<char>& out, Base64EncodePolicy policy) { out.clear(); if (!len) return; // If the input string is pathologically large, just return nothing. // Note: Keep this in sync with the "outLength" computation below. // Rather than being perfectly precise, this is a bit conservative. const unsigned maxInputBufferSize = UINT_MAX / 77 * 76 / 4 * 3 - 2; if (len > maxInputBufferSize) return; unsigned sidx = 0; unsigned didx = 0; unsigned outLength = ((len + 2) / 3) * 4; // Deal with the 76 character per line limit specified in RFC 2045. bool insertLFs = (policy == Base64InsertLFs && outLength > 76); if (insertLFs) outLength += ((outLength - 1) / 76); int count = 0; out.grow(outLength); // 3-byte to 4-byte conversion + 0-63 to ascii printable conversion if (len > 1) { while (sidx < len - 2) { if (insertLFs) { if (count && !(count % 76)) out[didx++] = '\n'; count += 4; } out[didx++] = base64EncMap[(data[sidx] >> 2) & 077]; out[didx++] = base64EncMap[((data[sidx + 1] >> 4) & 017) | ((data[sidx] << 4) & 077)]; out[didx++] = base64EncMap[((data[sidx + 2] >> 6) & 003) | ((data[sidx + 1] << 2) & 077)]; out[didx++] = base64EncMap[data[sidx + 2] & 077]; sidx += 3; } } if (sidx < len) { if (insertLFs && (count > 0) && !(count % 76)) out[didx++] = '\n'; out[didx++] = base64EncMap[(data[sidx] >> 2) & 077]; if (sidx < len - 1) { out[didx++] = base64EncMap[((data[sidx + 1] >> 4) & 017) | ((data[sidx] << 4) & 077)]; out[didx++] = base64EncMap[(data[sidx + 1] << 2) & 077]; } else out[didx++] = base64EncMap[(data[sidx] << 4) & 077]; } // Add padding while (didx < out.size()) { out[didx] = '='; ++didx; } } bool base64Decode(const Vector<char>& in, Vector<char>& out, Base64DecodePolicy policy) { out.clear(); // If the input string is pathologically large, just return nothing. if (in.size() > UINT_MAX) return false; return base64Decode(in.data(), in.size(), out, policy); } template<typename T> static inline bool base64DecodeInternal(const T* data, unsigned len, Vector<char>& out, Base64DecodePolicy policy) { out.clear(); if (!len) return true; out.grow(len); bool sawEqualsSign = false; unsigned outLength = 0; for (unsigned idx = 0; idx < len; ++idx) { unsigned ch = data[idx]; if (ch == '=') sawEqualsSign = true; else if (('0' <= ch && ch <= '9') || ('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z') || ch == '+' || ch == '/') { if (sawEqualsSign) return false; out[outLength] = base64DecMap[ch]; ++outLength; } else if (policy == Base64FailOnInvalidCharacter || (policy == Base64IgnoreWhitespace && !isSpaceOrNewline(ch))) return false; } if (!outLength) return !sawEqualsSign; // Valid data is (n * 4 + [0,2,3]) characters long. if ((outLength % 4) == 1) return false; // 4-byte to 3-byte conversion outLength -= (outLength + 3) / 4; if (!outLength) return false; unsigned sidx = 0; unsigned didx = 0; if (outLength > 1) { while (didx < outLength - 2) { out[didx] = (((out[sidx] << 2) & 255) | ((out[sidx + 1] >> 4) & 003)); out[didx + 1] = (((out[sidx + 1] << 4) & 255) | ((out[sidx + 2] >> 2) & 017)); out[didx + 2] = (((out[sidx + 2] << 6) & 255) | (out[sidx + 3] & 077)); sidx += 4; didx += 3; } } if (didx < outLength) out[didx] = (((out[sidx] << 2) & 255) | ((out[sidx + 1] >> 4) & 003)); if (++didx < outLength) out[didx] = (((out[sidx + 1] << 4) & 255) | ((out[sidx + 2] >> 2) & 017)); if (outLength < out.size()) out.shrink(outLength); return true; } bool base64Decode(const char* data, unsigned length, Vector<char>& out, Base64DecodePolicy policy) { return base64DecodeInternal<LChar>(reinterpret_cast<const LChar*>(data), length, out, policy); } bool base64Decode(const String& in, Vector<char>& out, Base64DecodePolicy policy) { if (in.isEmpty()) return base64DecodeInternal<LChar>(0, 0, out, policy); if (in.is8Bit()) return base64DecodeInternal<LChar>(in.characters8(), in.length(), out, policy); return base64DecodeInternal<UChar>(in.characters16(), in.length(), out, policy); } } // namespace WTF <|endoftext|>
<commit_before> #include "app/gibbs/gibbs_sampling.h" #include "app/gibbs/single_node_sampler.h" #include "io/pb_parser.h" #include "common.h" #include <unistd.h> #include <fstream> #include "timer.h" void load_fg(dd::FactorGraph * const _p_fg, const dd::CmdParser & cmd, const int & nodeid){ std::cout << "LOADING FACTOR GRAPH ON NODE " << nodeid << std::endl; numa_run_on_node(nodeid); numa_set_localalloc(); _p_fg->load(cmd); } /*! * \brief In this function, the factor graph is located to each NUMA node. * * TODO: in the near future, this allocation should be abstracted * into a higher-level class to avoid writing similar things * for Gibbs, NN, SGD etc. However, this is the task of next pass * of refactoring. */ void dd::GibbsSampling::prepare(){ n_numa_nodes = numa_max_node(); n_thread_per_numa = (sysconf(_SC_NPROCESSORS_CONF))/(n_numa_nodes+1); std::vector<std::thread> loaders; for(int i=0;i<=n_numa_nodes;i++){ dd::FactorGraph * fg = new dd::FactorGraph; this->factorgraphs.push_back(*fg); loaders.push_back(std::thread(load_fg, fg, *p_cmd_parser, i)); } for(int i=0;i<=n_numa_nodes;i++){ loaders[i].join(); } } void dd::GibbsSampling::inference(const int & n_epoch){ Timer t_total; Timer t; int nvar = this->factorgraphs[0].variables.size(); int nnode = n_numa_nodes + 1; std::vector<SingleNodeSampler> single_node_samplers; for(int i=0;i<=n_numa_nodes;i++){ single_node_samplers.push_back(SingleNodeSampler(&this->factorgraphs[i], n_thread_per_numa, i)); } for(int i=0;i<=n_numa_nodes;i++){ single_node_samplers[i].clear_variabletally(); } for(int i_epoch=0;i_epoch<n_epoch;i_epoch++){ std::cout << std::setprecision(2) << "INFERENCE EPOCH " << i_epoch * nnode << "~" << ((i_epoch+1) * nnode) << "...." << std::flush; t.restart(); for(int i=0;i<nnode;i++){ single_node_samplers[i].sample(); } for(int i=0;i<nnode;i++){ single_node_samplers[i].wait(); } double elapsed = t.elapsed(); std::cout << "" << elapsed << " sec." ; std::cout << "," << (nvar*nnode)/elapsed << " vars/sec" << std::endl; } double elapsed = t_total.elapsed(); std::cout << "TOTAL INFERENCE TIME: " << elapsed << " sec." << std::endl; } void dd::GibbsSampling::learn(const int & n_epoch, const int & n_sample_per_epoch, const double & stepsize, const double & decay){ Timer t_total; double current_stepsize = stepsize; Timer t; int nvar = this->factorgraphs[0].variables.size(); int nnode = n_numa_nodes + 1; int nweight = this->factorgraphs[0].weights.size(); std::vector<SingleNodeSampler> single_node_samplers; for(int i=0;i<=n_numa_nodes;i++){ single_node_samplers.push_back(SingleNodeSampler(&this->factorgraphs[i], n_thread_per_numa, i)); } double * ori_weights = new double[nweight]; for(int i_epoch=0;i_epoch<n_epoch;i_epoch++){ std::cout << std::setprecision(2) << "LEARNING EPOCH " << i_epoch * nnode << "~" << ((i_epoch+1) * nnode) << "...." << std::flush; t.restart(); memcpy(ori_weights, &this->factorgraphs[0].infrs->weight_values, sizeof(double)*nweight); for(int i=0;i<nnode;i++){ single_node_samplers[i].p_fg->stepsize = current_stepsize; } for(int i=0;i<nnode;i++){ single_node_samplers[i].sample_sgd(); } for(int i=0;i<nnode;i++){ single_node_samplers[i].wait_sgd(); } FactorGraph & cfg = this->factorgraphs[0]; for(int i=1;i<=n_numa_nodes;i++){ FactorGraph & cfg_other = this->factorgraphs[i]; for(int j=0;j<nweight;j++){ cfg.infrs->weight_values[j] += cfg_other.infrs->weight_values[j]; } } for(int j=0;j<nweight;j++){ cfg.infrs->weight_values[j] /= nnode; cfg.infrs->weight_values[j] *= (1.0/(1.0+0.01*current_stepsize)); } for(int i=1;i<=n_numa_nodes;i++){ FactorGraph &cfg_other = this->factorgraphs[i]; for(int j=0;j<nweight;j++){ if(cfg.infrs->weights_isfixed[j] == false){ cfg_other.infrs->weight_values[j] = cfg.infrs->weight_values[j]; } } } double lmax = -1000000; double l2=0.0; for(int i=0;i<nweight;i++){ double diff = fabs(ori_weights[i] - cfg.infrs->weight_values[i]); l2 += diff*diff; if(lmax < diff){ lmax = diff; } } lmax = lmax/current_stepsize; double elapsed = t.elapsed(); std::cout << "" << elapsed << " sec."; std::cout << "," << (nvar*nnode)/elapsed << " vars/sec." << ",stepsize=" << current_stepsize << ",lmax=" << lmax << ",l2=" << sqrt(l2)/current_stepsize << std::endl; //std::cout << " " << this->compact_factors[0].fg_mutable->weights[0] << std::endl; current_stepsize = current_stepsize * decay; } double elapsed = t_total.elapsed(); std::cout << "TOTAL LEARNING TIME: " << elapsed << " sec." << std::endl; } void dd::GibbsSampling::dump_weights(){ std::cout << "LEARNING SNIPPETS (QUERY WEIGHTS):" << std::endl; FactorGraph const & cfg = this->factorgraphs[0]; int ct = 0; for(size_t i=0;i<cfg.infrs->nweights;i++){ ct ++; std::cout << " " << i << " " << cfg.infrs->weight_values[i] << std::endl; if(ct % 10 == 0){ break; } } std::cout << " ..." << std::endl; std::string filename_protocol = p_cmd_parser->output_folder->getValue() + "/inference_result.out.weights"; std::string filename_text = p_cmd_parser->output_folder->getValue() + "/inference_result.out.weights.text"; std::cout << "DUMPING... PROTOCOL: " << filename_protocol << std::endl; std::cout << "DUMPING... TEXT : " << filename_text << std::endl; std::ofstream fout_text(filename_text.c_str()); std::ofstream mFs(filename_protocol.c_str(),std::ios::out | std::ios::binary); google::protobuf::io::OstreamOutputStream *_OstreamOutputStream = new google::protobuf::io::OstreamOutputStream(&mFs); google::protobuf::io::CodedOutputStream *_CodedOutputStream = new google::protobuf::io::CodedOutputStream(_OstreamOutputStream); deepdive::WeightInferenceResult msg; for(size_t i=0;i<cfg.infrs->nweights;i++){ fout_text << i << " " << cfg.infrs->weight_values[i] << std::endl; msg.set_id(i); msg.set_value(cfg.infrs->weight_values[i]); _CodedOutputStream->WriteVarint32(msg.ByteSize()); if ( !msg.SerializeToCodedStream(_CodedOutputStream) ){ std::cout << "SerializeToCodedStream error " << std::endl; assert(false); } } delete _CodedOutputStream; delete _OstreamOutputStream; mFs.close(); fout_text.close(); } void dd::GibbsSampling::dump(){ double * agg_means = new double[factorgraphs[0].variables.size()]; double * agg_nsamples = new double[factorgraphs[0].variables.size()]; for(long i=0;i<factorgraphs[0].variables.size();i++){ agg_means[i] = 0; agg_nsamples[i] = 0; } for(int i=0;i<=n_numa_nodes;i++){ const FactorGraph & cfg = factorgraphs[i]; for(auto & variable : cfg.variables){ agg_means[variable.id] += cfg.infrs->agg_means[variable.id]; agg_nsamples[variable.id] += cfg.infrs->agg_nsamples[variable.id]; } } std::cout << "INFERENCE SNIPPETS (QUERY VARIABLES):" << std::endl; int ct = 0; for(const Variable & variable : factorgraphs[0].variables){ if(variable.is_evid == false){ ct ++; std::cout << " " << variable.id << " " << agg_means[variable.id]/agg_nsamples[variable.id] << " @ " << agg_nsamples[variable.id] << std::endl; if(ct % 10 == 0){ break; } } } std::cout << " ..." << std::endl; std::string filename_protocol = p_cmd_parser->output_folder->getValue() + "/inference_result.out"; std::string filename_text = p_cmd_parser->output_folder->getValue() + "/inference_result.out.text"; std::cout << "DUMPING... PROTOCOL: " << filename_protocol << std::endl; std::cout << "DUMPING... TEXT : " << filename_text << std::endl; std::ofstream fout_text(filename_text.c_str()); std::ofstream mFs(filename_protocol.c_str(),std::ios::out | std::ios::binary); google::protobuf::io::OstreamOutputStream *_OstreamOutputStream = new google::protobuf::io::OstreamOutputStream(&mFs); google::protobuf::io::CodedOutputStream *_CodedOutputStream = new google::protobuf::io::CodedOutputStream(_OstreamOutputStream); deepdive::VariableInferenceResult msg; for(const Variable & variable : factorgraphs[0].variables){ if(variable.is_evid == true){ continue; } if(variable.domain_type != DTYPE_BOOLEAN){ std::cout << "ERROR: Only support boolean variables for now!" << std::endl; assert(false); } fout_text << variable.id << " " << (agg_means[variable.id]/agg_nsamples[variable.id]) << std::endl; msg.set_id(variable.id); msg.set_category(1.0); msg.set_expectation(agg_means[variable.id]/agg_nsamples[variable.id]); _CodedOutputStream->WriteVarint32(msg.ByteSize()); if ( !msg.SerializeToCodedStream(_CodedOutputStream) ){ std::cout << "SerializeToCodedStream error " << std::endl; assert(false); } } delete _CodedOutputStream; delete _OstreamOutputStream; mFs.close(); fout_text.close(); std::cout << "INFERENCE CALIBRATION (QUERY BINS):" << std::endl; std::vector<int> abc; for(int i=0;i<=10;i++){ abc.push_back(0); } int bad = 0; for(const auto & variable : factorgraphs[0].variables){ if(variable.is_evid == true){ continue; } int bin = (int)(agg_means[variable.id]/agg_nsamples[variable.id]*10); if(bin >= 0 && bin <=10){ abc[bin] ++; }else{ //std::cout << variable.id << " " << variable.agg_mean << " " << variable.n_sample << std::endl; bad ++; } } abc[9] += abc[10]; for(int i=0;i<10;i++){ std::cout << "PROB BIN 0." << i << "~0." << (i+1) << " --> # " << abc[i] << std::endl; } } <commit_msg>parallel load<commit_after> #include "app/gibbs/gibbs_sampling.h" #include "app/gibbs/single_node_sampler.h" #include "io/pb_parser.h" #include "common.h" #include <unistd.h> #include <fstream> #include "timer.h" void load_fg(dd::FactorGraph * const _p_fg, const dd::CmdParser & cmd, const int & nodeid){ std::cout << "LOADING FACTOR GRAPH ON NODE " << nodeid << std::endl; numa_run_on_node(nodeid); numa_set_localalloc(); _p_fg->load(cmd); } /*! * \brief In this function, the factor graph is located to each NUMA node. * * TODO: in the near future, this allocation should be abstracted * into a higher-level class to avoid writing similar things * for Gibbs, NN, SGD etc. However, this is the task of next pass * of refactoring. */ void dd::GibbsSampling::prepare(){ n_numa_nodes = numa_max_node(); n_thread_per_numa = (sysconf(_SC_NPROCESSORS_CONF))/(n_numa_nodes+1); std::vector<std::thread> loaders; for(int i=0;i<=n_numa_nodes;i++){ dd::FactorGraph * fg = new dd::FactorGraph; this->factorgraphs.push_back(*fg); } for(int i=0;i<=n_numa_nodes;i++){ dd::FactorGraph * fg = new dd::FactorGraph; this->factorgraphs.push_back(*fg); loaders.push_back(std::thread(load_fg, &factorgraphs[i], *p_cmd_parser, i)); } for(int i=0;i<=n_numa_nodes;i++){ loaders[i].join(); } } void dd::GibbsSampling::inference(const int & n_epoch){ Timer t_total; Timer t; int nvar = this->factorgraphs[0].variables.size(); std::cout << nvar << "!!!!!!!!!!!" << std::endl; int nnode = n_numa_nodes + 1; std::vector<SingleNodeSampler> single_node_samplers; for(int i=0;i<=n_numa_nodes;i++){ single_node_samplers.push_back(SingleNodeSampler(&this->factorgraphs[i], n_thread_per_numa, i)); } for(int i=0;i<=n_numa_nodes;i++){ single_node_samplers[i].clear_variabletally(); } for(int i_epoch=0;i_epoch<n_epoch;i_epoch++){ std::cout << std::setprecision(2) << "INFERENCE EPOCH " << i_epoch * nnode << "~" << ((i_epoch+1) * nnode) << "...." << std::flush; t.restart(); for(int i=0;i<nnode;i++){ single_node_samplers[i].sample(); } for(int i=0;i<nnode;i++){ single_node_samplers[i].wait(); } double elapsed = t.elapsed(); std::cout << "" << elapsed << " sec." ; std::cout << "," << (nvar*nnode)/elapsed << " vars/sec" << std::endl; } double elapsed = t_total.elapsed(); std::cout << "TOTAL INFERENCE TIME: " << elapsed << " sec." << std::endl; } void dd::GibbsSampling::learn(const int & n_epoch, const int & n_sample_per_epoch, const double & stepsize, const double & decay){ Timer t_total; double current_stepsize = stepsize; Timer t; int nvar = this->factorgraphs[0].variables.size(); int nnode = n_numa_nodes + 1; int nweight = this->factorgraphs[0].weights.size(); std::vector<SingleNodeSampler> single_node_samplers; for(int i=0;i<=n_numa_nodes;i++){ single_node_samplers.push_back(SingleNodeSampler(&this->factorgraphs[i], n_thread_per_numa, i)); } double * ori_weights = new double[nweight]; for(int i_epoch=0;i_epoch<n_epoch;i_epoch++){ std::cout << std::setprecision(2) << "LEARNING EPOCH " << i_epoch * nnode << "~" << ((i_epoch+1) * nnode) << "...." << std::flush; t.restart(); memcpy(ori_weights, &this->factorgraphs[0].infrs->weight_values, sizeof(double)*nweight); for(int i=0;i<nnode;i++){ single_node_samplers[i].p_fg->stepsize = current_stepsize; } for(int i=0;i<nnode;i++){ single_node_samplers[i].sample_sgd(); } for(int i=0;i<nnode;i++){ single_node_samplers[i].wait_sgd(); } FactorGraph & cfg = this->factorgraphs[0]; for(int i=1;i<=n_numa_nodes;i++){ FactorGraph & cfg_other = this->factorgraphs[i]; for(int j=0;j<nweight;j++){ cfg.infrs->weight_values[j] += cfg_other.infrs->weight_values[j]; } } for(int j=0;j<nweight;j++){ cfg.infrs->weight_values[j] /= nnode; cfg.infrs->weight_values[j] *= (1.0/(1.0+0.01*current_stepsize)); } for(int i=1;i<=n_numa_nodes;i++){ FactorGraph &cfg_other = this->factorgraphs[i]; for(int j=0;j<nweight;j++){ if(cfg.infrs->weights_isfixed[j] == false){ cfg_other.infrs->weight_values[j] = cfg.infrs->weight_values[j]; } } } double lmax = -1000000; double l2=0.0; for(int i=0;i<nweight;i++){ double diff = fabs(ori_weights[i] - cfg.infrs->weight_values[i]); l2 += diff*diff; if(lmax < diff){ lmax = diff; } } lmax = lmax/current_stepsize; double elapsed = t.elapsed(); std::cout << "" << elapsed << " sec."; std::cout << "," << (nvar*nnode)/elapsed << " vars/sec." << ",stepsize=" << current_stepsize << ",lmax=" << lmax << ",l2=" << sqrt(l2)/current_stepsize << std::endl; //std::cout << " " << this->compact_factors[0].fg_mutable->weights[0] << std::endl; current_stepsize = current_stepsize * decay; } double elapsed = t_total.elapsed(); std::cout << "TOTAL LEARNING TIME: " << elapsed << " sec." << std::endl; } void dd::GibbsSampling::dump_weights(){ std::cout << "LEARNING SNIPPETS (QUERY WEIGHTS):" << std::endl; FactorGraph const & cfg = this->factorgraphs[0]; int ct = 0; for(size_t i=0;i<cfg.infrs->nweights;i++){ ct ++; std::cout << " " << i << " " << cfg.infrs->weight_values[i] << std::endl; if(ct % 10 == 0){ break; } } std::cout << " ..." << std::endl; std::string filename_protocol = p_cmd_parser->output_folder->getValue() + "/inference_result.out.weights"; std::string filename_text = p_cmd_parser->output_folder->getValue() + "/inference_result.out.weights.text"; std::cout << "DUMPING... PROTOCOL: " << filename_protocol << std::endl; std::cout << "DUMPING... TEXT : " << filename_text << std::endl; std::ofstream fout_text(filename_text.c_str()); std::ofstream mFs(filename_protocol.c_str(),std::ios::out | std::ios::binary); google::protobuf::io::OstreamOutputStream *_OstreamOutputStream = new google::protobuf::io::OstreamOutputStream(&mFs); google::protobuf::io::CodedOutputStream *_CodedOutputStream = new google::protobuf::io::CodedOutputStream(_OstreamOutputStream); deepdive::WeightInferenceResult msg; for(size_t i=0;i<cfg.infrs->nweights;i++){ fout_text << i << " " << cfg.infrs->weight_values[i] << std::endl; msg.set_id(i); msg.set_value(cfg.infrs->weight_values[i]); _CodedOutputStream->WriteVarint32(msg.ByteSize()); if ( !msg.SerializeToCodedStream(_CodedOutputStream) ){ std::cout << "SerializeToCodedStream error " << std::endl; assert(false); } } delete _CodedOutputStream; delete _OstreamOutputStream; mFs.close(); fout_text.close(); } void dd::GibbsSampling::dump(){ double * agg_means = new double[factorgraphs[0].variables.size()]; double * agg_nsamples = new double[factorgraphs[0].variables.size()]; for(long i=0;i<factorgraphs[0].variables.size();i++){ agg_means[i] = 0; agg_nsamples[i] = 0; } for(int i=0;i<=n_numa_nodes;i++){ const FactorGraph & cfg = factorgraphs[i]; for(auto & variable : cfg.variables){ agg_means[variable.id] += cfg.infrs->agg_means[variable.id]; agg_nsamples[variable.id] += cfg.infrs->agg_nsamples[variable.id]; } } std::cout << "INFERENCE SNIPPETS (QUERY VARIABLES):" << std::endl; int ct = 0; for(const Variable & variable : factorgraphs[0].variables){ if(variable.is_evid == false){ ct ++; std::cout << " " << variable.id << " " << agg_means[variable.id]/agg_nsamples[variable.id] << " @ " << agg_nsamples[variable.id] << std::endl; if(ct % 10 == 0){ break; } } } std::cout << " ..." << std::endl; std::string filename_protocol = p_cmd_parser->output_folder->getValue() + "/inference_result.out"; std::string filename_text = p_cmd_parser->output_folder->getValue() + "/inference_result.out.text"; std::cout << "DUMPING... PROTOCOL: " << filename_protocol << std::endl; std::cout << "DUMPING... TEXT : " << filename_text << std::endl; std::ofstream fout_text(filename_text.c_str()); std::ofstream mFs(filename_protocol.c_str(),std::ios::out | std::ios::binary); google::protobuf::io::OstreamOutputStream *_OstreamOutputStream = new google::protobuf::io::OstreamOutputStream(&mFs); google::protobuf::io::CodedOutputStream *_CodedOutputStream = new google::protobuf::io::CodedOutputStream(_OstreamOutputStream); deepdive::VariableInferenceResult msg; for(const Variable & variable : factorgraphs[0].variables){ if(variable.is_evid == true){ continue; } if(variable.domain_type != DTYPE_BOOLEAN){ std::cout << "ERROR: Only support boolean variables for now!" << std::endl; assert(false); } fout_text << variable.id << " " << (agg_means[variable.id]/agg_nsamples[variable.id]) << std::endl; msg.set_id(variable.id); msg.set_category(1.0); msg.set_expectation(agg_means[variable.id]/agg_nsamples[variable.id]); _CodedOutputStream->WriteVarint32(msg.ByteSize()); if ( !msg.SerializeToCodedStream(_CodedOutputStream) ){ std::cout << "SerializeToCodedStream error " << std::endl; assert(false); } } delete _CodedOutputStream; delete _OstreamOutputStream; mFs.close(); fout_text.close(); std::cout << "INFERENCE CALIBRATION (QUERY BINS):" << std::endl; std::vector<int> abc; for(int i=0;i<=10;i++){ abc.push_back(0); } int bad = 0; for(const auto & variable : factorgraphs[0].variables){ if(variable.is_evid == true){ continue; } int bin = (int)(agg_means[variable.id]/agg_nsamples[variable.id]*10); if(bin >= 0 && bin <=10){ abc[bin] ++; }else{ //std::cout << variable.id << " " << variable.agg_mean << " " << variable.n_sample << std::endl; bad ++; } } abc[9] += abc[10]; for(int i=0;i<10;i++){ std::cout << "PROB BIN 0." << i << "~0." << (i+1) << " --> # " << abc[i] << std::endl; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** 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 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "setupqt.h" #include "../shared/logging/consolelogger.h" #include <qtprofilesetup.h> #include <logging/translator.h> #include <tools/hostosinfo.h> #include <tools/profile.h> #include <tools/settings.h> #include <tools/version.h> #include <QByteArrayMatcher> #include <QCoreApplication> #include <QDir> #include <QFileInfo> #include <QProcess> #include <QRegExp> #include <QStringList> #include <QtDebug> namespace qbs { using Internal::HostOsInfo; using Internal::Tr; using Internal::Version; const QString qmakeExecutableName = QLatin1String("qmake" QBS_HOST_EXE_SUFFIX); static QStringList collectQmakePaths() { QStringList qmakePaths; QByteArray environmentPath = qgetenv("PATH"); QList<QByteArray> environmentPaths = environmentPath.split(HostOsInfo::pathListSeparator().toLatin1()); foreach (const QByteArray &path, environmentPaths) { QFileInfo pathFileInfo(QDir(QLatin1String(path)), qmakeExecutableName); if (pathFileInfo.exists()) { QString qmakePath = pathFileInfo.absoluteFilePath(); if (!qmakePaths.contains(qmakePath)) qmakePaths.append(qmakePath); } } return qmakePaths; } bool SetupQt::isQMakePathValid(const QString &qmakePath) { QFileInfo qmakeFileInfo(qmakePath); return qmakeFileInfo.exists() && qmakeFileInfo.isFile() && qmakeFileInfo.isExecutable(); } QList<QtEnvironment> SetupQt::fetchEnvironments() { QList<QtEnvironment> qtEnvironments; foreach (const QString &qmakePath, collectQmakePaths()) qtEnvironments.append(fetchEnvironment(qmakePath)); return qtEnvironments; } void SetupQt::addQtBuildVariant(QtEnvironment *env, const QString &buildVariantName) { if (env->qtConfigItems.contains(buildVariantName)) env->buildVariant << buildVariantName; } static QMap<QByteArray, QByteArray> qmakeQueryOutput(const QString &qmakePath) { QProcess qmakeProcess; qmakeProcess.start(qmakePath, QStringList() << QLatin1String("-query")); if (!qmakeProcess.waitForStarted()) throw ErrorInfo(SetupQt::tr("%1 cannot be started.").arg(qmakePath)); qmakeProcess.waitForFinished(); const QByteArray output = qmakeProcess.readAllStandardOutput(); QMap<QByteArray, QByteArray> ret; foreach (const QByteArray &line, output.split('\n')) { int idx = line.indexOf(':'); if (idx >= 0) ret[line.left(idx)] = line.mid(idx + 1).trimmed(); } return ret; } static QByteArray readFileContent(const QString &filePath) { QFile file(filePath); if (file.open(QFile::ReadOnly)) return file.readAll(); return QByteArray(); } static QString configVariable(const QByteArray &configContent, const QString &key) { QRegExp regexp(QLatin1String("\\s*") + key + QLatin1String("\\s*\\+{0,1}=(.*)"), Qt::CaseSensitive); QList<QByteArray> configContentLines = configContent.split('\n'); bool success = false; foreach (const QByteArray &configContentLine, configContentLines) { success = regexp.exactMatch(QString::fromLocal8Bit(configContentLine)); if (success) break; } if (success) return regexp.capturedTexts()[1].simplified(); return QString(); } static QStringList configVariableItems(const QByteArray &configContent, const QString &key) { return configVariable(configContent, key).split(QLatin1Char(' '), QString::SkipEmptyParts); } typedef QMap<QByteArray, QByteArray> QueryMap; static QString pathQueryValue(const QueryMap &queryMap, const QByteArray &key) { return QDir::fromNativeSeparators(QString::fromLocal8Bit(queryMap.value(key))); } QtEnvironment SetupQt::fetchEnvironment(const QString &qmakePath) { QtEnvironment qtEnvironment; QueryMap queryOutput = qmakeQueryOutput(qmakePath); qtEnvironment.installPrefixPath = pathQueryValue(queryOutput, "QT_INSTALL_PREFIX"); qtEnvironment.documentationPath = pathQueryValue(queryOutput, "QT_INSTALL_DOCS"); qtEnvironment.includePath = pathQueryValue(queryOutput, "QT_INSTALL_HEADERS"); qtEnvironment.libraryPath = pathQueryValue(queryOutput, "QT_INSTALL_LIBS"); qtEnvironment.binaryPath = pathQueryValue(queryOutput, "QT_HOST_BINS"); if (qtEnvironment.binaryPath.isEmpty()) qtEnvironment.binaryPath = pathQueryValue(queryOutput, "QT_INSTALL_BINS"); qtEnvironment.documentationPath = pathQueryValue(queryOutput, "QT_INSTALL_DOCS"); qtEnvironment.pluginPath = pathQueryValue(queryOutput, "QT_INSTALL_PLUGINS"); qtEnvironment.qmlPath = pathQueryValue(queryOutput, "QT_INSTALL_QML"); qtEnvironment.qmlImportPath = pathQueryValue(queryOutput, "QT_INSTALL_IMPORTS"); qtEnvironment.qtVersion = QString::fromLocal8Bit(queryOutput.value("QT_VERSION")); const Version qtVersion = Version::fromString(qtEnvironment.qtVersion); QString mkspecsBaseSrcPath; if (qtVersion.majorVersion() >= 5) { qtEnvironment.mkspecBasePath = pathQueryValue(queryOutput, "QT_HOST_DATA") + QLatin1String("/mkspecs"); mkspecsBaseSrcPath = pathQueryValue(queryOutput, "QT_HOST_DATA/src") + QLatin1String("/mkspecs"); } else { qtEnvironment.mkspecBasePath = pathQueryValue(queryOutput, "QT_INSTALL_DATA") + QLatin1String("/mkspecs"); } if (!QFile::exists(qtEnvironment.mkspecBasePath)) throw ErrorInfo(tr("Cannot extract the mkspecs directory.")); const QByteArray qconfigContent = readFileContent(qtEnvironment.mkspecBasePath + QLatin1String("/qconfig.pri")); qtEnvironment.qtMajorVersion = configVariable(qconfigContent, QLatin1String("QT_MAJOR_VERSION")).toInt(); qtEnvironment.qtMinorVersion = configVariable(qconfigContent, QLatin1String("QT_MINOR_VERSION")).toInt(); qtEnvironment.qtPatchVersion = configVariable(qconfigContent, QLatin1String("QT_PATCH_VERSION")).toInt(); qtEnvironment.qtNameSpace = configVariable(qconfigContent, QLatin1String("QT_NAMESPACE")); qtEnvironment.qtLibInfix = configVariable(qconfigContent, QLatin1String("QT_LIBINFIX")); qtEnvironment.architecture = configVariable(qconfigContent, QLatin1String("QT_TARGET_ARCH")); if (qtEnvironment.architecture.isEmpty()) qtEnvironment.architecture = configVariable(qconfigContent, QLatin1String("QT_ARCH")); if (qtEnvironment.architecture.isEmpty()) qtEnvironment.architecture = QLatin1String("x86"); qtEnvironment.configItems = configVariableItems(qconfigContent, QLatin1String("CONFIG")); qtEnvironment.qtConfigItems = configVariableItems(qconfigContent, QLatin1String("QT_CONFIG")); // retrieve the mkspec if (qtVersion.majorVersion() >= 5) { const QString mkspecName = QString::fromLocal8Bit(queryOutput.value("QMAKE_XSPEC")); qtEnvironment.mkspecName = mkspecName; qtEnvironment.mkspecPath = qtEnvironment.mkspecBasePath + QLatin1Char('/') + mkspecName; if (!mkspecsBaseSrcPath.isEmpty() && !QFile::exists(qtEnvironment.mkspecPath)) qtEnvironment.mkspecPath = mkspecsBaseSrcPath + QLatin1Char('/') + mkspecName; } else { if (HostOsInfo::isWindowsHost()) { const QString baseDirPath = qtEnvironment.mkspecBasePath + QLatin1String("/default/"); const QByteArray fileContent = readFileContent(baseDirPath + QLatin1String("qmake.conf")); qtEnvironment.mkspecPath = configVariable(fileContent, QLatin1String("QMAKESPEC_ORIGINAL")); if (!QFile::exists(qtEnvironment.mkspecPath)) { // Work around QTBUG-28792. // The value of QMAKESPEC_ORIGINAL is wrong for MinGW packages. Y u h8 me? const QRegExp rex(QLatin1String("\\binclude\\(([^)]+)/qmake\\.conf\\)")); if (rex.indexIn(QString::fromLocal8Bit(fileContent)) != -1) qtEnvironment.mkspecPath = QDir::cleanPath(baseDirPath + rex.cap(1)); } } else { qtEnvironment.mkspecPath = QFileInfo(qtEnvironment.mkspecBasePath + QLatin1String("/default")).symLinkTarget(); } qtEnvironment.mkspecName = qtEnvironment.mkspecPath; int idx = qtEnvironment.mkspecName.lastIndexOf(QLatin1Char('/')); if (idx != -1) qtEnvironment.mkspecName.remove(0, idx + 1); } // determine whether we have a framework build qtEnvironment.frameworkBuild = false; if (qtEnvironment.mkspecPath.contains(QLatin1String("macx"))) { if (qtEnvironment.configItems.contains(QLatin1String("qt_framework"))) qtEnvironment.frameworkBuild = true; else if (!qtEnvironment.configItems.contains(QLatin1String("qt_no_framework"))) throw ErrorInfo(tr("could not determine whether Qt is a frameworks build")); } // determine whether Qt is built with debug, release or both addQtBuildVariant(&qtEnvironment, QLatin1String("debug")); addQtBuildVariant(&qtEnvironment, QLatin1String("release")); if (!QFileInfo(qtEnvironment.mkspecPath).exists()) throw ErrorInfo(tr("mkspec '%1' does not exist").arg(qtEnvironment.mkspecPath)); return qtEnvironment; } static bool isToolchainProfileKey(const QString &key) { // The Qt profile setup itself sets cpp.minimum*Version for some systems. return key.startsWith(QLatin1String("cpp.")) && !key.startsWith(QLatin1String("cpp.minimum")); } void SetupQt::saveToQbsSettings(const QString &qtVersionName, const QtEnvironment &qtEnvironment, Settings *settings) { const QString cleanQtVersionName = Profile::cleanName(qtVersionName); QString msg = QCoreApplication::translate("SetupQt", "Creating profile '%1'.") .arg(cleanQtVersionName); printf("%s\n", qPrintable(msg)); const ErrorInfo errorInfo = setupQtProfile(cleanQtVersionName, settings, qtEnvironment); if (errorInfo.hasError()) throw errorInfo; // If this profile does not specify a toolchain and we find exactly one profile that looks // like it might have been added by qbs-setup-toolchains, let's use that one as our // base profile. Profile profile(cleanQtVersionName, settings); if (!profile.baseProfile().isEmpty()) return; QStringList toolchainProfiles; foreach (const QString &key, profile.allKeys(Profile::KeySelectionNonRecursive)) { if (isToolchainProfileKey(key)) return; } foreach (const QString &profileName, settings->profiles()) { if (profileName == profile.name()) continue; const Profile otherProfile(profileName, settings); bool hasCppKey = false; bool hasQtKey = false; foreach (const QString &key, otherProfile.allKeys(Profile::KeySelectionNonRecursive)) { if (isToolchainProfileKey(key)) { hasCppKey = true; } else if (key.startsWith(QLatin1String("Qt."))) { hasQtKey = true; break; } } if (hasCppKey && !hasQtKey) toolchainProfiles << profileName; } if (toolchainProfiles.count() != 1) { QString message = Tr::tr("You need to set up toolchain information before you can " "use this Qt version for building. "); if (toolchainProfiles.isEmpty()) { message += Tr::tr("However, no toolchain profile was found. Either create one " "using qbs-setup-toolchains and set it as this profile's " "base profile or add the toolchain settings manually " "to this profile."); } else { message += Tr::tr("Consider setting one of these profiles as this profile's base " "profile: %1.").arg(toolchainProfiles.join(QLatin1String(", "))); } qbsWarning() << message; } else { profile.setBaseProfile(toolchainProfiles.first()); qbsInfo() << Tr::tr("Setting profile '%1' as the base profile for this profile.") .arg(toolchainProfiles.first()); } } bool SetupQt::checkIfMoreThanOneQtWithTheSameVersion(const QString &qtVersion, const QList<QtEnvironment> &qtEnvironments) { bool foundOneVersion = false; foreach (const QtEnvironment &qtEnvironment, qtEnvironments) { if (qtEnvironment.qtVersion == qtVersion) { if (foundOneVersion) return true; foundOneVersion = true; } } return false; } } // namespace qbs <commit_msg>setupqt: Don't create more than one profile for the same Qt.<commit_after>/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms and ** conditions see http://www.qt.io/terms-conditions. For further information ** use the contact form at http://www.qt.io/contact-us. ** ** 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 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "setupqt.h" #include "../shared/logging/consolelogger.h" #include <qtprofilesetup.h> #include <logging/translator.h> #include <tools/hostosinfo.h> #include <tools/profile.h> #include <tools/settings.h> #include <tools/version.h> #include <QByteArrayMatcher> #include <QCoreApplication> #include <QDir> #include <QFileInfo> #include <QProcess> #include <QRegExp> #include <QStringList> #include <QtDebug> #include <algorithm> namespace qbs { using Internal::HostOsInfo; using Internal::Tr; using Internal::Version; const QString qmakeExecutableName = QLatin1String("qmake" QBS_HOST_EXE_SUFFIX); static QStringList collectQmakePaths() { QStringList qmakePaths; QByteArray environmentPath = qgetenv("PATH"); QList<QByteArray> environmentPaths = environmentPath.split(HostOsInfo::pathListSeparator().toLatin1()); foreach (const QByteArray &path, environmentPaths) { QFileInfo pathFileInfo(QDir(QLatin1String(path)), qmakeExecutableName); if (pathFileInfo.exists()) { QString qmakePath = pathFileInfo.absoluteFilePath(); if (!qmakePaths.contains(qmakePath)) qmakePaths.append(qmakePath); } } return qmakePaths; } bool SetupQt::isQMakePathValid(const QString &qmakePath) { QFileInfo qmakeFileInfo(qmakePath); return qmakeFileInfo.exists() && qmakeFileInfo.isFile() && qmakeFileInfo.isExecutable(); } QList<QtEnvironment> SetupQt::fetchEnvironments() { QList<QtEnvironment> qtEnvironments; foreach (const QString &qmakePath, collectQmakePaths()) { const QtEnvironment env = fetchEnvironment(qmakePath); if (std::find_if(qtEnvironments.constBegin(), qtEnvironments.constEnd(), [&env](const QtEnvironment &otherEnv) { return env.includePath == otherEnv.includePath; }) == qtEnvironments.constEnd()) { qtEnvironments.append(env); } } return qtEnvironments; } void SetupQt::addQtBuildVariant(QtEnvironment *env, const QString &buildVariantName) { if (env->qtConfigItems.contains(buildVariantName)) env->buildVariant << buildVariantName; } static QMap<QByteArray, QByteArray> qmakeQueryOutput(const QString &qmakePath) { QProcess qmakeProcess; qmakeProcess.start(qmakePath, QStringList() << QLatin1String("-query")); if (!qmakeProcess.waitForStarted()) throw ErrorInfo(SetupQt::tr("%1 cannot be started.").arg(qmakePath)); qmakeProcess.waitForFinished(); const QByteArray output = qmakeProcess.readAllStandardOutput(); QMap<QByteArray, QByteArray> ret; foreach (const QByteArray &line, output.split('\n')) { int idx = line.indexOf(':'); if (idx >= 0) ret[line.left(idx)] = line.mid(idx + 1).trimmed(); } return ret; } static QByteArray readFileContent(const QString &filePath) { QFile file(filePath); if (file.open(QFile::ReadOnly)) return file.readAll(); return QByteArray(); } static QString configVariable(const QByteArray &configContent, const QString &key) { QRegExp regexp(QLatin1String("\\s*") + key + QLatin1String("\\s*\\+{0,1}=(.*)"), Qt::CaseSensitive); QList<QByteArray> configContentLines = configContent.split('\n'); bool success = false; foreach (const QByteArray &configContentLine, configContentLines) { success = regexp.exactMatch(QString::fromLocal8Bit(configContentLine)); if (success) break; } if (success) return regexp.capturedTexts()[1].simplified(); return QString(); } static QStringList configVariableItems(const QByteArray &configContent, const QString &key) { return configVariable(configContent, key).split(QLatin1Char(' '), QString::SkipEmptyParts); } typedef QMap<QByteArray, QByteArray> QueryMap; static QString pathQueryValue(const QueryMap &queryMap, const QByteArray &key) { return QDir::fromNativeSeparators(QString::fromLocal8Bit(queryMap.value(key))); } QtEnvironment SetupQt::fetchEnvironment(const QString &qmakePath) { QtEnvironment qtEnvironment; QueryMap queryOutput = qmakeQueryOutput(qmakePath); qtEnvironment.installPrefixPath = pathQueryValue(queryOutput, "QT_INSTALL_PREFIX"); qtEnvironment.documentationPath = pathQueryValue(queryOutput, "QT_INSTALL_DOCS"); qtEnvironment.includePath = pathQueryValue(queryOutput, "QT_INSTALL_HEADERS"); qtEnvironment.libraryPath = pathQueryValue(queryOutput, "QT_INSTALL_LIBS"); qtEnvironment.binaryPath = pathQueryValue(queryOutput, "QT_HOST_BINS"); if (qtEnvironment.binaryPath.isEmpty()) qtEnvironment.binaryPath = pathQueryValue(queryOutput, "QT_INSTALL_BINS"); qtEnvironment.documentationPath = pathQueryValue(queryOutput, "QT_INSTALL_DOCS"); qtEnvironment.pluginPath = pathQueryValue(queryOutput, "QT_INSTALL_PLUGINS"); qtEnvironment.qmlPath = pathQueryValue(queryOutput, "QT_INSTALL_QML"); qtEnvironment.qmlImportPath = pathQueryValue(queryOutput, "QT_INSTALL_IMPORTS"); qtEnvironment.qtVersion = QString::fromLocal8Bit(queryOutput.value("QT_VERSION")); const Version qtVersion = Version::fromString(qtEnvironment.qtVersion); QString mkspecsBaseSrcPath; if (qtVersion.majorVersion() >= 5) { qtEnvironment.mkspecBasePath = pathQueryValue(queryOutput, "QT_HOST_DATA") + QLatin1String("/mkspecs"); mkspecsBaseSrcPath = pathQueryValue(queryOutput, "QT_HOST_DATA/src") + QLatin1String("/mkspecs"); } else { qtEnvironment.mkspecBasePath = pathQueryValue(queryOutput, "QT_INSTALL_DATA") + QLatin1String("/mkspecs"); } if (!QFile::exists(qtEnvironment.mkspecBasePath)) throw ErrorInfo(tr("Cannot extract the mkspecs directory.")); const QByteArray qconfigContent = readFileContent(qtEnvironment.mkspecBasePath + QLatin1String("/qconfig.pri")); qtEnvironment.qtMajorVersion = configVariable(qconfigContent, QLatin1String("QT_MAJOR_VERSION")).toInt(); qtEnvironment.qtMinorVersion = configVariable(qconfigContent, QLatin1String("QT_MINOR_VERSION")).toInt(); qtEnvironment.qtPatchVersion = configVariable(qconfigContent, QLatin1String("QT_PATCH_VERSION")).toInt(); qtEnvironment.qtNameSpace = configVariable(qconfigContent, QLatin1String("QT_NAMESPACE")); qtEnvironment.qtLibInfix = configVariable(qconfigContent, QLatin1String("QT_LIBINFIX")); qtEnvironment.architecture = configVariable(qconfigContent, QLatin1String("QT_TARGET_ARCH")); if (qtEnvironment.architecture.isEmpty()) qtEnvironment.architecture = configVariable(qconfigContent, QLatin1String("QT_ARCH")); if (qtEnvironment.architecture.isEmpty()) qtEnvironment.architecture = QLatin1String("x86"); qtEnvironment.configItems = configVariableItems(qconfigContent, QLatin1String("CONFIG")); qtEnvironment.qtConfigItems = configVariableItems(qconfigContent, QLatin1String("QT_CONFIG")); // retrieve the mkspec if (qtVersion.majorVersion() >= 5) { const QString mkspecName = QString::fromLocal8Bit(queryOutput.value("QMAKE_XSPEC")); qtEnvironment.mkspecName = mkspecName; qtEnvironment.mkspecPath = qtEnvironment.mkspecBasePath + QLatin1Char('/') + mkspecName; if (!mkspecsBaseSrcPath.isEmpty() && !QFile::exists(qtEnvironment.mkspecPath)) qtEnvironment.mkspecPath = mkspecsBaseSrcPath + QLatin1Char('/') + mkspecName; } else { if (HostOsInfo::isWindowsHost()) { const QString baseDirPath = qtEnvironment.mkspecBasePath + QLatin1String("/default/"); const QByteArray fileContent = readFileContent(baseDirPath + QLatin1String("qmake.conf")); qtEnvironment.mkspecPath = configVariable(fileContent, QLatin1String("QMAKESPEC_ORIGINAL")); if (!QFile::exists(qtEnvironment.mkspecPath)) { // Work around QTBUG-28792. // The value of QMAKESPEC_ORIGINAL is wrong for MinGW packages. Y u h8 me? const QRegExp rex(QLatin1String("\\binclude\\(([^)]+)/qmake\\.conf\\)")); if (rex.indexIn(QString::fromLocal8Bit(fileContent)) != -1) qtEnvironment.mkspecPath = QDir::cleanPath(baseDirPath + rex.cap(1)); } } else { qtEnvironment.mkspecPath = QFileInfo(qtEnvironment.mkspecBasePath + QLatin1String("/default")).symLinkTarget(); } qtEnvironment.mkspecName = qtEnvironment.mkspecPath; int idx = qtEnvironment.mkspecName.lastIndexOf(QLatin1Char('/')); if (idx != -1) qtEnvironment.mkspecName.remove(0, idx + 1); } // determine whether we have a framework build qtEnvironment.frameworkBuild = false; if (qtEnvironment.mkspecPath.contains(QLatin1String("macx"))) { if (qtEnvironment.configItems.contains(QLatin1String("qt_framework"))) qtEnvironment.frameworkBuild = true; else if (!qtEnvironment.configItems.contains(QLatin1String("qt_no_framework"))) throw ErrorInfo(tr("could not determine whether Qt is a frameworks build")); } // determine whether Qt is built with debug, release or both addQtBuildVariant(&qtEnvironment, QLatin1String("debug")); addQtBuildVariant(&qtEnvironment, QLatin1String("release")); if (!QFileInfo(qtEnvironment.mkspecPath).exists()) throw ErrorInfo(tr("mkspec '%1' does not exist").arg(qtEnvironment.mkspecPath)); return qtEnvironment; } static bool isToolchainProfileKey(const QString &key) { // The Qt profile setup itself sets cpp.minimum*Version for some systems. return key.startsWith(QLatin1String("cpp.")) && !key.startsWith(QLatin1String("cpp.minimum")); } void SetupQt::saveToQbsSettings(const QString &qtVersionName, const QtEnvironment &qtEnvironment, Settings *settings) { const QString cleanQtVersionName = Profile::cleanName(qtVersionName); QString msg = QCoreApplication::translate("SetupQt", "Creating profile '%1'.") .arg(cleanQtVersionName); printf("%s\n", qPrintable(msg)); const ErrorInfo errorInfo = setupQtProfile(cleanQtVersionName, settings, qtEnvironment); if (errorInfo.hasError()) throw errorInfo; // If this profile does not specify a toolchain and we find exactly one profile that looks // like it might have been added by qbs-setup-toolchains, let's use that one as our // base profile. Profile profile(cleanQtVersionName, settings); if (!profile.baseProfile().isEmpty()) return; QStringList toolchainProfiles; foreach (const QString &key, profile.allKeys(Profile::KeySelectionNonRecursive)) { if (isToolchainProfileKey(key)) return; } foreach (const QString &profileName, settings->profiles()) { if (profileName == profile.name()) continue; const Profile otherProfile(profileName, settings); bool hasCppKey = false; bool hasQtKey = false; foreach (const QString &key, otherProfile.allKeys(Profile::KeySelectionNonRecursive)) { if (isToolchainProfileKey(key)) { hasCppKey = true; } else if (key.startsWith(QLatin1String("Qt."))) { hasQtKey = true; break; } } if (hasCppKey && !hasQtKey) toolchainProfiles << profileName; } if (toolchainProfiles.count() != 1) { QString message = Tr::tr("You need to set up toolchain information before you can " "use this Qt version for building. "); if (toolchainProfiles.isEmpty()) { message += Tr::tr("However, no toolchain profile was found. Either create one " "using qbs-setup-toolchains and set it as this profile's " "base profile or add the toolchain settings manually " "to this profile."); } else { message += Tr::tr("Consider setting one of these profiles as this profile's base " "profile: %1.").arg(toolchainProfiles.join(QLatin1String(", "))); } qbsWarning() << message; } else { profile.setBaseProfile(toolchainProfiles.first()); qbsInfo() << Tr::tr("Setting profile '%1' as the base profile for this profile.") .arg(toolchainProfiles.first()); } } bool SetupQt::checkIfMoreThanOneQtWithTheSameVersion(const QString &qtVersion, const QList<QtEnvironment> &qtEnvironments) { bool foundOneVersion = false; foreach (const QtEnvironment &qtEnvironment, qtEnvironments) { if (qtEnvironment.qtVersion == qtVersion) { if (foundOneVersion) return true; foundOneVersion = true; } } return false; } } // namespace qbs <|endoftext|>
<commit_before>#include "permuter.h" #include <sys/stat.h> #include <stdio.h> #include <fstream> #include <vector> #include <iostream> #include <algorithm> #include <iterator> #include <boost/algorithm/string.hpp> #include <codecvt> #include <locale> #include <clocale> #include <cstdlib> #define ENDL "\n" Permuter::Permuter() {} bool Permuter::allGood() { return true || (this->fileExists(this->sourceFile) && this->canWriteToFile(this->targetFile)); } /** * @brief Checks if a file exists * @details Does not check if the file is readable * @param sourceFile std::wstring * @return bool true if the file exists */ bool Permuter::fileExists(std::string sourceFile) { struct stat buffer; if (stat (sourceFile.c_str(), &buffer) == 0) { std::cout << "fileExists(" << sourceFile << ") -> true" << ENDL; return true; } return false; } bool Permuter::canWriteToFile(std::string targetFile) { FILE * pFile; const char* param = targetFile.c_str(); pFile = fopen(param, "w"); return pFile != NULL; } void Permuter::setWord(std::wstring word) {} /** * @brief Counts lines in a file * @details [long description] * * @param pathToFile The path to the file to count lines from * @return int The number of lines in a file */ int Permuter::countLinesInFile(std::string pathToFile) { std::ifstream sFile(pathToFile); std::string line; int total = 0; for (; std::getline(sFile, line); ++total); return total; } void Permuter::setSourceFile(std::string sourceFile) { this->sourceFile = sourceFile; } void Permuter::setTargetFile(std::string targetFile) { this->targetFile = targetFile; } std::vector<std::wstring> Permuter::fileToVector(std::string sourceFile) { std::vector<std::wstring> originalWords; std::ifstream hFile(sourceFile); if (hFile.is_open()) { std::wifstream stream(sourceFile); std::wstring line; while (stream.good()) { std::getline(stream, line); // getline(hFile, line); originalWords.push_back(line); } } return originalWords; } bool Permuter::hasLowerCase(std::wstring toCheck) { return std::any_of(toCheck.begin(), toCheck.end(), ::islower); } /** * @details Takes the original word and returns a vector of all combinations with different cases * * @param original string of the original word to permute * @return [Chess, CHESS, chess, CHess, CHEss, CHESs, CHESS, cHess, cHEss, cHESs,...] */ std::vector<std::wstring> Permuter::mixCases(std::wstring original) { std::vector<std::wstring> mixedCases; // start with an upper case word std::wstring upper = boost::to_upper_copy<std::wstring>(original); mixedCases.push_back(upper); mixedCases.push_back(original); mixedCases.push_back(boost::to_lower_copy<std::wstring>(original)); // std::vector<std::wstring>::iterator ite = mixedCases.begin(); std::vector<std::wstring> lower_cases = this->mixOfLowerCases(original); // std::cout << "Added " << upper << " and " << original << ENDL; // std::cout << mixedCases[0] << ENDL; mixedCases = this->mergeVectors(mixedCases, lower_cases); // There shouldn't be any duplicates but lets make sure this->uniqueVector(mixedCases); return mixedCases; } /** * @brief Returns every combination of upper and lower case * @details [long description] * * @param original [description] * @return [Chess, CHess, cHess, cHEss,...] */ std::vector<std::wstring> Permuter::mixOfLowerCases(std::wstring original) { std::vector<std::wstring> lower_cases; std::wstring upper = this->to_upper(original); std::wstring temp_string; int original_size = original.size(); for(std::wstring::size_type current_char = 0; current_char <= original_size; ++current_char) { temp_string = upper; for(std::wstring::size_type iteration = 0; iteration <= (original_size); ++iteration) { // This routine creates duplicated entries, it can certainly be improved temp_string[current_char] = towlower(temp_string[current_char]); lower_cases.push_back(temp_string); temp_string[current_char + iteration] = towlower(temp_string[current_char + iteration]); lower_cases.push_back(temp_string); } } this->uniqueVector(lower_cases); return lower_cases; } void Permuter::printVector(std::vector<std::wstring> original) { for (std::vector<std::wstring>::iterator i = original.begin(); i != original.end(); i++) { std::wcout << *i << ENDL; } } std::wstring Permuter::to_upper(std::wstring original) { for (std::wstring::iterator it = original.begin(); it != original.end(); it++) { *it = towupper(*it); } return original; } /** * @brief Removes duplicate entries in an std::vector * * @param originalVector vector of string */ void Permuter::uniqueVector(std::vector<std::wstring> &originalVector) { sort( originalVector.begin(), originalVector.end() ); originalVector.erase( unique( originalVector.begin(), originalVector.end() ), originalVector.end() ); } /** * @brief Merges vectors * * @return A new array with the unique contents of arrays a and b */ std::vector<std::wstring> Permuter::mergeVectors(std::vector<std::wstring> a, std::vector<std::wstring> b) { std::vector<std::wstring> merged; merged.insert(merged.end(), a.begin(), a.end()); merged.insert(merged.end(), b.begin(), b.end()); this->uniqueVector(merged); return merged; } std::vector<std::wstring> Permuter::addNumbers(std::vector<std::wstring> original) { std::wstring temp; std::vector<std::wstring> passwords; // Merge vectors for (std::vector<std::wstring>::iterator ite = original.begin(); ite != original.end(); ite++) { passwords.push_back(temp); } } std::vector<std::wstring> Permuter::generatePasswords(std::wstring original) { std::vector<std::wstring> passwords; std::vector<std::wstring> mixedCases = this->mixCases(original); std::vector<std::wstring> numeric = this->addNumbers(mixedCases); passwords = this->mergeVectors(mixedCases, numeric); // Remove duplicates this->uniqueVector(passwords); return passwords; } void Permuter::savePasswordsToFile(std::vector<std::wstring> words) { // std::cout << "savePermutationsToFile() -> " std::wofstream store; store.open(this->targetFile); for (std::vector<std::wstring>::iterator ite = words.begin(); ite != words.end(); ite++) { std::wcout << std::wstring(L"savePasswordsToFile(vector<string>) -> Storing: ") << *ite << ENDL; store << *ite << ENDL; } store.close(); } void Permuter::run() { if (true || this->fileExists(this->sourceFile) == true) { std::vector<std::wstring> permutations; std::cout << this->sourceFile << " <--> " << this->targetFile << ENDL; this->sourceWords = this->fileToVector(this->sourceFile); std::cout << "Total words to permute: " << this->sourceWords.size() << ENDL; for (std::vector<std::wstring>::iterator ite = this->sourceWords.begin(); ite != this->sourceWords.end(); ite++ ) { std::wcout << std::wstring(L"run() -> ") << *ite << ENDL; permutations = this->generatePasswords(*ite); this->savePasswordsToFile(permutations); } // std::cout << "permutations[0]: " << permutations[0] << ENDL; } else { std::cout << "Not everything is ok" << ENDL; } }<commit_msg>Feature: Adds numbers to each string<commit_after>#include "permuter.h" #include <sys/stat.h> #include <stdio.h> #include <fstream> #include <vector> #include <iostream> #include <algorithm> #include <iterator> #include <boost/algorithm/string.hpp> #include <codecvt> #include <locale> #include <clocale> #include <cstdlib> #include <stdlib.h> #include <string> #define ENDL "\n" Permuter::Permuter() {} bool Permuter::allGood() { return true || (this->fileExists(this->sourceFile) && this->canWriteToFile(this->targetFile)); } /** * @brief Checks if a file exists * @details Does not check if the file is readable * @param sourceFile std::wstring * @return bool true if the file exists */ bool Permuter::fileExists(std::string sourceFile) { struct stat buffer; if (stat (sourceFile.c_str(), &buffer) == 0) { std::cout << "fileExists(" << sourceFile << ") -> true" << ENDL; return true; } return false; } bool Permuter::canWriteToFile(std::string targetFile) { FILE * pFile; const char* param = targetFile.c_str(); pFile = fopen(param, "w"); return pFile != NULL; } void Permuter::setWord(std::wstring word) {} /** * @brief Counts lines in a file * @details [long description] * * @param pathToFile The path to the file to count lines from * @return int The number of lines in a file */ int Permuter::countLinesInFile(std::string pathToFile) { std::ifstream sFile(pathToFile); std::string line; int total = 0; for (; std::getline(sFile, line); ++total); return total; } void Permuter::setSourceFile(std::string sourceFile) { this->sourceFile = sourceFile; } void Permuter::setTargetFile(std::string targetFile) { this->targetFile = targetFile; } std::vector<std::wstring> Permuter::fileToVector(std::string sourceFile) { std::vector<std::wstring> originalWords; std::ifstream hFile(sourceFile); if (hFile.is_open()) { std::wifstream stream(sourceFile); std::wstring line; while (stream.good()) { std::getline(stream, line); // getline(hFile, line); originalWords.push_back(line); } } return originalWords; } bool Permuter::hasLowerCase(std::wstring toCheck) { return std::any_of(toCheck.begin(), toCheck.end(), ::islower); } /** * @details Takes the original word and returns a vector of all combinations with different cases * * @param original string of the original word to permute * @return [Chess, CHESS, chess, CHess, CHEss, CHESs, CHESS, cHess, cHEss, cHESs,...] */ std::vector<std::wstring> Permuter::mixCases(std::wstring original) { std::vector<std::wstring> mixedCases; // start with an upper case word std::wstring upper = boost::to_upper_copy<std::wstring>(original); mixedCases.push_back(upper); mixedCases.push_back(original); mixedCases.push_back(boost::to_lower_copy<std::wstring>(original)); // std::vector<std::wstring>::iterator ite = mixedCases.begin(); std::vector<std::wstring> lower_cases = this->mixOfLowerCases(original); // std::cout << "Added " << upper << " and " << original << ENDL; // std::cout << mixedCases[0] << ENDL; mixedCases = this->mergeVectors(mixedCases, lower_cases); // There shouldn't be any duplicates but lets make sure this->uniqueVector(mixedCases); return mixedCases; } /** * @brief Returns every combination of upper and lower case * @details [long description] * * @param original [description] * @return [Chess, CHess, cHess, cHEss,...] */ std::vector<std::wstring> Permuter::mixOfLowerCases(std::wstring original) { std::vector<std::wstring> lower_cases; std::wstring upper = this->to_upper(original); std::wstring temp_string; int original_size = original.size(); for(std::wstring::size_type current_char = 0; current_char <= original_size; ++current_char) { temp_string = upper; for(std::wstring::size_type iteration = 0; iteration <= (original_size); ++iteration) { // This routine creates duplicated entries, it can certainly be improved temp_string[current_char] = towlower(temp_string[current_char]); lower_cases.push_back(temp_string); temp_string[current_char + iteration] = towlower(temp_string[current_char + iteration]); lower_cases.push_back(temp_string); } } this->uniqueVector(lower_cases); return lower_cases; } void Permuter::printVector(std::vector<std::wstring> original) { for (std::vector<std::wstring>::iterator i = original.begin(); i != original.end(); i++) { std::wcout << *i << ENDL; } } std::wstring Permuter::to_upper(std::wstring original) { for (std::wstring::iterator it = original.begin(); it != original.end(); it++) { *it = towupper(*it); } return original; } /** * @brief Removes duplicate entries in an std::vector * * @param originalVector vector of string */ void Permuter::uniqueVector(std::vector<std::wstring> &originalVector) { sort( originalVector.begin(), originalVector.end() ); originalVector.erase( unique( originalVector.begin(), originalVector.end() ), originalVector.end() ); } /** * @brief Merges vectors * * @return A new array with the unique contents of arrays a and b */ std::vector<std::wstring> Permuter::mergeVectors(std::vector<std::wstring> a, std::vector<std::wstring> b) { std::vector<std::wstring> merged; merged.insert(merged.end(), a.begin(), a.end()); merged.insert(merged.end(), b.begin(), b.end()); this->uniqueVector(merged); return merged; } std::vector<std::wstring> Permuter::addNumbers(std::vector<std::wstring> original) { std::wstring current_word; std::wstring temp; std::vector<std::wstring> passwords; std::string the_number; int original_size; // Loop through every word for (std::vector<std::wstring>::iterator vec_iterator = original.begin(); vec_iterator != original.end(); vec_iterator++) { current_word = *vec_iterator; original_size = current_word.size(); for (std::wstring::size_type current_char = 0; current_char <= original_size; ++current_char) { for (int i = 0; i < 100; ++i) { temp = current_word.substr(0, current_char); temp += std::to_wstring(i); // + "#" + temp += current_word.substr(current_char, (original_size - current_char)); } } } return passwords; } std::vector<std::wstring> Permuter::generatePasswords(std::wstring original) { std::vector<std::wstring> passwords; std::vector<std::wstring> mixedCases = this->mixCases(original); std::vector<std::wstring> numeric = this->addNumbers(mixedCases); passwords = this->mergeVectors(mixedCases, numeric); // Remove duplicates this->uniqueVector(passwords); return passwords; } void Permuter::savePasswordsToFile(std::vector<std::wstring> words) { // std::cout << "savePermutationsToFile() -> " std::wofstream store; store.open(this->targetFile); for (std::vector<std::wstring>::iterator ite = words.begin(); ite != words.end(); ite++) { std::wcout << std::wstring(L"savePasswordsToFile(vector<string>) -> Storing: ") << *ite << ENDL; store << *ite << ENDL; } store.close(); } void Permuter::run() { if (true || this->fileExists(this->sourceFile) == true) { std::vector<std::wstring> permutations; std::cout << this->sourceFile << " <--> " << this->targetFile << ENDL; this->sourceWords = this->fileToVector(this->sourceFile); std::cout << "Total words to permute: " << this->sourceWords.size() << ENDL; for (std::vector<std::wstring>::iterator ite = this->sourceWords.begin(); ite != this->sourceWords.end(); ite++ ) { std::wcout << std::wstring(L"run() -> ") << *ite << ENDL; permutations = this->generatePasswords(*ite); this->savePasswordsToFile(permutations); } // std::cout << "permutations[0]: " << permutations[0] << ENDL; } else { std::cout << "Not everything is ok" << ENDL; } }<|endoftext|>
<commit_before>// Copyright (c) 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. // This file was forked off the Mac port. #include "webkit/tools/test_shell/test_webview_delegate.h" #include <gtk/gtk.h> #include "base/gfx/point.h" #include "base/string_util.h" #include "net/base/net_errors.h" #include "chrome/common/page_transition_types.h" #include "webkit/glue/webcursor.h" #include "webkit/glue/webdatasource.h" #include "webkit/glue/webdropdata.h" #include "webkit/glue/weberror.h" #include "webkit/glue/webframe.h" #include "webkit/glue/webpreferences.h" #include "webkit/glue/weburlrequest.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/webview.h" #include "webkit/glue/window_open_disposition.h" #include "webkit/tools/test_shell/test_navigation_controller.h" #include "webkit/tools/test_shell/test_shell.h" // WebViewDelegate ----------------------------------------------------------- TestWebViewDelegate::~TestWebViewDelegate() { } WebPluginDelegate* TestWebViewDelegate::CreatePluginDelegate( WebView* webview, const GURL& url, const std::string& mime_type, const std::string& clsid, std::string* actual_mime_type) { NOTIMPLEMENTED(); return NULL; } void TestWebViewDelegate::ShowJavaScriptAlert(const std::wstring& message) { // TODO(port): remove GTK_WINDOW bit after gfx::WindowHandle is fixed. GtkWidget* dialog = gtk_message_dialog_new( GTK_WINDOW(shell_->mainWnd()), GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "%s", WideToUTF8(message).c_str()); gtk_window_set_title(GTK_WINDOW(dialog), "JavaScript Alert"); gtk_dialog_run(GTK_DIALOG(dialog)); // Runs a nested message loop. gtk_widget_destroy(dialog); } void TestWebViewDelegate::Show(WebWidget* webwidget, WindowOpenDisposition disposition) { WebWidgetHost* host = GetHostForWidget(webwidget); GtkWidget* drawing_area = host->window_handle(); GtkWidget* window = gtk_widget_get_parent(gtk_widget_get_parent(drawing_area)); gtk_widget_show_all(window); } void TestWebViewDelegate::CloseWidgetSoon(WebWidget* webwidget) { if (webwidget == shell_->popup()) { shell_->ClosePopup(); } else { // In the Windows code, this closes the main window. However, it's not // clear when this would ever be needed by WebKit. NOTIMPLEMENTED(); } } void TestWebViewDelegate::SetCursor(WebWidget* webwidget, const WebCursor& cursor) { GdkCursorType cursor_type = cursor.GetCursorType(); GdkCursor* gdk_cursor; if (cursor_type == GDK_CURSOR_IS_PIXMAP) { // TODO(port): WebKit bug https://bugs.webkit.org/show_bug.cgi?id=16388 is // that calling gdk_window_set_cursor repeatedly is expensive. We should // avoid it here where possible. gdk_cursor = cursor.GetCustomCursor(); } else { // Optimize the common case, where the cursor hasn't changed. // However, we can switch between different pixmaps, so only on the // non-pixmap branch. if (cursor_type_ == cursor_type) return; gdk_cursor = gdk_cursor_new(cursor_type); } cursor_type_ = cursor_type; gdk_window_set_cursor(shell_->webViewWnd()->window, gdk_cursor); // The window now owns the cursor. gdk_cursor_unref(gdk_cursor); } void TestWebViewDelegate::GetWindowRect(WebWidget* webwidget, gfx::Rect* out_rect) { DCHECK(out_rect); WebWidgetHost* host = GetHostForWidget(webwidget); GtkWidget* drawing_area = host->window_handle(); GtkWidget* vbox = gtk_widget_get_parent(drawing_area); GtkWidget* window = gtk_widget_get_parent(vbox); gint x, y; gtk_window_get_position(GTK_WINDOW(window), &x, &y); x += vbox->allocation.x + drawing_area->allocation.x; y += vbox->allocation.y + drawing_area->allocation.y; out_rect->SetRect(x, y, drawing_area->allocation.width, drawing_area->allocation.height); } void TestWebViewDelegate::SetWindowRect(WebWidget* webwidget, const gfx::Rect& rect) { if (webwidget == shell_->webView()) { // ignored } else if (webwidget == shell_->popup()) { WebWidgetHost* host = GetHostForWidget(webwidget); GtkWidget* drawing_area = host->window_handle(); GtkWidget* window = gtk_widget_get_parent(gtk_widget_get_parent(drawing_area)); gtk_window_resize(GTK_WINDOW(window), rect.width(), rect.height()); gtk_window_move(GTK_WINDOW(window), rect.x(), rect.y()); } } void TestWebViewDelegate::GetRootWindowRect(WebWidget* webwidget, gfx::Rect* out_rect) { //if (WebWidgetHost* host = GetHostForWidget(webwidget)) { NOTIMPLEMENTED(); //} } void TestWebViewDelegate::RunModal(WebWidget* webwidget) { NOTIMPLEMENTED(); } // Private methods ----------------------------------------------------------- void TestWebViewDelegate::SetPageTitle(const std::wstring& title) { gtk_window_set_title(GTK_WINDOW(shell_->mainWnd()), ("Test Shell - " + WideToUTF8(title)).c_str()); } void TestWebViewDelegate::SetAddressBarURL(const GURL& url) { gtk_entry_set_text(GTK_ENTRY(shell_->editWnd()), url.spec().c_str()); } <commit_msg>Implement GetRootWindowRect, for example, window.screenX.<commit_after>// Copyright (c) 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. // This file was forked off the Mac port. #include "webkit/tools/test_shell/test_webview_delegate.h" #include <gtk/gtk.h> #include "base/gfx/point.h" #include "base/string_util.h" #include "net/base/net_errors.h" #include "chrome/common/page_transition_types.h" #include "webkit/glue/webcursor.h" #include "webkit/glue/webdatasource.h" #include "webkit/glue/webdropdata.h" #include "webkit/glue/weberror.h" #include "webkit/glue/webframe.h" #include "webkit/glue/webpreferences.h" #include "webkit/glue/weburlrequest.h" #include "webkit/glue/webkit_glue.h" #include "webkit/glue/webview.h" #include "webkit/glue/window_open_disposition.h" #include "webkit/tools/test_shell/test_navigation_controller.h" #include "webkit/tools/test_shell/test_shell.h" // WebViewDelegate ----------------------------------------------------------- TestWebViewDelegate::~TestWebViewDelegate() { } WebPluginDelegate* TestWebViewDelegate::CreatePluginDelegate( WebView* webview, const GURL& url, const std::string& mime_type, const std::string& clsid, std::string* actual_mime_type) { NOTIMPLEMENTED(); return NULL; } void TestWebViewDelegate::ShowJavaScriptAlert(const std::wstring& message) { // TODO(port): remove GTK_WINDOW bit after gfx::WindowHandle is fixed. GtkWidget* dialog = gtk_message_dialog_new( GTK_WINDOW(shell_->mainWnd()), GTK_DIALOG_MODAL, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "%s", WideToUTF8(message).c_str()); gtk_window_set_title(GTK_WINDOW(dialog), "JavaScript Alert"); gtk_dialog_run(GTK_DIALOG(dialog)); // Runs a nested message loop. gtk_widget_destroy(dialog); } void TestWebViewDelegate::Show(WebWidget* webwidget, WindowOpenDisposition disposition) { WebWidgetHost* host = GetHostForWidget(webwidget); GtkWidget* drawing_area = host->window_handle(); GtkWidget* window = gtk_widget_get_parent(gtk_widget_get_parent(drawing_area)); gtk_widget_show_all(window); } void TestWebViewDelegate::CloseWidgetSoon(WebWidget* webwidget) { if (webwidget == shell_->popup()) { shell_->ClosePopup(); } else { // In the Windows code, this closes the main window. However, it's not // clear when this would ever be needed by WebKit. NOTIMPLEMENTED(); } } void TestWebViewDelegate::SetCursor(WebWidget* webwidget, const WebCursor& cursor) { GdkCursorType cursor_type = cursor.GetCursorType(); GdkCursor* gdk_cursor; if (cursor_type == GDK_CURSOR_IS_PIXMAP) { // TODO(port): WebKit bug https://bugs.webkit.org/show_bug.cgi?id=16388 is // that calling gdk_window_set_cursor repeatedly is expensive. We should // avoid it here where possible. gdk_cursor = cursor.GetCustomCursor(); } else { // Optimize the common case, where the cursor hasn't changed. // However, we can switch between different pixmaps, so only on the // non-pixmap branch. if (cursor_type_ == cursor_type) return; gdk_cursor = gdk_cursor_new(cursor_type); } cursor_type_ = cursor_type; gdk_window_set_cursor(shell_->webViewWnd()->window, gdk_cursor); // The window now owns the cursor. gdk_cursor_unref(gdk_cursor); } void TestWebViewDelegate::GetWindowRect(WebWidget* webwidget, gfx::Rect* out_rect) { DCHECK(out_rect); WebWidgetHost* host = GetHostForWidget(webwidget); GtkWidget* drawing_area = host->window_handle(); GtkWidget* vbox = gtk_widget_get_parent(drawing_area); GtkWidget* window = gtk_widget_get_parent(vbox); gint x, y; gtk_window_get_position(GTK_WINDOW(window), &x, &y); x += vbox->allocation.x + drawing_area->allocation.x; y += vbox->allocation.y + drawing_area->allocation.y; out_rect->SetRect(x, y, drawing_area->allocation.width, drawing_area->allocation.height); } void TestWebViewDelegate::SetWindowRect(WebWidget* webwidget, const gfx::Rect& rect) { if (webwidget == shell_->webView()) { // ignored } else if (webwidget == shell_->popup()) { WebWidgetHost* host = GetHostForWidget(webwidget); GtkWidget* drawing_area = host->window_handle(); GtkWidget* window = gtk_widget_get_parent(gtk_widget_get_parent(drawing_area)); gtk_window_resize(GTK_WINDOW(window), rect.width(), rect.height()); gtk_window_move(GTK_WINDOW(window), rect.x(), rect.y()); } } void TestWebViewDelegate::GetRootWindowRect(WebWidget* webwidget, gfx::Rect* out_rect) { if (WebWidgetHost* host = GetHostForWidget(webwidget)) { // We are being asked for the x/y and width/height of the entire browser // window. This means the x/y is the distance from the corner of the // screen, and the width/height is the size of the entire browser window. // For example, this is used to implement window.screenX and window.screenY. GtkWidget* drawing_area = host->window_handle(); GtkWidget* window = gtk_widget_get_parent(gtk_widget_get_parent(drawing_area)); gint x, y, width, height; gtk_window_get_position(GTK_WINDOW(window), &x, &y); gtk_window_get_size(GTK_WINDOW(window), &width, &height); out_rect->SetRect(x, y, width, height); } } void TestWebViewDelegate::RunModal(WebWidget* webwidget) { NOTIMPLEMENTED(); } // Private methods ----------------------------------------------------------- void TestWebViewDelegate::SetPageTitle(const std::wstring& title) { gtk_window_set_title(GTK_WINDOW(shell_->mainWnd()), ("Test Shell - " + WideToUTF8(title)).c_str()); } void TestWebViewDelegate::SetAddressBarURL(const GURL& url) { gtk_entry_set_text(GTK_ENTRY(shell_->editWnd()), url.spec().c_str()); } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <print.hpp> #include <file.hpp> #include <system.hpp> #include <string.hpp> #include <algorithms.hpp> #include <errors.hpp> namespace { size_t columns = 0; size_t rows = 0; void get_console_information(){ columns = get_columns(); rows = get_rows(); } void exit_command(const std::vector<std::string>& params); void echo_command(const std::vector<std::string>& params); void sleep_command(const std::vector<std::string>& params); void clear_command(const std::vector<std::string>& params); void cd_command(const std::vector<std::string>& params); void pwd_command(const std::vector<std::string>& params); struct command_definition { const char* name; void (*function)(const std::vector<std::string>&); }; command_definition commands[6] = { {"exit", exit_command}, {"echo", echo_command}, {"sleep", sleep_command}, {"clear", clear_command}, {"cd", cd_command}, {"pwd", pwd_command}, }; void exit_command(const std::vector<std::string>&){ exit(0); } void echo_command(const std::vector<std::string>& params){ for(uint64_t i = 1; i < params.size(); ++i){ print(params[i]); print(' '); } print_line(); } void sleep_command(const std::vector<std::string>& params){ if(params.size() == 1){ print_line("sleep: missing operand"); } else { size_t time = std::parse(params[1]); sleep_ms(time * 1000); } } void clear_command(const std::vector<std::string>&){ clear(); } void cd_command(const std::vector<std::string>& params){ if(params.size() == 1){ print_line("Usage: cd file_path"); return; } auto& path = params[1]; auto fd = open(path.c_str()); if(fd.valid()){ auto info = stat(*fd); if(info.valid()){ if(!(info->flags & STAT_FLAG_DIRECTORY)){ print_line("cat: error: Is not a directory"); } else { auto cwd = current_working_directory(); if(path[0] == '/'){ cwd = "/"; } auto parts = std::split(path, '/'); for(auto& part : parts){ cwd += part; cwd += '/'; } set_current_working_directory(cwd); } } else { printf("cd: error: %s\n", std::error_message(info.error())); } close(*fd); } else { printf("cd: error: %s\n", std::error_message(fd.error())); } } void pwd_command(const std::vector<std::string>&){ auto cwd = current_working_directory(); print_line(cwd); } } //end of anonymous namespace int main(){ get_console_information(); char input_buffer[64]; std::string current_input; while(true){ print("thor> "); auto c = read_input(input_buffer, 63); if(input_buffer[c-1] == '\n'){ if(c > 1){ input_buffer[c-1] = '\0'; current_input += input_buffer; } if(current_input.size() > 0){ auto params = std::split(current_input);; bool found = false; for(auto& command : commands){ if(params[0] == command.name){ command.function(params); found = true; break; } } if(!found){ std::vector<std::string> args; if(params.size() > 1){ args.reserve(params.size() - 1); for(size_t i = 1; i < params.size(); ++i){ args.push_back(params[i]); } } auto executable = params[0]; if(executable[0] != '/'){ executable = "/bin/" + executable; } auto result = exec_and_wait(executable.c_str(), args); if(!result.valid()){ print("error: "); print_line(std::error_message(result.error())); } } } current_input.clear(); } else { input_buffer[c] = '\0'; current_input += input_buffer; } } __builtin_unreachable(); }<commit_msg>Add more information on error<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2014. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <print.hpp> #include <file.hpp> #include <system.hpp> #include <string.hpp> #include <algorithms.hpp> #include <errors.hpp> namespace { size_t columns = 0; size_t rows = 0; void get_console_information(){ columns = get_columns(); rows = get_rows(); } void exit_command(const std::vector<std::string>& params); void echo_command(const std::vector<std::string>& params); void sleep_command(const std::vector<std::string>& params); void clear_command(const std::vector<std::string>& params); void cd_command(const std::vector<std::string>& params); void pwd_command(const std::vector<std::string>& params); struct command_definition { const char* name; void (*function)(const std::vector<std::string>&); }; command_definition commands[6] = { {"exit", exit_command}, {"echo", echo_command}, {"sleep", sleep_command}, {"clear", clear_command}, {"cd", cd_command}, {"pwd", pwd_command}, }; void exit_command(const std::vector<std::string>&){ exit(0); } void echo_command(const std::vector<std::string>& params){ for(uint64_t i = 1; i < params.size(); ++i){ print(params[i]); print(' '); } print_line(); } void sleep_command(const std::vector<std::string>& params){ if(params.size() == 1){ print_line("sleep: missing operand"); } else { size_t time = std::parse(params[1]); sleep_ms(time * 1000); } } void clear_command(const std::vector<std::string>&){ clear(); } void cd_command(const std::vector<std::string>& params){ if(params.size() == 1){ print_line("Usage: cd file_path"); return; } auto& path = params[1]; auto fd = open(path.c_str()); if(fd.valid()){ auto info = stat(*fd); if(info.valid()){ if(!(info->flags & STAT_FLAG_DIRECTORY)){ print_line("cat: error: Is not a directory"); } else { auto cwd = current_working_directory(); if(path[0] == '/'){ cwd = "/"; } auto parts = std::split(path, '/'); for(auto& part : parts){ cwd += part; cwd += '/'; } set_current_working_directory(cwd); } } else { printf("cd: error: %s\n", std::error_message(info.error())); } close(*fd); } else { printf("cd: error: %s\n", std::error_message(fd.error())); } } void pwd_command(const std::vector<std::string>&){ auto cwd = current_working_directory(); print_line(cwd); } } //end of anonymous namespace int main(){ get_console_information(); char input_buffer[64]; std::string current_input; while(true){ print("thor> "); auto c = read_input(input_buffer, 63); if(input_buffer[c-1] == '\n'){ if(c > 1){ input_buffer[c-1] = '\0'; current_input += input_buffer; } if(current_input.size() > 0){ auto params = std::split(current_input);; bool found = false; for(auto& command : commands){ if(params[0] == command.name){ command.function(params); found = true; break; } } if(!found){ std::vector<std::string> args; if(params.size() > 1){ args.reserve(params.size() - 1); for(size_t i = 1; i < params.size(); ++i){ args.push_back(params[i]); } } auto executable = params[0]; if(executable[0] != '/'){ executable = "/bin/" + executable; } auto result = exec_and_wait(executable.c_str(), args); if(!result.valid()){ print("error: "); print_line(std::error_message(result.error())); print("command: \""); print(current_input); print_line("\""); } } } current_input.clear(); } else { input_buffer[c] = '\0'; current_input += input_buffer; } } __builtin_unreachable(); }<|endoftext|>
<commit_before>#include "aquila/global.h" #include "aquila/source/SignalSource.h" #include "aquila/source/Frame.h" #include "aquila/source/FramesCollection.h" #include <unittestpp.h> #include <algorithm> bool equalSamples(Aquila::Frame frame, Aquila::SampleType arr[]) { return std::equal(std::begin(frame), std::end(frame), arr); } SUITE(FramesCollection) { const int SIZE = 10; Aquila::SampleType testArray[SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; Aquila::FrequencyType sampleFrequency = 100; Aquila::SignalSource data(testArray, SIZE, sampleFrequency); TEST(Empty) { Aquila::FramesCollection frames; CHECK_EQUAL(0u, frames.count()); } TEST(EmptyWhenZeroSamples) { Aquila::FramesCollection frames(data, 0); CHECK_EQUAL(0u, frames.count()); } TEST(FiveSamplesPerFrame) { Aquila::FramesCollection frames(data, 5); CHECK_EQUAL(2u, frames.count()); Aquila::SampleType arr0[5] = {0, 1, 2, 3, 4}; CHECK(equalSamples(frames.frame(0), arr0)); Aquila::SampleType arr1[5] = {5, 6, 7, 8, 9}; CHECK(equalSamples(frames.frame(1), arr1)); } TEST(TwoSamplesPerFrame) { Aquila::FramesCollection frames(data, 2); CHECK_EQUAL(5u, frames.count()); Aquila::SampleType arr[2] = {0, 1}; CHECK(equalSamples(frames.frame(0), arr)); } TEST(OneSamplePerFrame) { Aquila::FramesCollection frames(data, 1); CHECK_EQUAL(10u, frames.count()); Aquila::SampleType arr[1] = {0}; CHECK(equalSamples(frames.frame(0), arr)); } TEST(AllSamplesPerFrame) { Aquila::FramesCollection frames(data, 10); CHECK_EQUAL(1u, frames.count()); Aquila::SampleType arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; CHECK(equalSamples(frames.frame(0), arr)); } TEST(MoreThanHalfSamplesPerFrame) { Aquila::FramesCollection frames(data, 7); CHECK_EQUAL(1u, frames.count()); Aquila::SampleType arr[7] = {0, 1, 2, 3, 4, 5, 6}; CHECK(equalSamples(frames.frame(0), arr)); } TEST(TooManySamplesPerFrame) { Aquila::FramesCollection frames(data, 11); CHECK_EQUAL(0u, frames.count()); } TEST(Duration) { // sampling at 100 Hz -> 10 miliseconds is 1 sample auto frames = Aquila::FramesCollection::createFromDuration(data, 10); CHECK_EQUAL(10u, frames.count()); } TEST(Duration2) { // sampling at 100 Hz -> 50 miliseconds is 5 samples auto frames = Aquila::FramesCollection::createFromDuration(data, 50); CHECK_EQUAL(2u, frames.count()); } TEST(DurationWithOverlap) { // sampling at 100 Hz -> 50 miliseconds is 5 samples // 80% overlap -> 4 common samples between consecutive frames // frame data: 0 1 2 3 4 5 6 7 8 9 // frame 0: | | // frame 1: | | // frame 2: | | // frame 3: | | // frame 4: | | // frame 5: | | auto frames = Aquila::FramesCollection::createFromDuration(data, 50, 0.8); CHECK_EQUAL(6u, frames.count()); } TEST(ApplySimpleFunction) { Aquila::FramesCollection frames(data, 5); auto energies = frames.apply<double>(Aquila::mean); double expected[2] = {2.0, 7.0}; CHECK_ARRAY_CLOSE(expected, energies, 2, 0.000001); } } <commit_msg>Check that we can apply lambda functions to FramesCollection.<commit_after>#include "aquila/global.h" #include "aquila/source/SignalSource.h" #include "aquila/source/Frame.h" #include "aquila/source/FramesCollection.h" #include <unittestpp.h> #include <algorithm> bool equalSamples(Aquila::Frame frame, Aquila::SampleType arr[]) { return std::equal(std::begin(frame), std::end(frame), arr); } SUITE(FramesCollection) { const int SIZE = 10; Aquila::SampleType testArray[SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; Aquila::FrequencyType sampleFrequency = 100; Aquila::SignalSource data(testArray, SIZE, sampleFrequency); TEST(Empty) { Aquila::FramesCollection frames; CHECK_EQUAL(0u, frames.count()); } TEST(EmptyWhenZeroSamples) { Aquila::FramesCollection frames(data, 0); CHECK_EQUAL(0u, frames.count()); } TEST(FiveSamplesPerFrame) { Aquila::FramesCollection frames(data, 5); CHECK_EQUAL(2u, frames.count()); Aquila::SampleType arr0[5] = {0, 1, 2, 3, 4}; CHECK(equalSamples(frames.frame(0), arr0)); Aquila::SampleType arr1[5] = {5, 6, 7, 8, 9}; CHECK(equalSamples(frames.frame(1), arr1)); } TEST(TwoSamplesPerFrame) { Aquila::FramesCollection frames(data, 2); CHECK_EQUAL(5u, frames.count()); Aquila::SampleType arr[2] = {0, 1}; CHECK(equalSamples(frames.frame(0), arr)); } TEST(OneSamplePerFrame) { Aquila::FramesCollection frames(data, 1); CHECK_EQUAL(10u, frames.count()); Aquila::SampleType arr[1] = {0}; CHECK(equalSamples(frames.frame(0), arr)); } TEST(AllSamplesPerFrame) { Aquila::FramesCollection frames(data, 10); CHECK_EQUAL(1u, frames.count()); Aquila::SampleType arr[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; CHECK(equalSamples(frames.frame(0), arr)); } TEST(MoreThanHalfSamplesPerFrame) { Aquila::FramesCollection frames(data, 7); CHECK_EQUAL(1u, frames.count()); Aquila::SampleType arr[7] = {0, 1, 2, 3, 4, 5, 6}; CHECK(equalSamples(frames.frame(0), arr)); } TEST(TooManySamplesPerFrame) { Aquila::FramesCollection frames(data, 11); CHECK_EQUAL(0u, frames.count()); } TEST(Duration) { // sampling at 100 Hz -> 10 miliseconds is 1 sample auto frames = Aquila::FramesCollection::createFromDuration(data, 10); CHECK_EQUAL(10u, frames.count()); } TEST(Duration2) { // sampling at 100 Hz -> 50 miliseconds is 5 samples auto frames = Aquila::FramesCollection::createFromDuration(data, 50); CHECK_EQUAL(2u, frames.count()); } TEST(DurationWithOverlap) { // sampling at 100 Hz -> 50 miliseconds is 5 samples // 80% overlap -> 4 common samples between consecutive frames // frame data: 0 1 2 3 4 5 6 7 8 9 // frame 0: | | // frame 1: | | // frame 2: | | // frame 3: | | // frame 4: | | // frame 5: | | auto frames = Aquila::FramesCollection::createFromDuration(data, 50, 0.8); CHECK_EQUAL(6u, frames.count()); } TEST(ApplySimpleFunction) { Aquila::FramesCollection frames(data, 5); auto energies = frames.apply<double>(Aquila::mean); double expected[2] = {2.0, 7.0}; CHECK_ARRAY_CLOSE(expected, energies, 2, 0.000001); } TEST(ApplyLambda) { Aquila::FramesCollection frames(data, 5); auto maximums = frames.apply<Aquila::SampleType>( [&](const Aquila::SignalSource& s) { return *std::max_element(s.begin(), s.end()); } ); Aquila::SampleType expected[2] = {4.0, 9.0}; CHECK_ARRAY_CLOSE(expected, maximums, 2, 0.000001); } } <|endoftext|>
<commit_before>#include "Hardware.h" #define PIN_LED_R 14 #define PIN_LED_G 13 #define PIN_LED_B 10 #define PIN_MOTOR_I_PWM 22 #define PIN_MOTOR_I_DIR 27 #define PIN_MOTOR_J_PWM 24 #define PIN_MOTOR_J_DIR 28 #define PIN_MOTOR_K_PWM 25 #define PIN_MOTOR_K_DIR 29 #define PIN_LINE_LED 12 #define PIN_BUZZER 11 const int Hardware::LINE_SENSORS[] = {6,7,5,3,4,2,0,1}; Hardware::Hardware() { wiringPiSetup(); /// initialize LED software pwms softPwmCreate(PIN_LED_R,0,255); softPwmCreate(PIN_LED_G,0,255); softPwmCreate(PIN_LED_B,0,255); /// initialize motor software pwms softPwmCreate(PIN_MOTOR_I_PWM,0,100); softPwmCreate(PIN_MOTOR_J_PWM,0,100); softPwmCreate(PIN_MOTOR_K_PWM,0,100); /// initialize motor direction outputs pinMode(PIN_MOTOR_I_DIR,OUTPUT); pinMode(PIN_MOTOR_J_DIR,OUTPUT); pinMode(PIN_MOTOR_K_DIR,OUTPUT); // initialize line sensor array LED pinMode(PIN_LINE_LED,OUTPUT); // open serial line serialFileDesc = serialOpen("/dev/ttyAMA0",115200); // initialize buzzer softToneCreate(PIN_BUZZER); } void Hardware::setLED(int r, int g, int b) { softPwmWrite(PIN_LED_R,r); softPwmWrite(PIN_LED_G,g); softPwmWrite(PIN_LED_B,b); } int Hardware::readLine() { digitalWrite(PIN_LINE_LED,1); usleep(200); long long longest = 0; int longPin = 0; for (int i=0; i<8; i++) { long long iTime = (readLineSensor(LINE_SENSORS[i]) + readLineSensor(LINE_SENSORS[i]))/2; if (iTime > longest) { longest = iTime; longPin = i; } } return longPin; } long long Hardware::readLineSensor(int i) { pinMode(i,OUTPUT); digitalWrite(i,1); usleep(10); pinMode(i,INPUT); pullUpDnControl(i,PUD_OFF); auto start = std::chrono::high_resolution_clock::now(); while (digitalRead(i)); auto elapsed = std::chrono::high_resolution_clock::now() - start; return std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); } void Hardware::goHolonomic(int x, int y) { double i = x/2 + y*sqrt(3)/2; double j = x/2 - y*sqrt(3)/2; double k = x; setMotors(i,j,k); } void Hardware::setMotors(int i, int j, int k) { digitalWrite(PIN_MOTOR_I_DIR,i>0); softPwmWrite(PIN_MOTOR_I_PWM,abs(i)); digitalWrite(PIN_MOTOR_J_DIR,j>0); softPwmWrite(PIN_MOTOR_J_PWM,abs(j)); digitalWrite(PIN_MOTOR_K_DIR,k<0); softPwmWrite(PIN_MOTOR_K_PWM,abs(k)); } void Hardware::getZX(int& z, int& x) { serialFlush(serialFileDesc); while (serialGetchar(serialFileDesc) != 0xFA); x = serialGetchar(serialFileDesc) - 120; while (serialGetchar(serialFileDesc) != 0xFB); z = serialGetchar(serialFileDesc); } void Hardware::setBuzzer(int freq) { softToneWrite(PIN_BUZZER,freq); } Hardware::~Hardware() { setLED(0,0,0); setMotors(0,0,0); digitalWrite(PIN_LINE_LED,0); serialClose(serialFileDesc); setBuzzer(0); usleep(100000); } <commit_msg>flip y axis<commit_after>#include "Hardware.h" #define PIN_LED_R 14 #define PIN_LED_G 13 #define PIN_LED_B 10 #define PIN_MOTOR_I_PWM 22 #define PIN_MOTOR_I_DIR 27 #define PIN_MOTOR_J_PWM 24 #define PIN_MOTOR_J_DIR 28 #define PIN_MOTOR_K_PWM 25 #define PIN_MOTOR_K_DIR 29 #define PIN_LINE_LED 12 #define PIN_BUZZER 11 const int Hardware::LINE_SENSORS[] = {6,7,5,3,4,2,0,1}; Hardware::Hardware() { wiringPiSetup(); /// initialize LED software pwms softPwmCreate(PIN_LED_R,0,255); softPwmCreate(PIN_LED_G,0,255); softPwmCreate(PIN_LED_B,0,255); /// initialize motor software pwms softPwmCreate(PIN_MOTOR_I_PWM,0,100); softPwmCreate(PIN_MOTOR_J_PWM,0,100); softPwmCreate(PIN_MOTOR_K_PWM,0,100); /// initialize motor direction outputs pinMode(PIN_MOTOR_I_DIR,OUTPUT); pinMode(PIN_MOTOR_J_DIR,OUTPUT); pinMode(PIN_MOTOR_K_DIR,OUTPUT); // initialize line sensor array LED pinMode(PIN_LINE_LED,OUTPUT); // open serial line serialFileDesc = serialOpen("/dev/ttyAMA0",115200); // initialize buzzer softToneCreate(PIN_BUZZER); } void Hardware::setLED(int r, int g, int b) { softPwmWrite(PIN_LED_R,r); softPwmWrite(PIN_LED_G,g); softPwmWrite(PIN_LED_B,b); } int Hardware::readLine() { digitalWrite(PIN_LINE_LED,1); usleep(200); long long longest = 0; int longPin = 0; for (int i=0; i<8; i++) { long long iTime = (readLineSensor(LINE_SENSORS[i]) + readLineSensor(LINE_SENSORS[i]))/2; if (iTime > longest) { longest = iTime; longPin = i; } } return longPin; } long long Hardware::readLineSensor(int i) { pinMode(i,OUTPUT); digitalWrite(i,1); usleep(10); pinMode(i,INPUT); pullUpDnControl(i,PUD_OFF); auto start = std::chrono::high_resolution_clock::now(); while (digitalRead(i)); auto elapsed = std::chrono::high_resolution_clock::now() - start; return std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count(); } void Hardware::goHolonomic(int x, int y) { double i = x/2 - y*sqrt(3)/2; double j = x/2 + y*sqrt(3)/2; double k = x; setMotors(i,j,k); } void Hardware::setMotors(int i, int j, int k) { digitalWrite(PIN_MOTOR_I_DIR,i>0); softPwmWrite(PIN_MOTOR_I_PWM,abs(i)); digitalWrite(PIN_MOTOR_J_DIR,j>0); softPwmWrite(PIN_MOTOR_J_PWM,abs(j)); digitalWrite(PIN_MOTOR_K_DIR,k<0); softPwmWrite(PIN_MOTOR_K_PWM,abs(k)); } void Hardware::getZX(int& z, int& x) { serialFlush(serialFileDesc); while (serialGetchar(serialFileDesc) != 0xFA); x = serialGetchar(serialFileDesc) - 120; while (serialGetchar(serialFileDesc) != 0xFB); z = serialGetchar(serialFileDesc); } void Hardware::setBuzzer(int freq) { softToneWrite(PIN_BUZZER,freq); } Hardware::~Hardware() { setLED(0,0,0); setMotors(0,0,0); digitalWrite(PIN_LINE_LED,0); serialClose(serialFileDesc); setBuzzer(0); usleep(100000); } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include "agent.h" #include "../test_context.h" #include "../test_agents/test_agent.h" namespace cyclus { namespace toolkit { TEST(TimeSeriesTests, Power) { TestContext tc; Agent* a = new TestAgent(tc.get()); RecordTimeSeries<POWER>(a, 42.0); } TEST(TimeSeriesTests, RawPower) { TestContext tc; Agent* a = new TestAgent(tc.get()); RecordTimeSeries<double>("Power", a, 42.0); } } // namespace toolkit } // namespace cyclus <commit_msg>clean up agents<commit_after>#include <gtest/gtest.h> #include "agent.h" #include "../test_context.h" #include "../test_agents/test_agent.h" namespace cyclus { namespace toolkit { TEST(TimeSeriesTests, Power) { TestContext tc; Agent* a = new TestAgent(tc.get()); RecordTimeSeries<POWER>(a, 42.0); delete a; } TEST(TimeSeriesTests, RawPower) { TestContext tc; Agent* a = new TestAgent(tc.get()); RecordTimeSeries<double>("Power", a, 42.0); delete a; } } // namespace toolkit } // namespace cyclus <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // File: NekConstantSizedVector.hpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Constant sized and variable sized vectors have the same interface // and performt he same algorithms - the only real difference is how // the data is stored. These methods allow use to use the same // algorithm regardless of data storage mechanism. // /////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_VECTOR_COMMON_HPP #define NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_VECTOR_COMMON_HPP #include <LibUtilities/LinearAlgebra/NekVectorFwd.hpp> #include <LibUtilities/LinearAlgebra/NekVectorTypeTraits.hpp> namespace Nektar { template<typename DataType> std::vector<DataType> FromString(const std::string& str) { std::vector<DataType> result; try { typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep("(<,>) "); tokenizer tokens(str, sep); for( tokenizer::iterator strIter = tokens.begin(); strIter != tokens.end(); ++strIter) { result.push_back(boost::lexical_cast<DataType>(*strIter)); } } catch(boost::bad_lexical_cast&) { } return result; } /// \todo Do the Norms with Blas where applicable. template<typename DataType, typename dim, typename space> DataType L1Norm(const NekVector<const DataType, dim, space>& v) { typedef NekVector<DataType, dim, space> VectorType; DataType result(0); for(typename VectorType::const_iterator iter = v.begin(); iter != v.end(); ++iter) { result += NekVectorTypeTraits<DataType>::abs(*iter); } return result; } template<typename DataType, typename dim, typename space> DataType L2Norm(const NekVector<const DataType, dim, space>& v) { typedef NekVector<DataType, dim, space> VectorType; DataType result(0); for(typename VectorType::const_iterator iter = v.begin(); iter != v.end(); ++iter) { DataType v = NekVectorTypeTraits<DataType>::abs(*iter); result += v*v; } return sqrt(result); } template<typename DataType, typename dim, typename space> DataType InfinityNorm(const NekVector<const DataType, dim, space>& v) { DataType result = NekVectorTypeTraits<DataType>::abs(v[0]); for(unsigned int i = 1; i < v.GetDimension(); ++i) { result = std::max(NekVectorTypeTraits<DataType>::abs(v[i]), result); } return result; } template<typename DataType, typename dim, typename space> NekVector<DataType, dim, space> Negate(const NekVector<const DataType, dim, space>& v) { NekVector<DataType, dim, space> temp(v); for(unsigned int i=0; i < temp.GetDimension(); ++i) { temp(i) = -temp(i); } return temp; } template<typename DataType, typename dim, typename space> void PlusEqual(NekVector<DataType, dim, space>& lhs, const NekVector<const DataType, dim, space>& rhs) { ASSERTL1(lhs.GetDimension() == rhs.GetDimension(), "Two vectors must have the same size in PlusEqual.") DataType* lhs_buf = lhs.GetRawPtr(); const DataType* rhs_buf = rhs.GetRawPtr(); for(unsigned int i=0; i < lhs.GetDimension(); ++i) { lhs_buf[i] += rhs_buf[i]; } } template<typename DataType, typename dim, typename space> void MinusEqual(NekVector<DataType, dim, space>& lhs, const NekVector<const DataType, dim, space>& rhs) { ASSERTL1(lhs.GetDimension() == rhs.GetDimension(), "Two vectors must have the same size in MinusEqual.") for(unsigned int i=0; i < lhs.GetDimension(); ++i) { lhs[i] -= rhs[i]; } } template<typename DataType, typename dim, typename space> void TimesEqual(NekVector<DataType, dim, space>& lhs, const DataType& rhs) { for(unsigned int i=0; i < lhs.GetDimension(); ++i) { lhs[i] *= rhs; } } template<typename DataType, typename dim, typename space> void DivideEqual(NekVector<DataType, dim, space>& lhs, const DataType& rhs) { for(unsigned int i=0; i < lhs.GetDimension(); ++i) { lhs[i] /= rhs; } } template<typename DataType, typename dim, typename space> DataType Magnitude(const NekVector<const DataType, dim, space>& v) { DataType result = DataType(0); for(unsigned int i = 0; i < v.GetDimension(); ++i) { result += v[i]*v[i]; } return sqrt(result); } template<typename DataType, typename dim, typename space> DataType Dot(const NekVector<const DataType, dim, space>& lhs, const NekVector<const DataType, dim, space>& rhs) { ASSERTL1( lhs.GetDimension() == rhs.GetDimension(), "Dot, dimension of the two operands must be identical."); DataType result = DataType(0); for(unsigned int i = 0; i < lhs.GetDimension(); ++i) { result += lhs[i]*rhs[i]; } return result; } template<typename DataType, typename dim, typename space> void Normalize(NekVector<DataType, dim, space>& v) { DataType m = v.Magnitude(); if( m > DataType(0) ) { v /= m; } } template<typename DataType, typename dim, typename space> NekVector<DataType, dim, space> Cross(const NekVector<const DataType, dim, space>& lhs, const NekVector<const DataType, dim, space>& rhs) { BOOST_STATIC_ASSERT(dim::Value==3 || dim::Value == 0); ASSERTL1(lhs.GetDimension() == 3 && rhs.GetDimension() == 3, "Cross is only valid for 3D vectors."); DataType first = lhs.y()*rhs.z() - lhs.z()*rhs.y(); DataType second = lhs.z()*rhs.x() - lhs.x()*rhs.z(); DataType third = lhs.x()*rhs.y() - lhs.y()*rhs.x(); NekVector<DataType, dim, space> result(first, second, third); return result; } template<typename DataType, typename dim, typename space> std::string AsString(const NekVector<DataType, dim, space>& v) { unsigned int d = v.GetRows(); std::string result = "("; for(unsigned int i = 0; i < d; ++i) { result += boost::lexical_cast<std::string>(v[i]); if( i < v.GetDimension()-1 ) { result += ", "; } } result += ")"; return result; } } #endif //NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_VECTOR_COMMON_HPP <commit_msg>Added missing semicolon at line 135.<commit_after>/////////////////////////////////////////////////////////////////////////////// // // File: NekConstantSizedVector.hpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Constant sized and variable sized vectors have the same interface // and performt he same algorithms - the only real difference is how // the data is stored. These methods allow use to use the same // algorithm regardless of data storage mechanism. // /////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_VECTOR_COMMON_HPP #define NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_VECTOR_COMMON_HPP #include <LibUtilities/LinearAlgebra/NekVectorFwd.hpp> #include <LibUtilities/LinearAlgebra/NekVectorTypeTraits.hpp> namespace Nektar { template<typename DataType> std::vector<DataType> FromString(const std::string& str) { std::vector<DataType> result; try { typedef boost::tokenizer<boost::char_separator<char> > tokenizer; boost::char_separator<char> sep("(<,>) "); tokenizer tokens(str, sep); for( tokenizer::iterator strIter = tokens.begin(); strIter != tokens.end(); ++strIter) { result.push_back(boost::lexical_cast<DataType>(*strIter)); } } catch(boost::bad_lexical_cast&) { } return result; } /// \todo Do the Norms with Blas where applicable. template<typename DataType, typename dim, typename space> DataType L1Norm(const NekVector<const DataType, dim, space>& v) { typedef NekVector<DataType, dim, space> VectorType; DataType result(0); for(typename VectorType::const_iterator iter = v.begin(); iter != v.end(); ++iter) { result += NekVectorTypeTraits<DataType>::abs(*iter); } return result; } template<typename DataType, typename dim, typename space> DataType L2Norm(const NekVector<const DataType, dim, space>& v) { typedef NekVector<DataType, dim, space> VectorType; DataType result(0); for(typename VectorType::const_iterator iter = v.begin(); iter != v.end(); ++iter) { DataType v = NekVectorTypeTraits<DataType>::abs(*iter); result += v*v; } return sqrt(result); } template<typename DataType, typename dim, typename space> DataType InfinityNorm(const NekVector<const DataType, dim, space>& v) { DataType result = NekVectorTypeTraits<DataType>::abs(v[0]); for(unsigned int i = 1; i < v.GetDimension(); ++i) { result = std::max(NekVectorTypeTraits<DataType>::abs(v[i]), result); } return result; } template<typename DataType, typename dim, typename space> NekVector<DataType, dim, space> Negate(const NekVector<const DataType, dim, space>& v) { NekVector<DataType, dim, space> temp(v); for(unsigned int i=0; i < temp.GetDimension(); ++i) { temp(i) = -temp(i); } return temp; } template<typename DataType, typename dim, typename space> void PlusEqual(NekVector<DataType, dim, space>& lhs, const NekVector<const DataType, dim, space>& rhs) { ASSERTL1(lhs.GetDimension() == rhs.GetDimension(), "Two vectors must have the same size in PlusEqual.") DataType* lhs_buf = lhs.GetRawPtr(); const DataType* rhs_buf = rhs.GetRawPtr(); for(unsigned int i=0; i < lhs.GetDimension(); ++i) { lhs_buf[i] += rhs_buf[i]; } } template<typename DataType, typename dim, typename space> void MinusEqual(NekVector<DataType, dim, space>& lhs, const NekVector<const DataType, dim, space>& rhs) { ASSERTL1(lhs.GetDimension() == rhs.GetDimension(), "Two vectors must have the same size in MinusEqual."); for(unsigned int i=0; i < lhs.GetDimension(); ++i) { lhs[i] -= rhs[i]; } } template<typename DataType, typename dim, typename space> void TimesEqual(NekVector<DataType, dim, space>& lhs, const DataType& rhs) { for(unsigned int i=0; i < lhs.GetDimension(); ++i) { lhs[i] *= rhs; } } template<typename DataType, typename dim, typename space> void DivideEqual(NekVector<DataType, dim, space>& lhs, const DataType& rhs) { for(unsigned int i=0; i < lhs.GetDimension(); ++i) { lhs[i] /= rhs; } } template<typename DataType, typename dim, typename space> DataType Magnitude(const NekVector<const DataType, dim, space>& v) { DataType result = DataType(0); for(unsigned int i = 0; i < v.GetDimension(); ++i) { result += v[i]*v[i]; } return sqrt(result); } template<typename DataType, typename dim, typename space> DataType Dot(const NekVector<const DataType, dim, space>& lhs, const NekVector<const DataType, dim, space>& rhs) { ASSERTL1( lhs.GetDimension() == rhs.GetDimension(), "Dot, dimension of the two operands must be identical."); DataType result = DataType(0); for(unsigned int i = 0; i < lhs.GetDimension(); ++i) { result += lhs[i]*rhs[i]; } return result; } template<typename DataType, typename dim, typename space> void Normalize(NekVector<DataType, dim, space>& v) { DataType m = v.Magnitude(); if( m > DataType(0) ) { v /= m; } } template<typename DataType, typename dim, typename space> NekVector<DataType, dim, space> Cross(const NekVector<const DataType, dim, space>& lhs, const NekVector<const DataType, dim, space>& rhs) { BOOST_STATIC_ASSERT(dim::Value==3 || dim::Value == 0); ASSERTL1(lhs.GetDimension() == 3 && rhs.GetDimension() == 3, "Cross is only valid for 3D vectors."); DataType first = lhs.y()*rhs.z() - lhs.z()*rhs.y(); DataType second = lhs.z()*rhs.x() - lhs.x()*rhs.z(); DataType third = lhs.x()*rhs.y() - lhs.y()*rhs.x(); NekVector<DataType, dim, space> result(first, second, third); return result; } template<typename DataType, typename dim, typename space> std::string AsString(const NekVector<DataType, dim, space>& v) { unsigned int d = v.GetRows(); std::string result = "("; for(unsigned int i = 0; i < d; ++i) { result += boost::lexical_cast<std::string>(v[i]); if( i < v.GetDimension()-1 ) { result += ", "; } } result += ")"; return result; } } #endif //NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_VECTOR_COMMON_HPP <|endoftext|>
<commit_before>#include "CascadeClassifierWrap.h" #include "OpenCV.h" #include "Matrix.h" #include <nan.h> Persistent<FunctionTemplate> CascadeClassifierWrap::constructor; void CascadeClassifierWrap::Init(Handle<Object> target) { NanScope(); Local<FunctionTemplate> ctor = NanNew<FunctionTemplate>(CascadeClassifierWrap::New); NanAssignPersistent(constructor, ctor); ctor->InstanceTemplate()->SetInternalFieldCount(1); ctor->SetClassName(NanNew("CascadeClassifier")); // Prototype //Local<ObjectTemplate> proto = constructor->PrototypeTemplate(); NODE_SET_PROTOTYPE_METHOD(ctor, "detectMultiScale", DetectMultiScale); target->Set(NanNew("CascadeClassifier"), ctor->GetFunction()); }; NAN_METHOD(CascadeClassifierWrap::New) { NanScope(); if (args.This()->InternalFieldCount() == 0) NanThrowTypeError("Cannot instantiate without new"); CascadeClassifierWrap *pt = new CascadeClassifierWrap(*args[0]); pt->Wrap(args.This()); NanReturnValue( args.This() ); } CascadeClassifierWrap::CascadeClassifierWrap(v8::Value* fileName){ std::string filename; filename = std::string(*NanAsciiString(fileName->ToString())); if (!cc.load(filename.c_str())){ NanThrowTypeError("Error loading file"); } } class AsyncDetectMultiScale : public NanAsyncWorker { public: AsyncDetectMultiScale(NanCallback *callback, CascadeClassifierWrap *cc, Matrix* im, double scale, int neighbors, int minw, int minh) : NanAsyncWorker(callback), cc(cc), im(im), scale(scale), neighbors(neighbors), minw(minw), minh(minh) {} ~AsyncDetectMultiScale() {} void Execute () { try { std::vector<cv::Rect> objects; cv::Mat gray; if(this->im->mat.channels() != 1) { cvtColor(this->im->mat, gray, CV_BGR2GRAY); } else { gray = this->im->mat; } equalizeHist( gray, gray); this->cc->cc.detectMultiScale(gray, objects, this->scale, this->neighbors, 0 | CV_HAAR_SCALE_IMAGE, cv::Size(this->minw, this->minh)); res = objects; } catch( cv::Exception& e ){ SetErrorMessage(e.what()); } } void HandleOKCallback () { NanScope(); // this->matrix->Unref(); Handle<Value> argv[2]; v8::Local<v8::Array> arr = NanNew<v8::Array>(this->res.size()); for(unsigned int i = 0; i < this->res.size(); i++ ){ v8::Local<v8::Object> x = NanNew<v8::Object>(); x->Set(NanNew("x"), NanNew<Number>(this->res[i].x)); x->Set(NanNew("y"), NanNew<Number>(this->res[i].y)); x->Set(NanNew("width"), NanNew<Number>(this->res[i].width)); x->Set(NanNew("height"), NanNew<Number>(this->res[i].height)); arr->Set(i, x); } argv[0] = NanNull(); argv[1] = arr; TryCatch try_catch; callback->Call(2, argv); if (try_catch.HasCaught()) { FatalException(try_catch); } } private: CascadeClassifierWrap *cc; Matrix* im; double scale; int neighbors; int minw; int minh; std::vector<cv::Rect> res; }; NAN_METHOD(CascadeClassifierWrap::DetectMultiScale){ NanScope(); CascadeClassifierWrap *self = ObjectWrap::Unwrap<CascadeClassifierWrap>(args.This()); if (args.Length() < 2){ NanThrowTypeError("detectMultiScale takes at least 2 args"); } Matrix *im = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject()); REQ_FUN_ARG(1, cb); double scale = 1.1; if (args.Length() > 2 && args[2]->IsNumber()) scale = args[2]->NumberValue(); int neighbors = 2; if (args.Length() > 3 && args[3]->IsInt32()) neighbors = args[3]->IntegerValue(); int minw = 30; int minh = 30; if (args.Length() > 5 && args[4]->IsInt32() && args[5]->IsInt32()){ minw = args[4]->IntegerValue(); minh = args[5]->IntegerValue(); } NanCallback *callback = new NanCallback(cb.As<Function>()); NanAsyncQueueWorker( new AsyncDetectMultiScale(callback, self, im, scale, neighbors, minw, minh) ); NanReturnUndefined(); } <commit_msg>Only run equalizeHist() if an BGR matrix was provided<commit_after>#include "CascadeClassifierWrap.h" #include "OpenCV.h" #include "Matrix.h" #include <nan.h> Persistent<FunctionTemplate> CascadeClassifierWrap::constructor; void CascadeClassifierWrap::Init(Handle<Object> target) { NanScope(); Local<FunctionTemplate> ctor = NanNew<FunctionTemplate>(CascadeClassifierWrap::New); NanAssignPersistent(constructor, ctor); ctor->InstanceTemplate()->SetInternalFieldCount(1); ctor->SetClassName(NanNew("CascadeClassifier")); // Prototype //Local<ObjectTemplate> proto = constructor->PrototypeTemplate(); NODE_SET_PROTOTYPE_METHOD(ctor, "detectMultiScale", DetectMultiScale); target->Set(NanNew("CascadeClassifier"), ctor->GetFunction()); }; NAN_METHOD(CascadeClassifierWrap::New) { NanScope(); if (args.This()->InternalFieldCount() == 0) NanThrowTypeError("Cannot instantiate without new"); CascadeClassifierWrap *pt = new CascadeClassifierWrap(*args[0]); pt->Wrap(args.This()); NanReturnValue( args.This() ); } CascadeClassifierWrap::CascadeClassifierWrap(v8::Value* fileName){ std::string filename; filename = std::string(*NanAsciiString(fileName->ToString())); if (!cc.load(filename.c_str())){ NanThrowTypeError("Error loading file"); } } class AsyncDetectMultiScale : public NanAsyncWorker { public: AsyncDetectMultiScale(NanCallback *callback, CascadeClassifierWrap *cc, Matrix* im, double scale, int neighbors, int minw, int minh) : NanAsyncWorker(callback), cc(cc), im(im), scale(scale), neighbors(neighbors), minw(minw), minh(minh) {} ~AsyncDetectMultiScale() {} void Execute () { try { std::vector<cv::Rect> objects; cv::Mat gray; if(this->im->mat.channels() != 1) { cvtColor(this->im->mat, gray, CV_BGR2GRAY); equalizeHist( gray, gray); } else { gray = this->im->mat; } this->cc->cc.detectMultiScale(gray, objects, this->scale, this->neighbors, 0 | CV_HAAR_SCALE_IMAGE, cv::Size(this->minw, this->minh)); res = objects; } catch( cv::Exception& e ){ SetErrorMessage(e.what()); } } void HandleOKCallback () { NanScope(); // this->matrix->Unref(); Handle<Value> argv[2]; v8::Local<v8::Array> arr = NanNew<v8::Array>(this->res.size()); for(unsigned int i = 0; i < this->res.size(); i++ ){ v8::Local<v8::Object> x = NanNew<v8::Object>(); x->Set(NanNew("x"), NanNew<Number>(this->res[i].x)); x->Set(NanNew("y"), NanNew<Number>(this->res[i].y)); x->Set(NanNew("width"), NanNew<Number>(this->res[i].width)); x->Set(NanNew("height"), NanNew<Number>(this->res[i].height)); arr->Set(i, x); } argv[0] = NanNull(); argv[1] = arr; TryCatch try_catch; callback->Call(2, argv); if (try_catch.HasCaught()) { FatalException(try_catch); } } private: CascadeClassifierWrap *cc; Matrix* im; double scale; int neighbors; int minw; int minh; std::vector<cv::Rect> res; }; NAN_METHOD(CascadeClassifierWrap::DetectMultiScale){ NanScope(); CascadeClassifierWrap *self = ObjectWrap::Unwrap<CascadeClassifierWrap>(args.This()); if (args.Length() < 2){ NanThrowTypeError("detectMultiScale takes at least 2 args"); } Matrix *im = ObjectWrap::Unwrap<Matrix>(args[0]->ToObject()); REQ_FUN_ARG(1, cb); double scale = 1.1; if (args.Length() > 2 && args[2]->IsNumber()) scale = args[2]->NumberValue(); int neighbors = 2; if (args.Length() > 3 && args[3]->IsInt32()) neighbors = args[3]->IntegerValue(); int minw = 30; int minh = 30; if (args.Length() > 5 && args[4]->IsInt32() && args[5]->IsInt32()){ minw = args[4]->IntegerValue(); minh = args[5]->IntegerValue(); } NanCallback *callback = new NanCallback(cb.As<Function>()); NanAsyncQueueWorker( new AsyncDetectMultiScale(callback, self, im, scale, neighbors, minw, minh) ); NanReturnUndefined(); } <|endoftext|>
<commit_before>/* This file is part of MMOServer. For more information, visit http://swganh.com Copyright (c) 2006 - 2010 The SWG:ANH Team MMOServer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MMOServer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MMOServer. If not, see <http://www.gnu.org/licenses/>. */ #include "anh/service/galaxy.h" #include <boost/date_time/posix_time/posix_time.hpp> using namespace anh::service; Galaxy::Galaxy( uint32_t id, uint32_t primary_id, const std::string& name, const std::string& version, Galaxy::StatusType status, const std::string& created_at, const std::string& updated_at) : id_(id) , primary_id_(primary_id) , name_(name) , status_(status) , created_at_(created_at) , updated_at_(updated_at) {} Galaxy::Galaxy(const Galaxy& other) { id_ = other.id_; primary_id_ = other.primary_id_; name_ = other.name_; version_ = other.version_; status_ = other.status_; created_at_ = other.created_at_; updated_at_ = other.updated_at_; } Galaxy::Galaxy(Galaxy&& other) { id_ = other.id_; primary_id_ = other.primary_id_; name_ = std::move(other.name_); version_ = std::move(other.version_); status_ = other.status_; created_at_ = std::move(other.created_at_); updated_at_ = std::move(other.updated_at_); } void Galaxy::swap(Galaxy& other) { std::swap(other.id_, id_); std::swap(other.primary_id_, primary_id_); std::swap(other.name_, name_); std::swap(other.version_, version_); std::swap(other.status_, status_); std::swap(other.created_at_, created_at_); std::swap(other.updated_at_, updated_at_); } Galaxy& Galaxy::operator=(Galaxy other) { other.swap(*this); return *this; } uint32_t Galaxy::id() const { return id_; } uint32_t Galaxy::primary_id() const { return primary_id_; } void Galaxy::primary_id(uint32_t primary_id) { primary_id_ = primary_id; } const std::string& Galaxy::name() const { return name_; } const std::string& Galaxy::version() const { return version_; } Galaxy::StatusType Galaxy::status() const { return status_; } const std::string& Galaxy::created_at() const { return created_at_; } const std::string& Galaxy::updated_at() const { return updated_at_; } uint64_t Galaxy::GetGalaxyTimeInMilliseconds() { return boost::posix_time::time_duration( boost::posix_time::duration_from_string(updated_at())).total_milliseconds(); } <commit_msg>the duration_from_string expects the time in an HH:MM:SS.TT format which isn't compatible with the update timestamp format. Created a duration string by subtracting the current time from the start time.<commit_after>/* This file is part of MMOServer. For more information, visit http://swganh.com Copyright (c) 2006 - 2010 The SWG:ANH Team MMOServer is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. MMOServer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MMOServer. If not, see <http://www.gnu.org/licenses/>. */ #include "anh/service/galaxy.h" #include <boost/date_time/posix_time/posix_time.hpp> using namespace anh::service; Galaxy::Galaxy( uint32_t id, uint32_t primary_id, const std::string& name, const std::string& version, Galaxy::StatusType status, const std::string& created_at, const std::string& updated_at) : id_(id) , primary_id_(primary_id) , name_(name) , status_(status) , created_at_(created_at) , updated_at_(updated_at) {} Galaxy::Galaxy(const Galaxy& other) { id_ = other.id_; primary_id_ = other.primary_id_; name_ = other.name_; version_ = other.version_; status_ = other.status_; created_at_ = other.created_at_; updated_at_ = other.updated_at_; } Galaxy::Galaxy(Galaxy&& other) { id_ = other.id_; primary_id_ = other.primary_id_; name_ = std::move(other.name_); version_ = std::move(other.version_); status_ = other.status_; created_at_ = std::move(other.created_at_); updated_at_ = std::move(other.updated_at_); } void Galaxy::swap(Galaxy& other) { std::swap(other.id_, id_); std::swap(other.primary_id_, primary_id_); std::swap(other.name_, name_); std::swap(other.version_, version_); std::swap(other.status_, status_); std::swap(other.created_at_, created_at_); std::swap(other.updated_at_, updated_at_); } Galaxy& Galaxy::operator=(Galaxy other) { other.swap(*this); return *this; } uint32_t Galaxy::id() const { return id_; } uint32_t Galaxy::primary_id() const { return primary_id_; } void Galaxy::primary_id(uint32_t primary_id) { primary_id_ = primary_id; } const std::string& Galaxy::name() const { return name_; } const std::string& Galaxy::version() const { return version_; } Galaxy::StatusType Galaxy::status() const { return status_; } const std::string& Galaxy::created_at() const { return created_at_; } const std::string& Galaxy::updated_at() const { return updated_at_; } uint64_t Galaxy::GetGalaxyTimeInMilliseconds() { boost::posix_time::ptime start_time(boost::posix_time::time_from_string(created_at())); boost::posix_time::ptime current_time(boost::posix_time::time_from_string(updated_at())); return (current_time - start_time).total_milliseconds(); } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "rpcnetwork.h" #include "rpcservicepool.h" #include "rpcsendv1.h" #include "rpcsendv2.h" #include "rpctargetpool.h" #include "rpcnetworkparams.h" #include <vespa/messagebus/errorcode.h> #include <vespa/messagebus/iprotocol.h> #include <vespa/messagebus/tracelevel.h> #include <vespa/messagebus/emptyreply.h> #include <vespa/messagebus/routing/routingnode.h> #include <vespa/slobrok/sbregister.h> #include <vespa/slobrok/sbmirror.h> #include <vespa/vespalib/component/vtag.h> #include <vespa/vespalib/stllike/asciistream.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/util/lambdatask.h> #include <vespa/fnet/scheduler.h> #include <vespa/fnet/transport.h> #include <vespa/fnet/frt/supervisor.h> #include <thread> #include <vespa/log/log.h> LOG_SETUP(".rpcnetwork"); using vespalib::make_string; using namespace std::chrono_literals; namespace { /** * Implements a helper class for {@link RPCNetwork#sync()}. It provides a * blocking method {@link #await()} that will wait until the internal state * of this object is set to 'done'. By scheduling this task in the network * thread and then calling this method, we achieve handshaking with the network * thread. */ class SyncTask : public FNET_Task { private: vespalib::Gate _gate; public: SyncTask(FNET_Scheduler &s) : FNET_Task(&s), _gate() { ScheduleNow(); } ~SyncTask() = default; void await() { _gate.await(); } void PerformTask() override { _gate.countDown(); } }; } // namespace <unnamed> namespace mbus { RPCNetwork::SendContext::SendContext(RPCNetwork &net, const Message &msg, const std::vector<RoutingNode*> &recipients) : _net(net), _msg(msg), _traceLevel(msg.getTrace().getLevel()), _recipients(recipients), _hasError(false), _pending(_recipients.size()), _version(_net.getVersion()) { } void RPCNetwork::SendContext::handleVersion(const vespalib::Version *version) { bool shouldSend = false; { vespalib::LockGuard guard(_lock); if (version == nullptr) { _hasError = true; } else if (*version < _version) { _version = *version; } if (--_pending == 0) { shouldSend = true; } } if (shouldSend) { _net.send(*this); delete this; } } RPCNetwork::TargetPoolTask::TargetPoolTask(FNET_Scheduler &scheduler, RPCTargetPool &pool) : FNET_Task(&scheduler), _pool(pool) { ScheduleNow(); } void RPCNetwork::TargetPoolTask::PerformTask() { _pool.flushTargets(false); Schedule(1.0); } RPCNetwork::RPCNetwork(const RPCNetworkParams &params) : _owner(nullptr), _ident(params.getIdentity()), _threadPool(std::make_unique<FastOS_ThreadPool>(128000, 0)), _transport(std::make_unique<FNET_Transport>()), _orb(std::make_unique<FRT_Supervisor>(_transport.get())), _scheduler(*_transport->GetScheduler()), _targetPool(std::make_unique<RPCTargetPool>(params.getConnectionExpireSecs())), _targetPoolTask(_scheduler, *_targetPool), _servicePool(std::make_unique<RPCServicePool>(*this, 4096)), _slobrokCfgFactory(std::make_unique<slobrok::ConfiguratorFactory>(params.getSlobrokConfig())), _mirror(std::make_unique<slobrok::api::MirrorAPI>(*_orb, *_slobrokCfgFactory)), _regAPI(std::make_unique<slobrok::api::RegisterAPI>(*_orb, *_slobrokCfgFactory)), _requestedPort(params.getListenPort()), _executor(std::make_unique<vespalib::ThreadStackExecutor>(params.getNumThreads(), 65536)), _sendV1(std::make_unique<RPCSendV1>()), _sendV2(std::make_unique<RPCSendV2>()), _sendAdapters(), _compressionConfig(params.getCompressionConfig()), _allowDispatchForEncode(params.getDispatchOnEncode()), _allowDispatchForDecode(params.getDispatchOnDecode()) { _transport->SetMaxInputBufferSize(params.getMaxInputBufferSize()); _transport->SetMaxOutputBufferSize(params.getMaxOutputBufferSize()); } RPCNetwork::~RPCNetwork() { shutdown(); } FRT_RPCRequest * RPCNetwork::allocRequest() { return _orb->AllocRPCRequest(); } RPCTarget::SP RPCNetwork::getTarget(const RPCServiceAddress &address) { return _targetPool->getTarget(*_orb, address); } void RPCNetwork::replyError(const SendContext &ctx, uint32_t errCode, const string &errMsg) { for (RoutingNode * rnode : ctx._recipients) { Reply::UP reply(new EmptyReply()); reply->setTrace(Trace(ctx._traceLevel)); reply->addError(Error(errCode, errMsg)); _owner->deliverReply(std::move(reply), *rnode); } } int RPCNetwork::getPort() const { return _orb->GetListenPort(); } void RPCNetwork::flushTargetPool() { _targetPool->flushTargets(true); } const vespalib::Version & RPCNetwork::getVersion() const { return vespalib::Vtag::currentVersion; } void RPCNetwork::attach(INetworkOwner &owner) { LOG_ASSERT(_owner == nullptr); _owner = &owner; _sendV1->attach(*this); _sendV2->attach(*this); _sendAdapters[vespalib::Version(5)] = _sendV1.get(); _sendAdapters[vespalib::Version(6, 149)] = _sendV2.get(); FRT_ReflectionBuilder builder(_orb.get()); builder.DefineMethod("mbus.getVersion", "", "s", FRT_METHOD(RPCNetwork::invoke), this); builder.MethodDesc("Retrieves the message bus version."); builder.ReturnDesc("version", "The message bus version."); } void RPCNetwork::invoke(FRT_RPCRequest *req) { req->GetReturn()->AddString(getVersion().toString().c_str()); } const string RPCNetwork::getConnectionSpec() const { return make_string("tcp/%s:%d", _ident.getHostname().c_str(), _orb->GetListenPort()); } RPCSendAdapter * RPCNetwork::getSendAdapter(const vespalib::Version &version) { if (version < _sendAdapters.begin()->first) { return nullptr; } return (--_sendAdapters.upper_bound(version))->second; } bool RPCNetwork::start() { if (!_orb->Listen(_requestedPort)) { return false; } if (!_transport->Start(_threadPool.get())) { return false; } return true; } bool RPCNetwork::waitUntilReady(double seconds) const { slobrok::api::SlobrokList brokerList; slobrok::Configurator::UP configurator = _slobrokCfgFactory->create(brokerList); bool hasConfig = false; for (uint32_t i = 0; i < seconds * 100; ++i) { if (configurator->poll()) { hasConfig = true; } if (_mirror->ready()) { return true; } std::this_thread::sleep_for(10ms); } if (! hasConfig) { LOG(error, "failed to get config for slobroks in %d seconds", (int)seconds); } else if (! _mirror->ready()) { auto brokers = brokerList.logString(); LOG(error, "mirror (of %s) failed to become ready in %d seconds", brokers.c_str(), (int)seconds); } return false; } void RPCNetwork::registerSession(const string &session) { if (_ident.getServicePrefix().empty()) { LOG(warning, "The session (%s) will not be registered in the Slobrok since this network has no identity.", session.c_str()); return; } string name = _ident.getServicePrefix(); name += "/"; name += session; _regAPI->registerName(name); } void RPCNetwork::unregisterSession(const string &session) { if (_ident.getServicePrefix().empty()) { return; } string name = _ident.getServicePrefix(); name += "/"; name += session; _regAPI->unregisterName(name); } bool RPCNetwork::allocServiceAddress(RoutingNode &recipient) { const Hop &hop = recipient.getRoute().getHop(0); string service = hop.getServiceName(); Error error = resolveServiceAddress(recipient, service); if (error.getCode() == ErrorCode::NONE) { return true; // service address resolved } recipient.setError(error); return false; // service adddress not resolved } Error RPCNetwork::resolveServiceAddress(RoutingNode &recipient, const string &serviceName) { RPCServiceAddress::UP ret = _servicePool->resolve(serviceName); if ( ! ret) { return Error(ErrorCode::NO_ADDRESS_FOR_SERVICE, make_string("The address of service '%s' could not be resolved. It is not currently " "registered with the Vespa name server. " "The service must be having problems, or the routing configuration is wrong. " "Address resolution attempted from host '%s'", serviceName.c_str(), getIdentity().getHostname().c_str())); } RPCTarget::SP target = _targetPool->getTarget(*_orb, *ret); if ( ! target) { return Error(ErrorCode::CONNECTION_ERROR, make_string("Failed to connect to service '%s' from host '%s'.", serviceName.c_str(), getIdentity().getHostname().c_str())); } ret->setTarget(target); // free by freeServiceAddress() recipient.setServiceAddress(IServiceAddress::UP(ret.release())); return Error(); } void RPCNetwork::freeServiceAddress(RoutingNode &recipient) { recipient.setServiceAddress(IServiceAddress::UP()); } void RPCNetwork::send(const Message &msg, const std::vector<RoutingNode*> &recipients) { SendContext &ctx = *(new SendContext(*this, msg, recipients)); // deletes self double timeout = ctx._msg.getTimeRemainingNow() / 1000.0; for (uint32_t i = 0, len = ctx._recipients.size(); i < len; ++i) { RoutingNode *&recipient = ctx._recipients[i]; RPCServiceAddress &address = static_cast<RPCServiceAddress&>(recipient->getServiceAddress()); LOG_ASSERT(address.hasTarget()); address.getTarget().resolveVersion(timeout, ctx); } } namespace { void emit_recipient_endpoint(vespalib::asciistream& stream, const RoutingNode& recipient) { if (recipient.hasServiceAddress()) { // At this point the service addresses _should_ be RPCServiceAddress instances, // but stay on the safe side of the tracks anyway. const auto* rpc_addr = dynamic_cast<const RPCServiceAddress*>(&recipient.getServiceAddress()); if (rpc_addr) { stream << rpc_addr->getServiceName() << " at " << rpc_addr->getConnectionSpec(); } else { stream << "<non-RPC service address>"; } } else { stream << "<unknown service address>"; } } } vespalib::string RPCNetwork::buildRecipientListString(const SendContext& ctx) { vespalib::asciistream s; bool first = true; for (const auto* recipient : ctx._recipients) { if (!first) { s << ", "; } first = false; emit_recipient_endpoint(s, *recipient); } return s.str(); } void RPCNetwork::send(RPCNetwork::SendContext &ctx) { if (ctx._hasError) { replyError(ctx, ErrorCode::HANDSHAKE_FAILED, make_string("An error occurred while resolving version of recipient(s) [%s] from host '%s'.", buildRecipientListString(ctx).c_str(), getIdentity().getHostname().c_str())); } else { uint64_t timeRemaining = ctx._msg.getTimeRemainingNow(); Blob payload = _owner->getProtocol(ctx._msg.getProtocol())->encode(ctx._version, ctx._msg); RPCSendAdapter *adapter = getSendAdapter(ctx._version); if (adapter == nullptr) { replyError(ctx, ErrorCode::INCOMPATIBLE_VERSION, make_string("Can not send to version '%s' recipient.", ctx._version.toString().c_str())); } else if (timeRemaining == 0) { replyError(ctx, ErrorCode::TIMEOUT, "Aborting transmission because zero time remains."); } else if (payload.size() == 0) { replyError(ctx, ErrorCode::ENCODE_ERROR, make_string("Protocol '%s' failed to encode message.", ctx._msg.getProtocol().c_str())); } else if (ctx._recipients.size() == 1) { adapter->sendByHandover(*ctx._recipients.front(), ctx._version, std::move(payload), timeRemaining); } else { for (auto & recipient : ctx._recipients) { adapter->send(*recipient, ctx._version, payload, timeRemaining); } } } } void RPCNetwork::sync() { SyncTask task(_scheduler); _executor->sync(); task.await(); } void RPCNetwork::shutdown() { _transport->ShutDown(true); _threadPool->Close(); _executor->shutdown(); _executor->sync(); } void RPCNetwork::postShutdownHook() { _scheduler.CheckTasks(); } const slobrok::api::IMirrorAPI & RPCNetwork::getMirror() const { return *_mirror; } } // namespace mbus <commit_msg>Revert "Wait until shutdown is completed."<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "rpcnetwork.h" #include "rpcservicepool.h" #include "rpcsendv1.h" #include "rpcsendv2.h" #include "rpctargetpool.h" #include "rpcnetworkparams.h" #include <vespa/messagebus/errorcode.h> #include <vespa/messagebus/iprotocol.h> #include <vespa/messagebus/tracelevel.h> #include <vespa/messagebus/emptyreply.h> #include <vespa/messagebus/routing/routingnode.h> #include <vespa/slobrok/sbregister.h> #include <vespa/slobrok/sbmirror.h> #include <vespa/vespalib/component/vtag.h> #include <vespa/vespalib/stllike/asciistream.h> #include <vespa/vespalib/util/stringfmt.h> #include <vespa/vespalib/util/lambdatask.h> #include <vespa/fnet/scheduler.h> #include <vespa/fnet/transport.h> #include <vespa/fnet/frt/supervisor.h> #include <thread> #include <vespa/log/log.h> LOG_SETUP(".rpcnetwork"); using vespalib::make_string; using namespace std::chrono_literals; namespace { /** * Implements a helper class for {@link RPCNetwork#sync()}. It provides a * blocking method {@link #await()} that will wait until the internal state * of this object is set to 'done'. By scheduling this task in the network * thread and then calling this method, we achieve handshaking with the network * thread. */ class SyncTask : public FNET_Task { private: vespalib::Gate _gate; public: SyncTask(FNET_Scheduler &s) : FNET_Task(&s), _gate() { ScheduleNow(); } ~SyncTask() = default; void await() { _gate.await(); } void PerformTask() override { _gate.countDown(); } }; } // namespace <unnamed> namespace mbus { RPCNetwork::SendContext::SendContext(RPCNetwork &net, const Message &msg, const std::vector<RoutingNode*> &recipients) : _net(net), _msg(msg), _traceLevel(msg.getTrace().getLevel()), _recipients(recipients), _hasError(false), _pending(_recipients.size()), _version(_net.getVersion()) { } void RPCNetwork::SendContext::handleVersion(const vespalib::Version *version) { bool shouldSend = false; { vespalib::LockGuard guard(_lock); if (version == nullptr) { _hasError = true; } else if (*version < _version) { _version = *version; } if (--_pending == 0) { shouldSend = true; } } if (shouldSend) { _net.send(*this); delete this; } } RPCNetwork::TargetPoolTask::TargetPoolTask(FNET_Scheduler &scheduler, RPCTargetPool &pool) : FNET_Task(&scheduler), _pool(pool) { ScheduleNow(); } void RPCNetwork::TargetPoolTask::PerformTask() { _pool.flushTargets(false); Schedule(1.0); } RPCNetwork::RPCNetwork(const RPCNetworkParams &params) : _owner(nullptr), _ident(params.getIdentity()), _threadPool(std::make_unique<FastOS_ThreadPool>(128000, 0)), _transport(std::make_unique<FNET_Transport>()), _orb(std::make_unique<FRT_Supervisor>(_transport.get())), _scheduler(*_transport->GetScheduler()), _targetPool(std::make_unique<RPCTargetPool>(params.getConnectionExpireSecs())), _targetPoolTask(_scheduler, *_targetPool), _servicePool(std::make_unique<RPCServicePool>(*this, 4096)), _slobrokCfgFactory(std::make_unique<slobrok::ConfiguratorFactory>(params.getSlobrokConfig())), _mirror(std::make_unique<slobrok::api::MirrorAPI>(*_orb, *_slobrokCfgFactory)), _regAPI(std::make_unique<slobrok::api::RegisterAPI>(*_orb, *_slobrokCfgFactory)), _requestedPort(params.getListenPort()), _executor(std::make_unique<vespalib::ThreadStackExecutor>(params.getNumThreads(), 65536)), _sendV1(std::make_unique<RPCSendV1>()), _sendV2(std::make_unique<RPCSendV2>()), _sendAdapters(), _compressionConfig(params.getCompressionConfig()), _allowDispatchForEncode(params.getDispatchOnEncode()), _allowDispatchForDecode(params.getDispatchOnDecode()) { _transport->SetMaxInputBufferSize(params.getMaxInputBufferSize()); _transport->SetMaxOutputBufferSize(params.getMaxOutputBufferSize()); } RPCNetwork::~RPCNetwork() { shutdown(); } FRT_RPCRequest * RPCNetwork::allocRequest() { return _orb->AllocRPCRequest(); } RPCTarget::SP RPCNetwork::getTarget(const RPCServiceAddress &address) { return _targetPool->getTarget(*_orb, address); } void RPCNetwork::replyError(const SendContext &ctx, uint32_t errCode, const string &errMsg) { for (RoutingNode * rnode : ctx._recipients) { Reply::UP reply(new EmptyReply()); reply->setTrace(Trace(ctx._traceLevel)); reply->addError(Error(errCode, errMsg)); _owner->deliverReply(std::move(reply), *rnode); } } int RPCNetwork::getPort() const { return _orb->GetListenPort(); } void RPCNetwork::flushTargetPool() { _targetPool->flushTargets(true); } const vespalib::Version & RPCNetwork::getVersion() const { return vespalib::Vtag::currentVersion; } void RPCNetwork::attach(INetworkOwner &owner) { LOG_ASSERT(_owner == nullptr); _owner = &owner; _sendV1->attach(*this); _sendV2->attach(*this); _sendAdapters[vespalib::Version(5)] = _sendV1.get(); _sendAdapters[vespalib::Version(6, 149)] = _sendV2.get(); FRT_ReflectionBuilder builder(_orb.get()); builder.DefineMethod("mbus.getVersion", "", "s", FRT_METHOD(RPCNetwork::invoke), this); builder.MethodDesc("Retrieves the message bus version."); builder.ReturnDesc("version", "The message bus version."); } void RPCNetwork::invoke(FRT_RPCRequest *req) { req->GetReturn()->AddString(getVersion().toString().c_str()); } const string RPCNetwork::getConnectionSpec() const { return make_string("tcp/%s:%d", _ident.getHostname().c_str(), _orb->GetListenPort()); } RPCSendAdapter * RPCNetwork::getSendAdapter(const vespalib::Version &version) { if (version < _sendAdapters.begin()->first) { return nullptr; } return (--_sendAdapters.upper_bound(version))->second; } bool RPCNetwork::start() { if (!_orb->Listen(_requestedPort)) { return false; } if (!_transport->Start(_threadPool.get())) { return false; } return true; } bool RPCNetwork::waitUntilReady(double seconds) const { slobrok::api::SlobrokList brokerList; slobrok::Configurator::UP configurator = _slobrokCfgFactory->create(brokerList); bool hasConfig = false; for (uint32_t i = 0; i < seconds * 100; ++i) { if (configurator->poll()) { hasConfig = true; } if (_mirror->ready()) { return true; } std::this_thread::sleep_for(10ms); } if (! hasConfig) { LOG(error, "failed to get config for slobroks in %d seconds", (int)seconds); } else if (! _mirror->ready()) { auto brokers = brokerList.logString(); LOG(error, "mirror (of %s) failed to become ready in %d seconds", brokers.c_str(), (int)seconds); } return false; } void RPCNetwork::registerSession(const string &session) { if (_ident.getServicePrefix().empty()) { LOG(warning, "The session (%s) will not be registered in the Slobrok since this network has no identity.", session.c_str()); return; } string name = _ident.getServicePrefix(); name += "/"; name += session; _regAPI->registerName(name); } void RPCNetwork::unregisterSession(const string &session) { if (_ident.getServicePrefix().empty()) { return; } string name = _ident.getServicePrefix(); name += "/"; name += session; _regAPI->unregisterName(name); } bool RPCNetwork::allocServiceAddress(RoutingNode &recipient) { const Hop &hop = recipient.getRoute().getHop(0); string service = hop.getServiceName(); Error error = resolveServiceAddress(recipient, service); if (error.getCode() == ErrorCode::NONE) { return true; // service address resolved } recipient.setError(error); return false; // service adddress not resolved } Error RPCNetwork::resolveServiceAddress(RoutingNode &recipient, const string &serviceName) { RPCServiceAddress::UP ret = _servicePool->resolve(serviceName); if ( ! ret) { return Error(ErrorCode::NO_ADDRESS_FOR_SERVICE, make_string("The address of service '%s' could not be resolved. It is not currently " "registered with the Vespa name server. " "The service must be having problems, or the routing configuration is wrong. " "Address resolution attempted from host '%s'", serviceName.c_str(), getIdentity().getHostname().c_str())); } RPCTarget::SP target = _targetPool->getTarget(*_orb, *ret); if ( ! target) { return Error(ErrorCode::CONNECTION_ERROR, make_string("Failed to connect to service '%s' from host '%s'.", serviceName.c_str(), getIdentity().getHostname().c_str())); } ret->setTarget(target); // free by freeServiceAddress() recipient.setServiceAddress(IServiceAddress::UP(ret.release())); return Error(); } void RPCNetwork::freeServiceAddress(RoutingNode &recipient) { recipient.setServiceAddress(IServiceAddress::UP()); } void RPCNetwork::send(const Message &msg, const std::vector<RoutingNode*> &recipients) { SendContext &ctx = *(new SendContext(*this, msg, recipients)); // deletes self double timeout = ctx._msg.getTimeRemainingNow() / 1000.0; for (uint32_t i = 0, len = ctx._recipients.size(); i < len; ++i) { RoutingNode *&recipient = ctx._recipients[i]; RPCServiceAddress &address = static_cast<RPCServiceAddress&>(recipient->getServiceAddress()); LOG_ASSERT(address.hasTarget()); address.getTarget().resolveVersion(timeout, ctx); } } namespace { void emit_recipient_endpoint(vespalib::asciistream& stream, const RoutingNode& recipient) { if (recipient.hasServiceAddress()) { // At this point the service addresses _should_ be RPCServiceAddress instances, // but stay on the safe side of the tracks anyway. const auto* rpc_addr = dynamic_cast<const RPCServiceAddress*>(&recipient.getServiceAddress()); if (rpc_addr) { stream << rpc_addr->getServiceName() << " at " << rpc_addr->getConnectionSpec(); } else { stream << "<non-RPC service address>"; } } else { stream << "<unknown service address>"; } } } vespalib::string RPCNetwork::buildRecipientListString(const SendContext& ctx) { vespalib::asciistream s; bool first = true; for (const auto* recipient : ctx._recipients) { if (!first) { s << ", "; } first = false; emit_recipient_endpoint(s, *recipient); } return s.str(); } void RPCNetwork::send(RPCNetwork::SendContext &ctx) { if (ctx._hasError) { replyError(ctx, ErrorCode::HANDSHAKE_FAILED, make_string("An error occurred while resolving version of recipient(s) [%s] from host '%s'.", buildRecipientListString(ctx).c_str(), getIdentity().getHostname().c_str())); } else { uint64_t timeRemaining = ctx._msg.getTimeRemainingNow(); Blob payload = _owner->getProtocol(ctx._msg.getProtocol())->encode(ctx._version, ctx._msg); RPCSendAdapter *adapter = getSendAdapter(ctx._version); if (adapter == nullptr) { replyError(ctx, ErrorCode::INCOMPATIBLE_VERSION, make_string("Can not send to version '%s' recipient.", ctx._version.toString().c_str())); } else if (timeRemaining == 0) { replyError(ctx, ErrorCode::TIMEOUT, "Aborting transmission because zero time remains."); } else if (payload.size() == 0) { replyError(ctx, ErrorCode::ENCODE_ERROR, make_string("Protocol '%s' failed to encode message.", ctx._msg.getProtocol().c_str())); } else if (ctx._recipients.size() == 1) { adapter->sendByHandover(*ctx._recipients.front(), ctx._version, std::move(payload), timeRemaining); } else { for (auto & recipient : ctx._recipients) { adapter->send(*recipient, ctx._version, payload, timeRemaining); } } } } void RPCNetwork::sync() { SyncTask task(_scheduler); _executor->sync(); task.await(); } void RPCNetwork::shutdown() { _transport->ShutDown(false); _threadPool->Close(); _executor->shutdown(); _executor->sync(); } void RPCNetwork::postShutdownHook() { _scheduler.CheckTasks(); } const slobrok::api::IMirrorAPI & RPCNetwork::getMirror() const { return *_mirror; } } // namespace mbus <|endoftext|>
<commit_before>#include "application.h" #ifdef Q_OS_WIN #include <windows.h> //need for support console (It's Windows baby) #endif #include <iostream> #include <getopt.h> #define STRINGIFY(x) #x #define DEF_TO_STR(x) STRINGIFY(x) Application::Application(int &argc, char **argv) : QGuiApplication(argc, argv) { setApplicationDisplayName("CRC Calculator ver " DEF_TO_STR(MAJOR_VERSION) "." DEF_TO_STR(MINOR_VERSION)); attach_console(); processing_cmd(argc, argv); calc_text.set_ucrc(&uCRC); calc_hex.set_ucrc(&uCRC); // GUI engine.rootContext()->setContextProperty("uCRC", &uCRC); engine.rootContext()->setContextProperty("calc_text", &calc_text); engine.rootContext()->setContextProperty("calc_hex", &calc_hex); engine.load(QUrl(QLatin1String("qrc:/qml/main.qml"))); } void Application::attach_console() { #ifdef Q_OS_WIN // attach the new console to this application's process AttachConsole(ATTACH_PARENT_PROCESS); // reopen the std I/O streams to redirect I/O to the new console freopen("CON", "w", stdout); freopen("CON", "w", stderr); freopen("CON", "r", stdin); #endif } static const char *help_str = " =============== Help ===============\n" " Application: CRC Calculator\n" " App version: " DEF_TO_STR(MAJOR_VERSION) "." DEF_TO_STR(MINOR_VERSION) "\n" #ifdef QT_DEBUG " Build mode: debug\n" #else " Build mode: release\n" #endif " Build date: " __DATE__ "\n" " Build time: " __TIME__ "\n\n" "Options: description:\n\n" " --bits [value] Set Bits (value 1..64)\n" " --poly [value] Set Polynom (value in hex)\n" " --init [value] Set Init (value in hex)\n" " --xor_out [value] Set XorOut (value in hex)\n" " --ref_in [value] Set RefIn (value in hex)\n" " -v --version Display version information\n" " -h, --help Display this information\n\n"; // indexes for long_opt function namespace LongOpts { enum { version = 0, help, // Set CRC param bits, poly, init, xor_out, ref_in }; } static const struct option long_opts[] = { { "version", no_argument, NULL, LongOpts::version }, { "help", no_argument, NULL, LongOpts::help }, // Set CRC param { "bits", required_argument, NULL, LongOpts::bits }, { "poly", required_argument, NULL, LongOpts::poly }, { "init", required_argument, NULL, LongOpts::init }, { "xor_out", required_argument, NULL, LongOpts::xor_out }, { "ref_in", required_argument, NULL, LongOpts::ref_in }, { NULL, no_argument, NULL, 0 } }; void Application::processing_cmd(int argc, char *argv[]) { int opt; while( (opt = getopt_long(argc, argv, "", long_opts, NULL)) != -1 ) { switch( opt ) { case LongOpts::version: std::cout << "CRC Calculator version " << MAJOR_VERSION << '.' << MINOR_VERSION << "\n"; _exit(EXIT_SUCCESS); break; case LongOpts::help: std::cout << help_str; _exit(EXIT_SUCCESS); break; // Set CRC param case LongOpts::bits: if( uCRC.set_bits(str_to_uint64(optarg)) != 0 ) { std::cout << "Cant set bits from val: " << optarg << "\n"; _exit(EXIT_FAILURE); } break; case LongOpts::poly: uCRC.set_poly(str_to_uint64(optarg, 16)); break; case LongOpts::init: uCRC.set_init(str_to_uint64(optarg, 16)); break; case LongOpts::xor_out: uCRC.set_xor_out(str_to_uint64(optarg, 16)); break; case LongOpts::ref_in: uCRC.set_ref_in(str_to_bool(optarg)); break; default: // getopt_long function itself prints an error message std::cout << "for more detail see help\n\n"; _exit(EXIT_FAILURE); break; } } } quint64 Application::str_to_uint64(const char *val, int base) { bool ok; QString tmp(val); quint64 res = tmp.toULongLong(&ok, base); if(!ok) { std::cout << "Cant convert: " << val << " to hex\n"; _exit(EXIT_FAILURE); } return res; //good job } bool Application::str_to_bool(const char *val) { QString tmp(val); return (tmp.compare("true", Qt::CaseInsensitive) == 0) || (atoi(val) != 0); } <commit_msg>add cmd --ref_out<commit_after>#include "application.h" #ifdef Q_OS_WIN #include <windows.h> //need for support console (It's Windows baby) #endif #include <iostream> #include <getopt.h> #define STRINGIFY(x) #x #define DEF_TO_STR(x) STRINGIFY(x) Application::Application(int &argc, char **argv) : QGuiApplication(argc, argv) { setApplicationDisplayName("CRC Calculator ver " DEF_TO_STR(MAJOR_VERSION) "." DEF_TO_STR(MINOR_VERSION)); attach_console(); processing_cmd(argc, argv); calc_text.set_ucrc(&uCRC); calc_hex.set_ucrc(&uCRC); // GUI engine.rootContext()->setContextProperty("uCRC", &uCRC); engine.rootContext()->setContextProperty("calc_text", &calc_text); engine.rootContext()->setContextProperty("calc_hex", &calc_hex); engine.load(QUrl(QLatin1String("qrc:/qml/main.qml"))); } void Application::attach_console() { #ifdef Q_OS_WIN // attach the new console to this application's process AttachConsole(ATTACH_PARENT_PROCESS); // reopen the std I/O streams to redirect I/O to the new console freopen("CON", "w", stdout); freopen("CON", "w", stderr); freopen("CON", "r", stdin); #endif } static const char *help_str = " =============== Help ===============\n" " Application: CRC Calculator\n" " App version: " DEF_TO_STR(MAJOR_VERSION) "." DEF_TO_STR(MINOR_VERSION) "\n" #ifdef QT_DEBUG " Build mode: debug\n" #else " Build mode: release\n" #endif " Build date: " __DATE__ "\n" " Build time: " __TIME__ "\n\n" "Options: description:\n\n" " --bits [value] Set Bits (value 1..64)\n" " --poly [value] Set Polynom (value in hex)\n" " --init [value] Set Init (value in hex)\n" " --xor_out [value] Set XorOut (value in hex)\n" " --ref_in [value] Set RefIn ({0|flase} or {!=0|true})\n" " --ref_out [value] Set RefOut ({0|flase} or {!=0|true})\n" " -v --version Display version information\n" " -h, --help Display this information\n\n"; // indexes for long_opt function namespace LongOpts { enum { version = 0, help, // Set CRC param bits, poly, init, xor_out, ref_in, ref_out }; } static const struct option long_opts[] = { { "version", no_argument, NULL, LongOpts::version }, { "help", no_argument, NULL, LongOpts::help }, // Set CRC param { "bits", required_argument, NULL, LongOpts::bits }, { "poly", required_argument, NULL, LongOpts::poly }, { "init", required_argument, NULL, LongOpts::init }, { "xor_out", required_argument, NULL, LongOpts::xor_out }, { "ref_in", required_argument, NULL, LongOpts::ref_in }, { "ref_out", required_argument, NULL, LongOpts::ref_out }, { NULL, no_argument, NULL, 0 } }; void Application::processing_cmd(int argc, char *argv[]) { int opt; while( (opt = getopt_long(argc, argv, "", long_opts, NULL)) != -1 ) { switch( opt ) { case LongOpts::version: std::cout << "CRC Calculator version " << MAJOR_VERSION << '.' << MINOR_VERSION << "\n"; _exit(EXIT_SUCCESS); break; case LongOpts::help: std::cout << help_str; _exit(EXIT_SUCCESS); break; // Set CRC param case LongOpts::bits: if( uCRC.set_bits(str_to_uint64(optarg)) != 0 ) { std::cout << "Cant set bits from val: " << optarg << "\n"; _exit(EXIT_FAILURE); } break; case LongOpts::poly: uCRC.set_poly(str_to_uint64(optarg, 16)); break; case LongOpts::init: uCRC.set_init(str_to_uint64(optarg, 16)); break; case LongOpts::xor_out: uCRC.set_xor_out(str_to_uint64(optarg, 16)); break; case LongOpts::ref_in: uCRC.set_ref_in(str_to_bool(optarg)); break; case LongOpts::ref_out: uCRC.set_ref_out(str_to_bool(optarg)); break; default: // getopt_long function itself prints an error message std::cout << "for more detail see help\n\n"; _exit(EXIT_FAILURE); break; } } } quint64 Application::str_to_uint64(const char *val, int base) { bool ok; QString tmp(val); quint64 res = tmp.toULongLong(&ok, base); if(!ok) { std::cout << "Cant convert: " << val << " to hex\n"; _exit(EXIT_FAILURE); } return res; //good job } bool Application::str_to_bool(const char *val) { QString tmp(val); return (tmp.compare("true", Qt::CaseInsensitive) == 0) || (atoi(val) != 0); } <|endoftext|>
<commit_before>#ifndef INCLUDE_AL_GRAPHICS_ASSET_HPP #define INCLUDE_AL_GRAPHICS_ASSET_HPP /* Allocore -- Multimedia / virtual environment application class library Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB. Copyright (C) 2012. The Regents of the University of California. 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 University of California nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. File description: Asset manages the loading and parsing of 3D asset files (models and scenes) File author(s): Graham Wakefield, 2010, grrrwaaa@gmail.com Pablo Colapinto, 2010, wolftype@gmail.com */ /*! Asset manages the loading and parsing of 3D asset files Asset wraps the AssImp library. A scene contains - array of meshes - array of materials - array of textures - also: array of animations, array of lights, array of cameras - tree of nodes, starting from a root node A mesh contains - name - material (index into scene) - array of vertices - array of normals - array of colors - array of texcoords - arrays of tangents, bitangents - bones A material contains - array of properties - helper methods for retrieving textures A node contains - name - a 4x4 matrix transform relative to its parent - a list of children - a number of meshes (indexing scene arrays) */ #include <string> #include "allocore/graphics/al_Graphics.hpp" #include "allocore/types/al_Color.hpp" namespace al{ /// A collection of related meshes, textures, and materials for a 3D scene /// @ingroup allocore class Scene { public: /// Import flags enum ImportPreset { FAST, QUALITY, MAX_QUALITY }; /// Scene node struct Node { class Impl; Node(); ~Node(); std::string name() const; Impl * mImpl; }; /// Scene material struct Material { struct TextureProperty { bool useTexture; std::string texture; TextureProperty() : useTexture(false) {} }; Material(); std::string name; // standard OpenGL properties: int two_sided, wireframe; Color diffuse, ambient, specular, emissive; float shininess; // other properites: int shading_model, blend_func; float shininess_strength, opacity, reflectivity, refracti, bump_scaling; Color transparent, reflective; TextureProperty diffusemap, ambientmap, specularmap, opacitymap, emissivemap, shininessmap, lightmap, normalmap, heightmap, displacementmap, reflectionmap; std::string background; }; ~Scene(); /// Import an asset static Scene * import(const std::string& path, ImportPreset preset = MAX_QUALITY); /// Return number of meshes in scene unsigned int meshes() const; /// Read a mesh from the Scene void mesh(unsigned int i, Mesh& mesh) const; /// Alternative read a mesh from the Scene void meshAlt(unsigned int i, Mesh& mesh) const; /// Read all meshes void meshAll(Mesh& dst) const { for (unsigned i=0; i<meshes(); i++) mesh(i, dst); } /// Get the material index for a given mesh unsigned int meshMaterial(unsigned int i) const; /// Get the name of a given mesh std::string meshName(unsigned int i) const; /// Return number of materials in scene unsigned int materials() const; /// Read a material from the scene const Material& material(unsigned int i) const; /// Return number of materials in scene unsigned int textures() const; /// Return number of nodes in scene unsigned int nodes() const; /// Read a node in the scene: Node& node(unsigned int i) const; /// Get scene extents /// @param[out] min 3-vector of minimum coordinates /// @param[out] max 3-vector of maximum coordinates void getBounds(Vec3f& min, Vec3f& max) const; /// Print out information about the Scene void print() const; void dump() const {print();} /// Toggle verbose mode static void verbose(bool b); protected: std::vector<Material> mMaterials; class Impl; Impl * mImpl; Scene(Impl * impl); }; } // al:: #endif /* include guard */ <commit_msg>Asset: minimize includes in header<commit_after>#ifndef INCLUDE_AL_GRAPHICS_ASSET_HPP #define INCLUDE_AL_GRAPHICS_ASSET_HPP /* Allocore -- Multimedia / virtual environment application class library Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB. Copyright (C) 2012. The Regents of the University of California. 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 University of California nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. File description: Asset manages the loading and parsing of 3D asset files (models and scenes) File author(s): Graham Wakefield, 2010, grrrwaaa@gmail.com Pablo Colapinto, 2010, wolftype@gmail.com */ /*! Asset manages the loading and parsing of 3D asset files Asset wraps the AssImp library. A scene contains - array of meshes - array of materials - array of textures - also: array of animations, array of lights, array of cameras - tree of nodes, starting from a root node A mesh contains - name - material (index into scene) - array of vertices - array of normals - array of colors - array of texcoords - arrays of tangents, bitangents - bones A material contains - array of properties - helper methods for retrieving textures A node contains - name - a 4x4 matrix transform relative to its parent - a list of children - a number of meshes (indexing scene arrays) */ #include <string> #include "allocore/graphics/al_Mesh.hpp" #include "allocore/types/al_Color.hpp" namespace al{ /// A collection of related meshes, textures, and materials for a 3D scene /// @ingroup allocore class Scene { public: /// Import flags enum ImportPreset { FAST, QUALITY, MAX_QUALITY }; /// Scene node struct Node { class Impl; Node(); ~Node(); std::string name() const; Impl * mImpl; }; /// Scene material struct Material { struct TextureProperty { bool useTexture; std::string texture; TextureProperty() : useTexture(false) {} }; Material(); std::string name; // standard OpenGL properties: int two_sided, wireframe; Color diffuse, ambient, specular, emissive; float shininess; // other properites: int shading_model, blend_func; float shininess_strength, opacity, reflectivity, refracti, bump_scaling; Color transparent, reflective; TextureProperty diffusemap, ambientmap, specularmap, opacitymap, emissivemap, shininessmap, lightmap, normalmap, heightmap, displacementmap, reflectionmap; std::string background; }; ~Scene(); /// Import an asset static Scene * import(const std::string& path, ImportPreset preset = MAX_QUALITY); /// Return number of meshes in scene unsigned int meshes() const; /// Read a mesh from the Scene void mesh(unsigned int i, Mesh& mesh) const; /// Alternative read a mesh from the Scene void meshAlt(unsigned int i, Mesh& mesh) const; /// Read all meshes void meshAll(Mesh& dst) const { for (unsigned i=0; i<meshes(); i++) mesh(i, dst); } /// Get the material index for a given mesh unsigned int meshMaterial(unsigned int i) const; /// Get the name of a given mesh std::string meshName(unsigned int i) const; /// Return number of materials in scene unsigned int materials() const; /// Read a material from the scene const Material& material(unsigned int i) const; /// Return number of materials in scene unsigned int textures() const; /// Return number of nodes in scene unsigned int nodes() const; /// Read a node in the scene: Node& node(unsigned int i) const; /// Get scene extents /// @param[out] min 3-vector of minimum coordinates /// @param[out] max 3-vector of maximum coordinates void getBounds(Vec3f& min, Vec3f& max) const; /// Print out information about the Scene void print() const; void dump() const {print();} /// Toggle verbose mode static void verbose(bool b); protected: std::vector<Material> mMaterials; class Impl; Impl * mImpl; Scene(Impl * impl); }; } // al:: #endif /* include guard */ <|endoftext|>
<commit_before>/* @doc Computation of the dynamic aspect for a robot. This class will load the description of a robot from a VRML file following the OpenHRP syntax. Using ForwardVelocity it is then possible specifying the angular velocity and the angular value to get the absolute position, and absolute velocity of each body separetly. Heavy rewriting from the original source of Adrien and Jean-Remy. This implantation is an updated based on a mixture between the code provided by Jean-Remy and Adrien. Copyright (c) 2005-2006, @author Olivier Stasse, Ramzi Sellouati, Jean-Remy Chardonnet, Adrien Escande, Abderrahmane Kheddar Copyright (c) 2007-2009 @author Olivier Stasse, Oussama Kannoun, Fumio Kanehiro. JRL-Japan, CNRS/AIST All rights reserved. Please refers to file License.txt for details on the license. */ /*! System includes */ #include <iostream> #include <sstream> #include <fstream> #include <string.h> #include "Debug.h" /*! Local library includes. */ #include "MatrixAbstractLayer/MatrixAbstractLayer.h" #include "dynamicsJRLJapan/DynamicBody.h" #include "DynMultiBodyPrivate.h" #include "robotDynamics/jrlBody.h" #include "fileReader.h" using namespace dynamicsJRLJapan; void DynMultiBodyPrivate::BackwardDynamics(DynamicBodyPrivate & CurrentBody ) { MAL_S3x3_MATRIX(,double) aRt; MAL_S3x3_MATRIX(,double) currentBodyR; currentBodyR = MAL_S3x3_RET_TRANSPOSE(CurrentBody.R); MAL_S3_VECTOR(,double) lg; lg(0) = 0.0; lg(1) = 0.0; lg(2) = -9.81; /* Compute the torque * with eq. (7.147) Spong RMC p. 277 * * */ MAL_S3_VECTOR(,double) firstterm, sndterm, thirdterm, fifthterm,tmp; // Do not fourth term because it is the angular acceleration. /* Constant part */ tmp = CurrentBody.dv_c - lg; tmp = MAL_S3x3_RET_A_by_B(currentBodyR,tmp); CurrentBody.m_Force = tmp * CurrentBody.mass(); /* 2nd term : -f_i x r_{i,ci} */ vector3d lc = CurrentBody.localCenterOfMass(); /* 5th term : w_i x (I_i w_i)*/ MAL_S3x3_MATRIX(,double) lI = CurrentBody.getInertie(); tmp = MAL_S3x3_RET_A_by_B(currentBodyR,CurrentBody.w); tmp = MAL_S3x3_RET_A_by_B(lI,tmp); MAL_S3_VECTOR_CROSS_PRODUCT(fifthterm,CurrentBody.w,tmp); CurrentBody.m_Torque = MAL_S3x3_RET_A_by_B(currentBodyR,CurrentBody.dw) + fifthterm ; /* Compute with the force * eq. (7.146) Spong RMC p. 277 * fi = R^i_{i+1} * f_{i+1} + m_i * a_{c,i} - m_i * g_i * g_i is the gravity express in the i reference frame. */ matrix4d curtri; if (CurrentBody.joint()!=0) curtri = CurrentBody.joint()->currentTransformation(); else MAL_S4x4_MATRIX_SET_IDENTITY(curtri); matrix4d invcurtri; MAL_S4x4_INVERSE(curtri,invcurtri,double); int IndexChild = CurrentBody.child; while(IndexChild!=-1) { DynamicBodyPrivate *Child = m_listOfBodies[IndexChild]; //cout << "Child Bodies : " << Child->getName() << endl; aRt = MAL_S3x3_RET_A_by_B(Child->R_static,Child->Riip1); //cout << "Riip1: " << aRt << endl; // /* Force computation. */ // R_i_{i+1} f_{i+1} tmp= MAL_S3x3_RET_A_by_B(aRt, Child->m_Force); CurrentBody.m_Force += tmp; /* Torque computation. */ /* 1st term : R^i_{i+1} t_{i+1} */ firstterm = MAL_S3x3_RET_A_by_B(aRt, Child->m_Torque); /* 3rd term : (R_i_{i+1} f_{i+1}) x rip1,ci */ matrix4d curtrip1= Child->joint()->currentTransformation(); matrix4d ip1Mi; MAL_S4x4_C_eq_A_by_B(ip1Mi, invcurtri, curtrip1); /* rip1,ci = (riip1)^(-1)rici Note: rip1,c1 is expressed in the frame of link i. */ vector3d res3d; MAL_S3_VECTOR_ACCESS(res3d,0) = MAL_S3_VECTOR_ACCESS(lc,0)- MAL_S4x4_MATRIX_ACCESS_I_J(ip1Mi,0,3); MAL_S3_VECTOR_ACCESS(res3d,1) = MAL_S3_VECTOR_ACCESS(lc,1) - MAL_S4x4_MATRIX_ACCESS_I_J(ip1Mi,1,3) ; MAL_S3_VECTOR_ACCESS(res3d,2) = MAL_S3_VECTOR_ACCESS(lc,2)- MAL_S4x4_MATRIX_ACCESS_I_J(ip1Mi,2,3); MAL_S3_VECTOR_CROSS_PRODUCT(thirdterm,tmp, res3d); CurrentBody.m_Torque += firstterm + thirdterm; /* Body selection. */ IndexChild = m_listOfBodies[IndexChild]->sister; if (IndexChild!=-1) Child=m_listOfBodies[IndexChild]; } //vector3d lc = CurrentBody.w_c; MAL_S3_VECTOR_CROSS_PRODUCT(sndterm,CurrentBody.m_Force, lc); CurrentBody.m_Torque = CurrentBody.m_Torque - sndterm; // Update the vector related to the computed quantities. for(unsigned int i=0;i<m_StateVectorToJoint.size();i++) { unsigned int StateRankComputed=false; JointPrivate * aJoint = (JointPrivate *)m_JointVector[m_StateVectorToJoint[i]]; if (aJoint!=0) { DynamicBodyPrivate *aDB = (DynamicBodyPrivate *) aJoint->linkedBody(); if (aDB!=0) { StateRankComputed = true; for(unsigned int k=0;k<3;k++) { m_Forces(i,k)=aDB->m_Force[k]; m_Torques(i,k) = aDB->m_Torque[k]; } } } if (!StateRankComputed) { for(unsigned int k=0;k<3;k++) { m_Forces(i,k)=0.0; m_Torques(i,k)=0.0; } } } } <commit_msg>Fix a bug in the torque computation.<commit_after>/* @doc Computation of the dynamic aspect for a robot. This class will load the description of a robot from a VRML file following the OpenHRP syntax. Using ForwardVelocity it is then possible specifying the angular velocity and the angular value to get the absolute position, and absolute velocity of each body separetly. Heavy rewriting from the original source of Adrien and Jean-Remy. This implantation is an updated based on a mixture between the code provided by Jean-Remy and Adrien. Copyright (c) 2005-2006, @author Olivier Stasse, Ramzi Sellouati, Jean-Remy Chardonnet, Adrien Escande, Abderrahmane Kheddar Copyright (c) 2007-2009 @author Olivier Stasse, Oussama Kannoun, Fumio Kanehiro. JRL-Japan, CNRS/AIST All rights reserved. Please refers to file License.txt for details on the license. */ /*! System includes */ #include <iostream> #include <sstream> #include <fstream> #include <string.h> #include "Debug.h" /*! Local library includes. */ #include "MatrixAbstractLayer/MatrixAbstractLayer.h" #include "dynamicsJRLJapan/DynamicBody.h" #include "DynMultiBodyPrivate.h" #include "robotDynamics/jrlBody.h" #include "fileReader.h" using namespace dynamicsJRLJapan; void DynMultiBodyPrivate::BackwardDynamics(DynamicBodyPrivate & CurrentBody ) { MAL_S3x3_MATRIX(,double) aRt; MAL_S3x3_MATRIX(,double) currentBodyR; currentBodyR = MAL_S3x3_RET_TRANSPOSE(CurrentBody.R); MAL_S3_VECTOR(,double) lg; lg(0) = 0.0; lg(1) = 0.0; lg(2) = -9.81; /* Compute the torque * with eq. (7.147) Spong RMC p. 277 * * */ MAL_S3_VECTOR(,double) firstterm, sndterm, thirdterm, fifthterm,tmp; // Do not fourth term because it is the angular acceleration. /* Constant part */ tmp = CurrentBody.dv_c - lg; tmp = MAL_S3x3_RET_A_by_B(currentBodyR,tmp); CurrentBody.m_Force = tmp * CurrentBody.mass(); /* 2nd term : -f_i x r_{i,ci} */ vector3d lc = CurrentBody.localCenterOfMass(); /* 5th term : w_i x (I_i w_i)*/ MAL_S3x3_MATRIX(,double) lI = CurrentBody.getInertie(); tmp = MAL_S3x3_RET_A_by_B(currentBodyR,CurrentBody.w); tmp = MAL_S3x3_RET_A_by_B(lI,tmp); vector3d lw; MAL_S3x3_C_eq_A_by_B(lw,currentBodyR,CurrentBody.w); MAL_S3_VECTOR_CROSS_PRODUCT(fifthterm,lw,tmp); CurrentBody.m_Torque = MAL_S3x3_RET_A_by_B(currentBodyR,CurrentBody.dw) + fifthterm ; /* Compute with the force * eq. (7.146) Spong RMC p. 277 * fi = R^i_{i+1} * f_{i+1} + m_i * a_{c,i} - m_i * g_i * g_i is the gravity express in the i reference frame. */ matrix4d curtri; if (CurrentBody.joint()!=0) curtri = CurrentBody.joint()->currentTransformation(); else MAL_S4x4_MATRIX_SET_IDENTITY(curtri); matrix4d invcurtri; MAL_S4x4_INVERSE(curtri,invcurtri,double); int IndexChild = CurrentBody.child; while(IndexChild!=-1) { DynamicBodyPrivate *Child = m_listOfBodies[IndexChild]; //cout << "Child Bodies : " << Child->getName() << endl; aRt = MAL_S3x3_RET_A_by_B(Child->R_static,Child->Riip1); //cout << "Riip1: " << aRt << endl; // /* Force computation. */ // R_i_{i+1} f_{i+1} tmp= MAL_S3x3_RET_A_by_B(aRt, Child->m_Force); CurrentBody.m_Force += tmp; /* Torque computation. */ /* 1st term : R^i_{i+1} t_{i+1} */ firstterm = MAL_S3x3_RET_A_by_B(aRt, Child->m_Torque); /* 3rd term : (R_i_{i+1} f_{i+1}) x rip1,ci */ matrix4d curtrip1= Child->joint()->currentTransformation(); matrix4d ip1Mi; MAL_S4x4_C_eq_A_by_B(ip1Mi, invcurtri, curtrip1); /* rip1,ci = (riip1)^(-1)rici Note: rip1,c1 is expressed in the frame of link i. */ vector3d res3d; MAL_S3_VECTOR_ACCESS(res3d,0) = MAL_S3_VECTOR_ACCESS(lc,0)- MAL_S4x4_MATRIX_ACCESS_I_J(ip1Mi,0,3); MAL_S3_VECTOR_ACCESS(res3d,1) = MAL_S3_VECTOR_ACCESS(lc,1) - MAL_S4x4_MATRIX_ACCESS_I_J(ip1Mi,1,3) ; MAL_S3_VECTOR_ACCESS(res3d,2) = MAL_S3_VECTOR_ACCESS(lc,2)- MAL_S4x4_MATRIX_ACCESS_I_J(ip1Mi,2,3); MAL_S3_VECTOR_CROSS_PRODUCT(thirdterm,tmp, res3d); CurrentBody.m_Torque += firstterm + thirdterm; /* Body selection. */ IndexChild = m_listOfBodies[IndexChild]->sister; if (IndexChild!=-1) Child=m_listOfBodies[IndexChild]; } //vector3d lc = CurrentBody.w_c; MAL_S3_VECTOR_CROSS_PRODUCT(sndterm,CurrentBody.m_Force, lc); CurrentBody.m_Torque = CurrentBody.m_Torque - sndterm; // Update the vector related to the computed quantities. for(unsigned int i=0;i<m_StateVectorToJoint.size();i++) { unsigned int StateRankComputed=false; JointPrivate * aJoint = (JointPrivate *)m_JointVector[m_StateVectorToJoint[i]]; if (aJoint!=0) { DynamicBodyPrivate *aDB = (DynamicBodyPrivate *) aJoint->linkedBody(); if (aDB!=0) { StateRankComputed = true; for(unsigned int k=0;k<3;k++) { m_Forces(i,k)=aDB->m_Force[k]; m_Torques(i,k) = aDB->m_Torque[k]; } } } if (!StateRankComputed) { for(unsigned int k=0;k<3;k++) { m_Forces(i,k)=0.0; m_Torques(i,k)=0.0; } } } } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright UMC Utrecht and contributors * * 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. * *=========================================================================*/ #ifndef __xoutbase_hxx #define __xoutbase_hxx #include "xoutbase.h" namespace xoutlibrary { using namespace std; /** * ********************* Constructor **************************** */ template< class charT, class traits > xoutbase< charT, traits >::xoutbase() { this->m_Call = false; } // end Constructor /** * ********************* Destructor ***************************** */ template< class charT, class traits > xoutbase< charT, traits >::~xoutbase() { //nothing } // end Destructor /** * ********************* operator[] ***************************** */ template< class charT, class traits > xoutbase< charT, traits > & xoutbase< charT, traits >::operator[]( const char * cellname ) { return this->SelectXCell( cellname ); } // end operator[] /** * ******************** WriteBufferedData *********************** * * This method can be overriden in inheriting classes. They * could for example define a specific order in which the * cells are flushed. */ template< class charT, class traits > void xoutbase< charT, traits >::WriteBufferedData( void ) { /** Update the target c-streams. */ for( CStreamMapIteratorType cit = this->m_CTargetCells.begin(); cit != this->m_CTargetCells.end(); ++cit ) { *( cit->second ) << flush; } /** WriteBufferedData of the target xout-objects. */ for( XStreamMapIteratorType xit = this->m_XTargetCells.begin(); xit != this->m_XTargetCells.end(); ++xit ) { ( *( xit->second ) ).WriteBufferedData(); } } // end WriteBufferedData /** * **************** AddTargetCell (ostream_type) **************** */ template< class charT, class traits > int xoutbase< charT, traits >::AddTargetCell( const char * name, ostream_type * cell ) { int returndummy = 1; if( this->m_CTargetCells.count( name ) == 0 ) { this->m_CTargetCells.insert( CStreamMapEntryType( name, cell ) ); } if( this->m_CTargetCells.count( name ) > 0 ) { returndummy = 0; } return returndummy; } // end AddTargetCell /** * **************** AddTargetCell (xoutbase) ******************** */ template< class charT, class traits > int xoutbase< charT, traits >::AddTargetCell( const char * name, Self * cell ) { int returndummy = 1; if( this->m_XTargetCells.count( name ) == 0 ) { this->m_XTargetCells.insert( XStreamMapEntryType( name, cell ) ); } if( this->m_XTargetCells.count( name ) > 0 ) { returndummy = 0; } return returndummy; } // end AddTargetCell /** * ***************** RemoveTargetCell *************************** */ template< class charT, class traits > int xoutbase< charT, traits >::RemoveTargetCell( const char * name ) { int returndummy = 1; if( this->m_XTargetCells.count( name ) ) { this->m_XTargetCells.erase( name ); returndummy = 0; } if( this->m_CTargetCells.count( name ) ) { this->m_CTargetCells.erase( name ); returndummy = 0; } return returndummy; } // end RemoveTargetCell /** * **************** SetTargetCells (ostream_types) ************** */ template< class charT, class traits > void xoutbase< charT, traits >::SetTargetCells( const CStreamMapType & cellmap ) { this->m_CTargetCells = cellmap; } // end SetTargetCells /** * **************** SetTargetCells (xout objects) *************** */ template< class charT, class traits > void xoutbase< charT, traits >::SetTargetCells( const XStreamMapType & cellmap ) { this->m_XTargetCells = cellmap; } // end SetTargetCells /** * **************** AddOutput (ostream_type) ******************** */ template< class charT, class traits > int xoutbase< charT, traits >::AddOutput( const char * name, ostream_type * output ) { int returndummy = 1; if( this->m_COutputs.count( name ) == 0 ) { this->m_COutputs.insert( CStreamMapEntryType( name, output ) ); } if( this->m_COutputs.count( name ) ) { returndummy = 0; } return returndummy; } // end AddOutput /** * **************** AddOutput (xoutbase) ************************ */ template< class charT, class traits > int xoutbase< charT, traits >::AddOutput( const char * name, Self * output ) { int returndummy = 1; if( this->m_XOutputs.count( name ) == 0 ) { this->m_XOutputs.insert( XStreamMapEntryType( name, output ) ); } if( this->m_XOutputs.count( name ) ) { returndummy = 0; } return returndummy; } // end AddOutput /** * *********************** RemoveOutput ************************* */ template< class charT, class traits > int xoutbase< charT, traits >::RemoveOutput( const char * name ) { int returndummy = 1; if( this->m_XOutputs.count( name ) ) { this->m_XOutputs.erase( name ); returndummy = 0; } if( this->m_COutputs.count( name ) ) { this->m_COutputs.erase( name ); returndummy = 0; } return returndummy; } // end RemoveOutput /** * ******************* SetOutputs (ostream_types) *************** */ template< class charT, class traits > void xoutbase< charT, traits >::SetOutputs( const CStreamMapType & outputmap ) { this->m_COutputs = outputmap; } // end SetOutputs /** * **************** SetOutputs (xoutobjects) ******************** */ template< class charT, class traits > void xoutbase< charT, traits >::SetOutputs( const XStreamMapType & outputmap ) { this->m_XOutputs = outputmap; } // end SetOutputs /** * ************************ SelectXCell ************************* * * Returns a target cell. */ template< class charT, class traits > xoutbase< charT, traits > & xoutbase< charT, traits >::SelectXCell( const char * name ) { if( this->m_XTargetCells.count( name ) ) { return *( this->m_XTargetCells[ name ] ); } else { return *this; } } // end SelectXCell /** * **************** GetOutputs (map of xoutobjects) ************* */ template< class charT, class traits > const typename xoutbase< charT, traits >::XStreamMapType & xoutbase< charT, traits >::GetXOutputs( void ) { return this->m_XOutputs; } // end GetOutputs /** * **************** GetOutputs (map of c-streams) *************** */ template< class charT, class traits > const typename xoutbase< charT, traits >::CStreamMapType & xoutbase< charT, traits >::GetCOutputs( void ) { return this->m_COutputs; } // end GetOutputs /** * **************** GetCTargetCells ************* */ template< class charT, class traits > const typename xoutbase< charT, traits >::CStreamMapType & xoutbase< charT, traits >::GetCTargetCells( void ) { return this->m_CTargetCells; } /** * **************** GetXTargetCells *************** */ template< class charT, class traits > const typename xoutbase< charT, traits >::XStreamMapType & xoutbase< charT, traits >::GetXTargetCells( void ) { return this->m_XTargetCells; } } // end namespace xoutlibrary #endif // end #ifndef __xoutbase_hxx <commit_msg>BUG: Fix an issue with xout introduced by a recent commit where the same key can be added to both COutputs and XOutputs<commit_after>/*========================================================================= * * Copyright UMC Utrecht and contributors * * 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. * *=========================================================================*/ #ifndef __xoutbase_hxx #define __xoutbase_hxx #include "xoutbase.h" namespace xoutlibrary { using namespace std; /** * ********************* Constructor **************************** */ template< class charT, class traits > xoutbase< charT, traits >::xoutbase() { this->m_Call = false; } // end Constructor /** * ********************* Destructor ***************************** */ template< class charT, class traits > xoutbase< charT, traits >::~xoutbase() { //nothing } // end Destructor /** * ********************* operator[] ***************************** */ template< class charT, class traits > xoutbase< charT, traits > & xoutbase< charT, traits >::operator[]( const char * cellname ) { return this->SelectXCell( cellname ); } // end operator[] /** * ******************** WriteBufferedData *********************** * * This method can be overriden in inheriting classes. They * could for example define a specific order in which the * cells are flushed. */ template< class charT, class traits > void xoutbase< charT, traits >::WriteBufferedData( void ) { /** Update the target c-streams. */ for( CStreamMapIteratorType cit = this->m_CTargetCells.begin(); cit != this->m_CTargetCells.end(); ++cit ) { *( cit->second ) << flush; } /** WriteBufferedData of the target xout-objects. */ for( XStreamMapIteratorType xit = this->m_XTargetCells.begin(); xit != this->m_XTargetCells.end(); ++xit ) { ( *( xit->second ) ).WriteBufferedData(); } } // end WriteBufferedData /** * **************** AddTargetCell (ostream_type) **************** */ template< class charT, class traits > int xoutbase< charT, traits >::AddTargetCell( const char * name, ostream_type * cell ) { int returndummy = 1; if( this->m_XTargetCells.count( name ) ) { /** an X-cell with the same name already exists */ returndummy = 2; } else { this->m_CTargetCells.insert( CStreamMapEntryType( name, cell ) ); returndummy = 0; } return returndummy; } // end AddTargetCell /** * **************** AddTargetCell (xoutbase) ******************** */ template< class charT, class traits > int xoutbase< charT, traits >::AddTargetCell( const char * name, Self * cell ) { int returndummy = 1; if( this->m_CTargetCells.count( name ) ) { /** a C-cell with the same name already exists */ returndummy = 2; } else { this->m_XTargetCells.insert( XStreamMapEntryType( name, cell ) ); returndummy = 0; } return returndummy; } // end AddTargetCell /** * ***************** RemoveTargetCell *************************** */ template< class charT, class traits > int xoutbase< charT, traits >::RemoveTargetCell( const char * name ) { int returndummy = 1; if( this->m_XTargetCells.count( name ) ) { this->m_XTargetCells.erase( name ); returndummy = 0; } if( this->m_CTargetCells.count( name ) ) { this->m_CTargetCells.erase( name ); returndummy = 0; } return returndummy; } // end RemoveTargetCell /** * **************** SetTargetCells (ostream_types) ************** */ template< class charT, class traits > void xoutbase< charT, traits >::SetTargetCells( const CStreamMapType & cellmap ) { this->m_CTargetCells = cellmap; } // end SetTargetCells /** * **************** SetTargetCells (xout objects) *************** */ template< class charT, class traits > void xoutbase< charT, traits >::SetTargetCells( const XStreamMapType & cellmap ) { this->m_XTargetCells = cellmap; } // end SetTargetCells /** * **************** AddOutput (ostream_type) ******************** */ template< class charT, class traits > int xoutbase< charT, traits >::AddOutput( const char * name, ostream_type * output ) { int returndummy = 1; if( this->m_XOutputs.count( name ) ) { returndummy = 2; } else { this->m_COutputs.insert( CStreamMapEntryType( name, output ) ); returndummy = 0; } return returndummy; } // end AddOutput /** * **************** AddOutput (xoutbase) ************************ */ template< class charT, class traits > int xoutbase< charT, traits >::AddOutput( const char * name, Self * output ) { int returndummy = 1; if( this->m_COutputs.count( name ) ) { returndummy = 2; } else { this->m_XOutputs.insert( XStreamMapEntryType( name, output ) ); returndummy = 0; } return returndummy; } // end AddOutput /** * *********************** RemoveOutput ************************* */ template< class charT, class traits > int xoutbase< charT, traits >::RemoveOutput( const char * name ) { int returndummy = 1; if( this->m_XOutputs.count( name ) ) { this->m_XOutputs.erase( name ); returndummy = 0; } if( this->m_COutputs.count( name ) ) { this->m_COutputs.erase( name ); returndummy = 0; } return returndummy; } // end RemoveOutput /** * ******************* SetOutputs (ostream_types) *************** */ template< class charT, class traits > void xoutbase< charT, traits >::SetOutputs( const CStreamMapType & outputmap ) { this->m_COutputs = outputmap; } // end SetOutputs /** * **************** SetOutputs (xoutobjects) ******************** */ template< class charT, class traits > void xoutbase< charT, traits >::SetOutputs( const XStreamMapType & outputmap ) { this->m_XOutputs = outputmap; } // end SetOutputs /** * ************************ SelectXCell ************************* * * Returns a target cell. */ template< class charT, class traits > xoutbase< charT, traits > & xoutbase< charT, traits >::SelectXCell( const char * name ) { if( this->m_XTargetCells.count( name ) ) { return *( this->m_XTargetCells[ name ] ); } else { return *this; } } // end SelectXCell /** * **************** GetOutputs (map of xoutobjects) ************* */ template< class charT, class traits > const typename xoutbase< charT, traits >::XStreamMapType & xoutbase< charT, traits >::GetXOutputs( void ) { return this->m_XOutputs; } // end GetOutputs /** * **************** GetOutputs (map of c-streams) *************** */ template< class charT, class traits > const typename xoutbase< charT, traits >::CStreamMapType & xoutbase< charT, traits >::GetCOutputs( void ) { return this->m_COutputs; } // end GetOutputs /** * **************** GetCTargetCells ************* */ template< class charT, class traits > const typename xoutbase< charT, traits >::CStreamMapType & xoutbase< charT, traits >::GetCTargetCells( void ) { return this->m_CTargetCells; } /** * **************** GetXTargetCells *************** */ template< class charT, class traits > const typename xoutbase< charT, traits >::XStreamMapType & xoutbase< charT, traits >::GetXTargetCells( void ) { return this->m_XTargetCells; } } // end namespace xoutlibrary #endif // end #ifndef __xoutbase_hxx <|endoftext|>
<commit_before><commit_msg>Further prune optimizations.<commit_after><|endoftext|>
<commit_before>#include "GolfBall.hpp" #include "../Resources.hpp" #include "Default3D.vert.hpp" #include "Default3D.geom.hpp" #include "Default3D.frag.hpp" #include "glm/gtc/constants.hpp" #include "../Util/Log.hpp" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/quaternion.hpp> GolfBall::GolfBall(BallType ballType, TerrainObject* terrain) : ModelObject(modelGeometry = Resources().CreateOBJModel("Resources/Models/GolfBall/GolfBall.obj"), "Resources/Models/GolfBall/Diffuse.png", "Resources/Models/GolfBall/Normal.png", "Resources/Models/GolfBall/Specular.png") { active = false; restitution = ballType == TWOPIECE ? 0.78f : 0.68f; this->terrain = terrain; groundLevel = this->terrain->Position().y; origin = glm::vec3(1.f, 0.f, 1.f); /// @todo Mass based on explosive material. mass = 0.0459f; this->ballType = ballType; sphere.position = Position(); SetRadius(0.0214f); } GolfBall::~GolfBall() { Resources().FreeOBJModel(modelGeometry); } void GolfBall::Reset(){ active = false; velocity = glm::vec3(0.f, 0.f, 0.f); angularVelocity = glm::vec3(0.f, 0.f, 0.f); SetPosition(origin); sphere.position = Position(); orientation = glm::quat(); } void GolfBall::Update(double time, const glm::vec3& wind, std::vector<PlayerObject>& players) { if (active) { Move(static_cast<float>(time)* velocity); sphere.position = Position(); if (glm::length(angularVelocity) > 0.0001f) { glm::quat deltaQuat = glm::angleAxis(static_cast<float>(time)* glm::length(angularVelocity), glm::normalize(angularVelocity)); orientation = deltaQuat * orientation; } // Check for collision groundLevel = terrain->GetY(Position().x, Position().z); if (glm::length(velocity) > 0.0001f && (sphere.position.y - sphere.radius) < groundLevel){ float vCritical = 0.3f; float e = 0.55f; float muSliding = 0.51f; float muRolling = 0.096f; SetPosition(Position().x, groundLevel + sphere.radius, Position().z); sphere.position = Position(); //glm::vec3 eRoh = glm::normalize(glm::vec3(0.f, 1.f, 0.f)); glm::vec3 eRoh = terrain->GetNormal(Position().x, Position().y); Log() << eRoh << "\n"; glm::vec3 tangentialVelocity = velocity - glm::dot(velocity, eRoh) * eRoh; glm::vec3 eFriction = glm::vec3(0.f, 0.f, 0.f); if (glm::length(glm::cross(eRoh, angularVelocity) + tangentialVelocity) > 0.0001f) eFriction = glm::normalize(sphere.radius * glm::cross(eRoh, angularVelocity) + tangentialVelocity); float vRoh = glm::dot(velocity, eRoh); float deltaU = -(e + 1.f) * vRoh; glm::vec3 angularDirection = glm::cross(eRoh, glm::normalize(tangentialVelocity)); float w = glm::dot(angularVelocity, angularDirection); if (fabs(vRoh) < vCritical && glm::length(tangentialVelocity) > 0.0001f) { if (w * sphere.radius + 0.0001f < glm::length(tangentialVelocity)) { // Sliding. velocity = tangentialVelocity - static_cast<float>(time)* (eFriction * muSliding * 9.82f); angularVelocity += (5.f / 2.f) * (muSliding * 9.82f / sphere.radius * static_cast<float>(time)) * angularDirection; } else { // Rolling. velocity = tangentialVelocity - static_cast<float>(time)* (glm::normalize(tangentialVelocity) * muRolling * 9.82f); float tangentialVelocityAfter = glm::length(velocity - glm::dot(velocity, eRoh) * eRoh); angularVelocity = (glm::length(tangentialVelocityAfter) / sphere.radius) * angularDirection; // Stopped. if (glm::length(velocity) < 0.005f) { velocity = glm::vec3(0.f, 0.f, 0.f); angularVelocity = glm::vec3(0.f, 0.f, 0.f); } } } else { float deltaTime = pow(mass * mass / (fabs(vRoh) * sphere.radius), 0.2f) * 0.00251744f; float velocityRoh = glm::dot(velocity, eRoh); float velocityNormal = glm::dot(velocity, eFriction); float uRoh = -e*velocityRoh; float deltauRoh = uRoh - (velocityRoh); float deltaUn = muSliding*deltauRoh; float rollUn = (5.f / 7.f)*velocityNormal; float slideUn = velocityNormal - deltaUn; if (velocityNormal > rollUn) { velocity = uRoh*eRoh + rollUn*eFriction; angularVelocity += muRolling * (deltaU + 9.82f * deltaTime) / sphere.radius * glm::cross(eRoh, eFriction); } else { velocity = uRoh*eRoh + slideUn*eFriction; angularVelocity += muSliding * (deltaU + 9.82f * deltaTime) / sphere.radius * glm::cross(eRoh, eFriction); } } } // Calculate magnus force. float v = glm::length(velocity); float u = glm::length(velocity - wind); float w = glm::length(angularVelocity); glm::vec3 eU = (velocity - wind) / u; glm::vec3 magnusForce = glm::vec3(0.f, 0.f, 0.f); if (u > 0.f && v > 0.f && w > 0.f) { float Cm = (sqrt(1.f + 0.31f * (w / v)) - 1.f) / 20.f; float Fm = 0.5f * Cm * 1.23f * area * u * u; magnusForce = Fm * glm::cross(eU, glm::normalize(angularVelocity)); } // Calculate drag force. float cD; if (ballType == TWOPIECE) cD = v < 65.f ? -0.0051f * v + 0.53f : 0.21f; else cD = v < 60.f ? -0.0084f * v + 0.73f : 0.22f; glm::vec3 dragForce = glm::vec3(0.f, 0.f, 0.f); if (u > 0.f) dragForce = -0.5f * 1.23f * area * cD * u * u * eU; // Calculate gravitational force. glm::vec3 gravitationForce = glm::vec3(0.f, mass * -9.82f, 0.f); // Get acceleration from total force. glm::vec3 acceleration = (dragForce + magnusForce + gravitationForce) / mass; velocity += acceleration * static_cast<float>(time); } } void GolfBall::Render(Camera* camera, const glm::vec2& screenSize, const glm::vec4& clippingPlane) const{ ModelObject::Render(camera, screenSize, clippingPlane); } void GolfBall::Explode(std::vector<PlayerObject>& players, int playerIndex){ //@TODO: Set mass equivalent depending on material used. float equivalenceFactor = 1.0f; float massEquivalent = mass*equivalenceFactor; for (auto &player : players){ glm::vec3 distanceV = (Position() - player.Position()); float distance = glm::length(distanceV); //pow(meq, 1.f/3.f) => cube root of meq float z = distance / (pow(massEquivalent, 1.f / 3.f)); float alpha = 1 + pow((z / 4.5f), 2.f); float beta = 1 + pow((z / 0.048f), 2.f); float gamma = 1 + pow((z / 1.35f), 2.f); float delta = 1 + pow((z / 0.32f), 2.f); float Pf = 8.08f*pow(10.f, 7.f)*alpha; Pf = Pf / sqrt(beta*gamma*delta); player.TakeDamage(Pf); } origin = players[playerIndex].Position(); Reset(); } void GolfBall::Strike(ClubType club, const glm::vec3& clubVelocity) { active = true; // Club velocity in strike plane. float v = glm::length(clubVelocity); if (v > 0.f) { float sinLoft = sin(club.loft); float cosLoft = cos(club.loft); // Ball velocity. float massCoefficient = club.mass / (club.mass + mass); float Up = (1.f + restitution) * massCoefficient * v * cosLoft; float Un = (2.f / 7.f) * massCoefficient * v * sinLoft; // Go back from strike plane to 3D. glm::vec3 forward = clubVelocity / v; glm::vec3 up = glm::cross(forward, glm::cross(glm::vec3(0.f, 1.f, 0.f), forward)); glm::vec3 ep = glm::normalize(cosLoft * forward + sinLoft * up); glm::vec3 en = glm::normalize(sinLoft * forward - cosLoft * up); // Total velocity. velocity = Up * ep + Un * en; angularVelocity = -Un / sphere.radius * glm::cross(ep, en); } else { velocity = glm::vec3(0.f, 0.f, 0.f); angularVelocity = glm::vec3(0.f, 0.f, 0.f); } } void GolfBall::SetRadius(float radius) { sphere.radius = radius; SetScale(glm::vec3(radius, radius, radius)); area = glm::pi<float>() * radius * radius; } glm::mat4 GolfBall::Orientation() const { return glm::toMat4(orientation); } <commit_msg>Stuff<commit_after>#include "GolfBall.hpp" #include "../Resources.hpp" #include "Default3D.vert.hpp" #include "Default3D.geom.hpp" #include "Default3D.frag.hpp" #include "glm/gtc/constants.hpp" #include "../Util/Log.hpp" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/quaternion.hpp> GolfBall::GolfBall(BallType ballType, TerrainObject* terrain) : ModelObject(modelGeometry = Resources().CreateOBJModel("Resources/Models/GolfBall/GolfBall.obj"), "Resources/Models/GolfBall/Diffuse.png", "Resources/Models/GolfBall/Normal.png", "Resources/Models/GolfBall/Specular.png") { active = false; restitution = ballType == TWOPIECE ? 0.78f : 0.68f; this->terrain = terrain; groundLevel = this->terrain->Position().y; origin = glm::vec3(1.f, 0.f, 1.f); /// @todo Mass based on explosive material. mass = 0.0459f; this->ballType = ballType; sphere.position = Position(); SetRadius(0.0214f); } GolfBall::~GolfBall() { Resources().FreeOBJModel(modelGeometry); } void GolfBall::Reset(){ active = false; velocity = glm::vec3(0.f, 0.f, 0.f); angularVelocity = glm::vec3(0.f, 0.f, 0.f); SetPosition(origin); sphere.position = Position(); orientation = glm::quat(); } void GolfBall::Update(double time, const glm::vec3& wind, std::vector<PlayerObject>& players) { if (active) { Move(static_cast<float>(time)* velocity); sphere.position = Position(); if (glm::length(angularVelocity) > 0.0001f) { glm::quat deltaQuat = glm::angleAxis(static_cast<float>(time)* glm::length(angularVelocity), glm::normalize(angularVelocity)); orientation = deltaQuat * orientation; } glm::vec3 dragForce, magnusForce = glm::vec3(0.f, 0.f, 0.f); // Check for collision groundLevel = terrain->GetY(Position().x, Position().z); if (glm::length(velocity) > 0.0001f && (sphere.position.y - sphere.radius) < groundLevel){ float vCritical = 0.3f; float e = 0.55f; float muSliding = 0.51f; float muRolling = 0.096f; SetPosition(Position().x, groundLevel + sphere.radius, Position().z); sphere.position = Position(); //glm::vec3 eRoh = glm::normalize(glm::vec3(0.f, 1.f, 0.f)); glm::vec3 eRoh = terrain->GetNormal(Position().x, Position().z); Log() << eRoh << "\n"; glm::vec3 tangentialVelocity = velocity - glm::dot(velocity, eRoh) * eRoh; glm::vec3 eFriction = glm::vec3(0.f, 0.f, 0.f); if (glm::length(glm::cross(eRoh, angularVelocity) + tangentialVelocity) > 0.0001f) eFriction = glm::normalize(sphere.radius * glm::cross(eRoh, angularVelocity) + tangentialVelocity); float vRoh = glm::dot(velocity, eRoh); float deltaU = -(e + 1.f) * vRoh; glm::vec3 angularDirection = glm::cross(eRoh, glm::normalize(tangentialVelocity)); float w = glm::dot(angularVelocity, angularDirection); if (fabs(vRoh) < vCritical && glm::length(tangentialVelocity) > 0.0001f) { if (w * sphere.radius + 0.0001f < glm::length(tangentialVelocity)) { // Sliding. velocity = tangentialVelocity - static_cast<float>(time)* (eFriction * muSliding * 9.82f); angularVelocity += (5.f / 2.f) * (muSliding * 9.82f / sphere.radius * static_cast<float>(time)) * angularDirection; } else { // Rolling. velocity = tangentialVelocity - static_cast<float>(time)* (glm::normalize(tangentialVelocity) * muRolling * 9.82f); float tangentialVelocityAfter = glm::length(velocity - glm::dot(velocity, eRoh) * eRoh); angularVelocity = (glm::length(tangentialVelocityAfter) / sphere.radius) * angularDirection; // Stopped. if (glm::length(velocity) < 0.005f) { velocity = glm::vec3(0.f, 0.f, 0.f); angularVelocity = glm::vec3(0.f, 0.f, 0.f); } } } else { float deltaTime = pow(mass * mass / (fabs(vRoh) * sphere.radius), 0.2f) * 0.00251744f; float velocityRoh = glm::dot(velocity, eRoh); float velocityNormal = glm::dot(velocity, eFriction); float uRoh = -e*velocityRoh; float deltauRoh = uRoh - (velocityRoh); float deltaUn = muSliding*deltauRoh; float rollUn = (5.f / 7.f)*velocityNormal; float slideUn = velocityNormal - deltaUn; if (velocityNormal > rollUn){ velocity = uRoh*eRoh + rollUn*eFriction; angularVelocity += muRolling * (deltaU + 9.82f * deltaTime) / sphere.radius * glm::cross(eRoh, eFriction); } else { velocity = uRoh*eRoh + slideUn*eFriction; angularVelocity += muSliding * (deltaU + 9.82f * deltaTime) / sphere.radius * glm::cross(eRoh, eFriction); } } } else { // Calculate magnus force. float v = glm::length(velocity); float u = glm::length(velocity - wind); float w = glm::length(angularVelocity); glm::vec3 eU = (velocity - wind) / u; magnusForce = glm::vec3(0.f, 0.f, 0.f); if (u > 0.f && v > 0.f && w > 0.f) { float Cm = (sqrt(1.f + 0.31f * (w / v)) - 1.f) / 20.f; float Fm = 0.5f * Cm * 1.23f * area * u * u; magnusForce = Fm * glm::cross(eU, glm::normalize(angularVelocity)); } // Calculate drag force. float cD; if (ballType == TWOPIECE) cD = v < 65.f ? -0.0051f * v + 0.53f : 0.21f; else cD = v < 60.f ? -0.0084f * v + 0.73f : 0.22f; dragForce = glm::vec3(0.f, 0.f, 0.f); if (u > 0.f) dragForce = -0.5f * 1.23f * area * cD * u * u * eU; } // Calculate gravitational force. glm::vec3 gravitationForce = glm::vec3(0.f, mass * -9.82f, 0.f); // Get acceleration from total force. glm::vec3 acceleration = (dragForce + magnusForce + gravitationForce) / mass; velocity += acceleration * static_cast<float>(time); } } void GolfBall::Render(Camera* camera, const glm::vec2& screenSize, const glm::vec4& clippingPlane) const{ ModelObject::Render(camera, screenSize, clippingPlane); } void GolfBall::Explode(std::vector<PlayerObject>& players, int playerIndex){ //@TODO: Set mass equivalent depending on material used. float equivalenceFactor = 1.0f; float massEquivalent = mass*equivalenceFactor; for (auto &player : players){ glm::vec3 distanceV = (Position() - player.Position()); float distance = glm::length(distanceV); //pow(meq, 1.f/3.f) => cube root of meq float z = distance / (pow(massEquivalent, 1.f / 3.f)); float alpha = 1 + pow((z / 4.5f), 2.f); float beta = 1 + pow((z / 0.048f), 2.f); float gamma = 1 + pow((z / 1.35f), 2.f); float delta = 1 + pow((z / 0.32f), 2.f); float Pf = 8.08f*pow(10.f, 7.f)*alpha; Pf = Pf / sqrt(beta*gamma*delta); player.TakeDamage(Pf); } origin = players[playerIndex].Position(); Reset(); } void GolfBall::Strike(ClubType club, const glm::vec3& clubVelocity) { active = true; // Club velocity in strike plane. float v = glm::length(clubVelocity); if (v > 0.f) { float sinLoft = sin(club.loft); float cosLoft = cos(club.loft); // Ball velocity. float massCoefficient = club.mass / (club.mass + mass); float Up = (1.f + restitution) * massCoefficient * v * cosLoft; float Un = (2.f / 7.f) * massCoefficient * v * sinLoft; // Go back from strike plane to 3D. glm::vec3 forward = clubVelocity / v; glm::vec3 up = glm::cross(forward, glm::cross(glm::vec3(0.f, 1.f, 0.f), forward)); glm::vec3 ep = glm::normalize(cosLoft * forward + sinLoft * up); glm::vec3 en = glm::normalize(sinLoft * forward - cosLoft * up); // Total velocity. velocity = Up * ep + Un * en; angularVelocity = -Un / sphere.radius * glm::cross(ep, en); } else { velocity = glm::vec3(0.f, 0.f, 0.f); angularVelocity = glm::vec3(0.f, 0.f, 0.f); } } void GolfBall::SetRadius(float radius) { sphere.radius = radius; SetScale(glm::vec3(radius, radius, radius)); area = glm::pi<float>() * radius * radius; } glm::mat4 GolfBall::Orientation() const { return glm::toMat4(orientation); } <|endoftext|>
<commit_before>/** * COMP 4002 - Assignment 2 * * Task 1: Render a sphere at (100, 10, 100) using perspective projection. * Task 2: Render a hierarchical object beside the sphere from Task 1. * Task 3: Create a camera class with yaw, pitch and roll. * Task 4: Bonus: Use keys 1-5 to select robot arm, then z & x to move arm piece. * * Author: Ryan Seys - 100817604 */ #ifdef __APPLE_CC__ #include <GLUT/glut.h> #define glewInit(); // Don't glewInit on Mac #else #include <glew.h> #include <GL\freeglut.h> #define glewInit(); glewInit(); #endif #include <stdio.h> #include <cmath> #include "math.h" #include "Shader.h" #include "ryan_sphere.h" #include "ryan_cube.h" #include "ryan_camera.h" #include "ryan_matrix.h" #include "ryan_robotarm.h" GLdouble delta = 0.1; // how much to move the object (Task 2) GLdouble objX = 0.0; GLdouble objY = 0.0; GLdouble objZ = 0.0; GLint robotPartSelected = -1; // nothing initially selected GLfloat ROBOT_ROTATE_DEG = 1.0; GLuint shaderProg; GLint windowHeight, windowWidth; const GLfloat PITCH_AMT = 1.0; // degrees up and down const GLfloat YAW_AMT = 1.0; // degrees right and left const GLfloat FORWARD_AMT = 0.2; Vector3f position (106, 16, 106); Vector3f lookAtPoint(100, 10, 100); Vector3f upVector(0, 1, 0); // initialize camera Camera * cam; GLdouble rotateDelta1 = 0.1; // Rotate first sphere 0.1 degrees per frame GLdouble rotateDelta2 = 0.2; // Rotate second sphere 0.2 degrees per frame GLdouble sphere1Rotate = 0.0; GLdouble sphere2Rotate = 0.0; GLint timerMs = 20; // Robot arm RobotArm * robotarm; SolidSphere * sphere0; SolidSphere * sphere1; SolidSphere * sphere2; SolidCube * cube; /** * When a regular (not special) key is pressed. */ void keyboardFunc(unsigned char key, int x, int y) { switch (key) { case '1': { robotPartSelected = 1; break; } case '2': { robotPartSelected = 2; break; } case '3': { robotPartSelected = 3; break; } case '4': { robotPartSelected = 4; break; } case '5': { robotPartSelected = 5; break; } case 'i': { objX -= delta; break; } case 'j': { objZ -= delta; break; } case 'k': { objZ += delta; break; } case 'l': { objX += delta; break; } case 'a': { // Roll camera counter-clockwise // Yes, this is backward (i.e. -PITCH_AMT vs. PITCH_AMT to the assignment // description but it makes more sense when using the keyboard controls. cam->roll(-PITCH_AMT); break; } case 'd': { // Roll camera counter-clockwise // Yes, this is backward (i.e. PITCH_AMT vs. -PITCH_AMT to the assignment // description but it makes more sense when using the keyboard controls. cam->roll(PITCH_AMT); break; } case 'w': { // Move camera forward along lookAtVector cam->moveForward(FORWARD_AMT); break; } case 's': { // Move camera backward along lookAtVector cam->moveForward(-FORWARD_AMT); break; } case 'z': { // Rotate robot part +1 degree robotarm->rotatePart(robotPartSelected, ROBOT_ROTATE_DEG); break; } case 'x': { // Rotate robot part -1 degree robotarm->rotatePart(robotPartSelected, -ROBOT_ROTATE_DEG); break; } default: return; } glutPostRedisplay(); } /** * Rendering the window. */ void display() { glEnable(GL_DEPTH_TEST); glClearColor(0.0, 0.0, 0,1); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); Matrix4f initTranslateMat = Matrix4f::translation(100, 10, 100); // setting up the transformaiton of the object from model coord. system to world coord. Matrix4f worldMat = cam->getViewMatrix() * initTranslateMat; glUseProgram(shaderProg); sphere0->applyTransformation(worldMat); Matrix4f objMat = Matrix4f::translation(objX, objY, objZ); sphere1->applyTransformation(worldMat); sphere1->translate(-0.7, 1.0, -1.25); sphere1->applyTransformation(objMat); sphere1->rotateY(sphere1Rotate); sphere2->applyTransformation(worldMat); sphere2->translate(0.7, 1.0, -1.25); sphere2->applyTransformation(objMat); sphere2->rotateY(sphere2Rotate); cube->applyTransformation(worldMat); cube->applyTransformation(objMat); cube->translate(-0.25, -0.25, -1.6); robotarm->applyTransformation(worldMat); robotarm->applyTransformation(Matrix4f::translation(-3, 0.0, 1.0)); // draw them spheres, applying all transformations sphere0->drawSphere(shaderProg); sphere1->drawSphere(shaderProg); sphere2->drawSphere(shaderProg); cube->draw(shaderProg); robotarm->draw(shaderProg); glUseProgram(0); glFlush(); glutSwapBuffers(); } /** * When the window reshapes to a new size, you must update the camera. * * @param w the window new width * @param h the window new height */ void reshape(GLint w, GLint h) { cam->reshape(w, h); } /** * Every time the timer ticks */ void renderTick(int value) { sphere1Rotate = fmod(sphere1Rotate + rotateDelta1, 360); sphere2Rotate = fmod(sphere2Rotate - rotateDelta2, 360); glutPostRedisplay(); glutTimerFunc(timerMs, renderTick, 1); // restart the timer } void pressSpecialKey(int key, int xx, int yy) { switch (key) { case GLUT_KEY_UP: { cam->pitch(PITCH_AMT); break; } case GLUT_KEY_DOWN: { cam->pitch(-PITCH_AMT); break; } case GLUT_KEY_RIGHT: { cam->yaw(YAW_AMT); break; } case GLUT_KEY_LEFT: { cam->yaw(-YAW_AMT); break; } } glutPostRedisplay(); } /** * Main. */ int main(int argc, char** argv) { Shader s; glutInit(&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(800, 600); glutCreateWindow("COMP 4002 - Assignment 2 - Ryan Seys"); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboardFunc); glutSpecialFunc(pressSpecialKey); glewInit(); s.createShaderProgram("sphere.vert", "sphere.frag", &shaderProg); // For Task 1. sphere0 = new SolidSphere(0.75, 24, 24); // Object for Task 2. cube = new SolidCube(1.0, 0.5, 0.5); sphere1 = new SolidSphere(0.75, 24, 24); sphere2 = new SolidSphere(0.75, 24, 24); // For Task 3. cam = new Camera(position, lookAtPoint, upVector); // Robot arm for Task 4 (Bonus) robotarm = new RobotArm(); glutPostRedisplay(); glEnable(GL_DEPTH_TEST); glutTimerFunc(1, renderTick, 1); glutMainLoop(); return 0; } <commit_msg>change define name<commit_after>/** * COMP 4002 - Assignment 2 * * Task 1: Render a sphere at (100, 10, 100) using perspective projection. * Task 2: Render a hierarchical object beside the sphere from Task 1. * Task 3: Create a camera class with yaw, pitch and roll. * Task 4: Bonus: Use keys 1-5 to select robot arm, then z & x to move arm piece. * * Author: Ryan Seys - 100817604 */ #ifdef __APPLE_CC__ #include <GLUT/glut.h> #define INIT_GLEW(); // Don't glewInit on Mac #else #include <glew.h> #include <GL\freeglut.h> #define INIT_GLEW(); glewInit(); #endif #include <stdio.h> #include <cmath> #include "math.h" #include "Shader.h" #include "ryan_sphere.h" #include "ryan_cube.h" #include "ryan_camera.h" #include "ryan_matrix.h" #include "ryan_robotarm.h" GLdouble delta = 0.1; // how much to move the object (Task 2) GLdouble objX = 0.0; GLdouble objY = 0.0; GLdouble objZ = 0.0; GLint robotPartSelected = -1; // nothing initially selected GLfloat ROBOT_ROTATE_DEG = 1.0; GLuint shaderProg; GLint windowHeight, windowWidth; const GLfloat PITCH_AMT = 1.0; // degrees up and down const GLfloat YAW_AMT = 1.0; // degrees right and left const GLfloat FORWARD_AMT = 0.2; Vector3f position (106, 16, 106); Vector3f lookAtPoint(100, 10, 100); Vector3f upVector(0, 1, 0); // initialize camera Camera * cam; GLdouble rotateDelta1 = 0.1; // Rotate first sphere 0.1 degrees per frame GLdouble rotateDelta2 = 0.2; // Rotate second sphere 0.2 degrees per frame GLdouble sphere1Rotate = 0.0; GLdouble sphere2Rotate = 0.0; GLint timerMs = 20; // Robot arm RobotArm * robotarm; SolidSphere * sphere0; SolidSphere * sphere1; SolidSphere * sphere2; SolidCube * cube; /** * When a regular (not special) key is pressed. */ void keyboardFunc(unsigned char key, int x, int y) { switch (key) { case '1': { robotPartSelected = 1; break; } case '2': { robotPartSelected = 2; break; } case '3': { robotPartSelected = 3; break; } case '4': { robotPartSelected = 4; break; } case '5': { robotPartSelected = 5; break; } case 'i': { objX -= delta; break; } case 'j': { objZ -= delta; break; } case 'k': { objZ += delta; break; } case 'l': { objX += delta; break; } case 'a': { // Roll camera counter-clockwise // Yes, this is backward (i.e. -PITCH_AMT vs. PITCH_AMT to the assignment // description but it makes more sense when using the keyboard controls. cam->roll(-PITCH_AMT); break; } case 'd': { // Roll camera counter-clockwise // Yes, this is backward (i.e. PITCH_AMT vs. -PITCH_AMT to the assignment // description but it makes more sense when using the keyboard controls. cam->roll(PITCH_AMT); break; } case 'w': { // Move camera forward along lookAtVector cam->moveForward(FORWARD_AMT); break; } case 's': { // Move camera backward along lookAtVector cam->moveForward(-FORWARD_AMT); break; } case 'z': { // Rotate robot part +1 degree robotarm->rotatePart(robotPartSelected, ROBOT_ROTATE_DEG); break; } case 'x': { // Rotate robot part -1 degree robotarm->rotatePart(robotPartSelected, -ROBOT_ROTATE_DEG); break; } default: return; } glutPostRedisplay(); } /** * Rendering the window. */ void display() { glEnable(GL_DEPTH_TEST); glClearColor(0.0, 0.0, 0,1); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); Matrix4f initTranslateMat = Matrix4f::translation(100, 10, 100); // setting up the transformaiton of the object from model coord. system to world coord. Matrix4f worldMat = cam->getViewMatrix() * initTranslateMat; glUseProgram(shaderProg); sphere0->applyTransformation(worldMat); Matrix4f objMat = Matrix4f::translation(objX, objY, objZ); sphere1->applyTransformation(worldMat); sphere1->translate(-0.7, 1.0, -1.25); sphere1->applyTransformation(objMat); sphere1->rotateY(sphere1Rotate); sphere2->applyTransformation(worldMat); sphere2->translate(0.7, 1.0, -1.25); sphere2->applyTransformation(objMat); sphere2->rotateY(sphere2Rotate); cube->applyTransformation(worldMat); cube->applyTransformation(objMat); cube->translate(-0.25, -0.25, -1.6); robotarm->applyTransformation(worldMat); robotarm->applyTransformation(Matrix4f::translation(-3, 0.0, 1.0)); // draw them spheres, applying all transformations sphere0->drawSphere(shaderProg); sphere1->drawSphere(shaderProg); sphere2->drawSphere(shaderProg); cube->draw(shaderProg); robotarm->draw(shaderProg); glUseProgram(0); glFlush(); glutSwapBuffers(); } /** * When the window reshapes to a new size, you must update the camera. * * @param w the window new width * @param h the window new height */ void reshape(GLint w, GLint h) { cam->reshape(w, h); } /** * Every time the timer ticks */ void renderTick(int value) { sphere1Rotate = fmod(sphere1Rotate + rotateDelta1, 360); sphere2Rotate = fmod(sphere2Rotate - rotateDelta2, 360); glutPostRedisplay(); glutTimerFunc(timerMs, renderTick, 1); // restart the timer } void pressSpecialKey(int key, int xx, int yy) { switch (key) { case GLUT_KEY_UP: { cam->pitch(PITCH_AMT); break; } case GLUT_KEY_DOWN: { cam->pitch(-PITCH_AMT); break; } case GLUT_KEY_RIGHT: { cam->yaw(YAW_AMT); break; } case GLUT_KEY_LEFT: { cam->yaw(-YAW_AMT); break; } } glutPostRedisplay(); } /** * Main. */ int main(int argc, char** argv) { Shader s; glutInit(&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(800, 600); glutCreateWindow("COMP 4002 - Assignment 2 - Ryan Seys"); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboardFunc); glutSpecialFunc(pressSpecialKey); INIT_GLEW(); s.createShaderProgram("sphere.vert", "sphere.frag", &shaderProg); // For Task 1. sphere0 = new SolidSphere(0.75, 24, 24); // Object for Task 2. cube = new SolidCube(1.0, 0.5, 0.5); sphere1 = new SolidSphere(0.75, 24, 24); sphere2 = new SolidSphere(0.75, 24, 24); // For Task 3. cam = new Camera(position, lookAtPoint, upVector); // Robot arm for Task 4 (Bonus) robotarm = new RobotArm(); glutPostRedisplay(); glEnable(GL_DEPTH_TEST); glutTimerFunc(1, renderTick, 1); glutMainLoop(); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: ParaView Module: vtkSelection.cxx Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/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 notice for more information. =========================================================================*/ #include "vtkSelection.h" #include "vtkAbstractArray.h" #include "vtkFieldData.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationIntegerKey.h" #include "vtkInformationIterator.h" #include "vtkInformationObjectBaseKey.h" #include "vtkInformationStringKey.h" #include "vtkInformationDoubleKey.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkSelectionNode.h" #include "vtkSmartPointer.h" #include "vtkTable.h" #include <vtkstd/vector> //---------------------------------------------------------------------------- struct vtkSelectionInternals { vtkstd::vector<vtkSmartPointer<vtkSelectionNode> > Nodes; }; //---------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkSelection, "1.28"); vtkStandardNewMacro(vtkSelection); //---------------------------------------------------------------------------- vtkSelection::vtkSelection() { this->Internal = new vtkSelectionInternals; this->Information->Set(vtkDataObject::DATA_EXTENT_TYPE(), VTK_PIECES_EXTENT); this->Information->Set(vtkDataObject::DATA_PIECE_NUMBER(), -1); this->Information->Set(vtkDataObject::DATA_NUMBER_OF_PIECES(), 1); this->Information->Set(vtkDataObject::DATA_NUMBER_OF_GHOST_LEVELS(), 0); } //---------------------------------------------------------------------------- vtkSelection::~vtkSelection() { delete this->Internal; } //---------------------------------------------------------------------------- void vtkSelection::Initialize() { this->Superclass::Initialize(); delete this->Internal; this->Internal = new vtkSelectionInternals; } //---------------------------------------------------------------------------- unsigned int vtkSelection::GetNumberOfNodes() { return static_cast<unsigned int>(this->Internal->Nodes.size()); } //---------------------------------------------------------------------------- vtkSelectionNode* vtkSelection::GetNode(unsigned int idx) { if (idx >= this->GetNumberOfNodes()) { return 0; } return this->Internal->Nodes[idx]; } //---------------------------------------------------------------------------- void vtkSelection::AddNode(vtkSelectionNode* node) { if (!node) { return; } // Make sure that node is not already added unsigned int numNodes = this->GetNumberOfNodes(); for (unsigned int i = 0; i < numNodes; i++) { if (this->GetNode(i) == node) { return; } } this->Internal->Nodes.push_back(node); this->Modified(); } //---------------------------------------------------------------------------- void vtkSelection::RemoveNode(unsigned int idx) { if (idx >= this->GetNumberOfNodes()) { return; } vtkstd::vector<vtkSmartPointer<vtkSelectionNode> >::iterator iter = this->Internal->Nodes.begin(); this->Internal->Nodes.erase(iter+idx); this->Modified(); } //---------------------------------------------------------------------------- void vtkSelection::RemoveNode(vtkSelectionNode* node) { if (!node) { return; } unsigned int numNodes = this->GetNumberOfNodes(); for (unsigned int i = 0; i < numNodes; i++) { if (this->GetNode(i) == node) { this->RemoveNode(i); return; } } this->Modified(); } //---------------------------------------------------------------------------- void vtkSelection::RemoveAllNodes() { this->Internal->Nodes.clear(); this->Modified(); } //---------------------------------------------------------------------------- void vtkSelection::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); unsigned int numNodes = this->GetNumberOfNodes(); os << indent << "Number of nodes: " << numNodes << endl; os << indent << "Nodes: " << endl; for (unsigned int i = 0; i < numNodes; i++) { os << indent << "Node #" << i << endl; this->GetNode(i)->PrintSelf(os, indent.GetNextIndent()); } } //---------------------------------------------------------------------------- void vtkSelection::ShallowCopy(vtkDataObject* src) { vtkSelection *input = vtkSelection::SafeDownCast(src); if (!input) { return; } this->Initialize(); this->Superclass::ShallowCopy(src); unsigned int numNodes = input->GetNumberOfNodes(); for (unsigned int i=0; i<numNodes; i++) { vtkSmartPointer<vtkSelectionNode> newNode = vtkSmartPointer<vtkSelectionNode>::New(); newNode->ShallowCopy(input->GetNode(i)); this->AddNode(newNode); } this->Modified(); } //---------------------------------------------------------------------------- void vtkSelection::DeepCopy(vtkDataObject* src) { vtkSelection *input = vtkSelection::SafeDownCast(src); if (!input) { return; } this->Initialize(); this->Superclass::DeepCopy(src); unsigned int numNodes = input->GetNumberOfNodes(); for (unsigned int i=0; i<numNodes; i++) { vtkSmartPointer<vtkSelectionNode> newNode = vtkSmartPointer<vtkSelectionNode>::New(); newNode->DeepCopy(input->GetNode(i)); this->AddNode(newNode); } this->Modified(); } //---------------------------------------------------------------------------- void vtkSelection::Union(vtkSelection* s) { for (unsigned int n = 0; n < s->GetNumberOfNodes(); ++n) { this->Union(s->GetNode(n)); } } //---------------------------------------------------------------------------- void vtkSelection::Union(vtkSelectionNode* node) { bool merged = false; for (unsigned int tn = 0; tn < this->GetNumberOfNodes(); ++tn) { vtkSelectionNode* tnode = this->GetNode(tn); if (tnode->EqualProperties(node)) { tnode->UnionSelectionList(node); merged = true; break; } } if (!merged) { vtkSmartPointer<vtkSelectionNode> clone = vtkSmartPointer<vtkSelectionNode>::New(); clone->ShallowCopy(node); this->AddNode(clone); } } //---------------------------------------------------------------------------- unsigned long vtkSelection::GetMTime() { unsigned long mTime = this->MTime.GetMTime(); unsigned long nodeMTime; for (unsigned int n = 0; n < this->GetNumberOfNodes(); ++n) { vtkSelectionNode* node = this->GetNode(n); nodeMTime = node->GetMTime(); mTime = ( nodeMTime > mTime ? nodeMTime : mTime ); } return mTime; } //---------------------------------------------------------------------------- vtkSelection* vtkSelection::GetData(vtkInformation* info) { return info? vtkSelection::SafeDownCast(info->Get(DATA_OBJECT())) : 0; } //---------------------------------------------------------------------------- vtkSelection* vtkSelection::GetData(vtkInformationVector* v, int i) { return vtkSelection::GetData(v->GetInformationObject(i)); } <commit_msg>BUG: DeepCopy selections when performing a union.<commit_after>/*========================================================================= Program: ParaView Module: vtkSelection.cxx Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/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 notice for more information. =========================================================================*/ #include "vtkSelection.h" #include "vtkAbstractArray.h" #include "vtkFieldData.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationIntegerKey.h" #include "vtkInformationIterator.h" #include "vtkInformationObjectBaseKey.h" #include "vtkInformationStringKey.h" #include "vtkInformationDoubleKey.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkSelectionNode.h" #include "vtkSmartPointer.h" #include "vtkTable.h" #include <vtkstd/vector> //---------------------------------------------------------------------------- struct vtkSelectionInternals { vtkstd::vector<vtkSmartPointer<vtkSelectionNode> > Nodes; }; //---------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkSelection, "1.29"); vtkStandardNewMacro(vtkSelection); //---------------------------------------------------------------------------- vtkSelection::vtkSelection() { this->Internal = new vtkSelectionInternals; this->Information->Set(vtkDataObject::DATA_EXTENT_TYPE(), VTK_PIECES_EXTENT); this->Information->Set(vtkDataObject::DATA_PIECE_NUMBER(), -1); this->Information->Set(vtkDataObject::DATA_NUMBER_OF_PIECES(), 1); this->Information->Set(vtkDataObject::DATA_NUMBER_OF_GHOST_LEVELS(), 0); } //---------------------------------------------------------------------------- vtkSelection::~vtkSelection() { delete this->Internal; } //---------------------------------------------------------------------------- void vtkSelection::Initialize() { this->Superclass::Initialize(); delete this->Internal; this->Internal = new vtkSelectionInternals; } //---------------------------------------------------------------------------- unsigned int vtkSelection::GetNumberOfNodes() { return static_cast<unsigned int>(this->Internal->Nodes.size()); } //---------------------------------------------------------------------------- vtkSelectionNode* vtkSelection::GetNode(unsigned int idx) { if (idx >= this->GetNumberOfNodes()) { return 0; } return this->Internal->Nodes[idx]; } //---------------------------------------------------------------------------- void vtkSelection::AddNode(vtkSelectionNode* node) { if (!node) { return; } // Make sure that node is not already added unsigned int numNodes = this->GetNumberOfNodes(); for (unsigned int i = 0; i < numNodes; i++) { if (this->GetNode(i) == node) { return; } } this->Internal->Nodes.push_back(node); this->Modified(); } //---------------------------------------------------------------------------- void vtkSelection::RemoveNode(unsigned int idx) { if (idx >= this->GetNumberOfNodes()) { return; } vtkstd::vector<vtkSmartPointer<vtkSelectionNode> >::iterator iter = this->Internal->Nodes.begin(); this->Internal->Nodes.erase(iter+idx); this->Modified(); } //---------------------------------------------------------------------------- void vtkSelection::RemoveNode(vtkSelectionNode* node) { if (!node) { return; } unsigned int numNodes = this->GetNumberOfNodes(); for (unsigned int i = 0; i < numNodes; i++) { if (this->GetNode(i) == node) { this->RemoveNode(i); return; } } this->Modified(); } //---------------------------------------------------------------------------- void vtkSelection::RemoveAllNodes() { this->Internal->Nodes.clear(); this->Modified(); } //---------------------------------------------------------------------------- void vtkSelection::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); unsigned int numNodes = this->GetNumberOfNodes(); os << indent << "Number of nodes: " << numNodes << endl; os << indent << "Nodes: " << endl; for (unsigned int i = 0; i < numNodes; i++) { os << indent << "Node #" << i << endl; this->GetNode(i)->PrintSelf(os, indent.GetNextIndent()); } } //---------------------------------------------------------------------------- void vtkSelection::ShallowCopy(vtkDataObject* src) { vtkSelection *input = vtkSelection::SafeDownCast(src); if (!input) { return; } this->Initialize(); this->Superclass::ShallowCopy(src); unsigned int numNodes = input->GetNumberOfNodes(); for (unsigned int i=0; i<numNodes; i++) { vtkSmartPointer<vtkSelectionNode> newNode = vtkSmartPointer<vtkSelectionNode>::New(); newNode->ShallowCopy(input->GetNode(i)); this->AddNode(newNode); } this->Modified(); } //---------------------------------------------------------------------------- void vtkSelection::DeepCopy(vtkDataObject* src) { vtkSelection *input = vtkSelection::SafeDownCast(src); if (!input) { return; } this->Initialize(); this->Superclass::DeepCopy(src); unsigned int numNodes = input->GetNumberOfNodes(); for (unsigned int i=0; i<numNodes; i++) { vtkSmartPointer<vtkSelectionNode> newNode = vtkSmartPointer<vtkSelectionNode>::New(); newNode->DeepCopy(input->GetNode(i)); this->AddNode(newNode); } this->Modified(); } //---------------------------------------------------------------------------- void vtkSelection::Union(vtkSelection* s) { for (unsigned int n = 0; n < s->GetNumberOfNodes(); ++n) { this->Union(s->GetNode(n)); } } //---------------------------------------------------------------------------- void vtkSelection::Union(vtkSelectionNode* node) { bool merged = false; for (unsigned int tn = 0; tn < this->GetNumberOfNodes(); ++tn) { vtkSelectionNode* tnode = this->GetNode(tn); if (tnode->EqualProperties(node)) { tnode->UnionSelectionList(node); merged = true; break; } } if (!merged) { vtkSmartPointer<vtkSelectionNode> clone = vtkSmartPointer<vtkSelectionNode>::New(); clone->DeepCopy(node); this->AddNode(clone); } } //---------------------------------------------------------------------------- unsigned long vtkSelection::GetMTime() { unsigned long mTime = this->MTime.GetMTime(); unsigned long nodeMTime; for (unsigned int n = 0; n < this->GetNumberOfNodes(); ++n) { vtkSelectionNode* node = this->GetNode(n); nodeMTime = node->GetMTime(); mTime = ( nodeMTime > mTime ? nodeMTime : mTime ); } return mTime; } //---------------------------------------------------------------------------- vtkSelection* vtkSelection::GetData(vtkInformation* info) { return info? vtkSelection::SafeDownCast(info->Get(DATA_OBJECT())) : 0; } //---------------------------------------------------------------------------- vtkSelection* vtkSelection::GetData(vtkInformationVector* v, int i) { return vtkSelection::GetData(v->GetInformationObject(i)); } <|endoftext|>
<commit_before>// Copyright 2016 The Mumble Developers. All rights reserved. // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. #include "../mumble_plugin_win32.h" static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) { for (int i=0;i<3;i++) { avatar_pos[i] = avatar_front[i] = avatar_top[i] = camera_pos[i] = camera_front[i] = camera_top[i] = 0.0f; } char state, host[22]; BYTE team; bool ok; // Create containers to stuff our raw data into, so we can convert it to Mumble's coordinate system float avatar_pos_corrector[3], camera_pos_corrector[3], viewHor, viewVer; // Peekproc and assign game addresses to our containers, so we can retrieve positional data ok = peekProc((BYTE *) pModule + 0x0188248, &state, 1) && // Magical state value: 1 when in-game and 0 when not peekProc((BYTE *) pModule + 0x10728C4, &avatar_pos_corrector, 12) && // Avatar Position values (X, Y and Z) peekProc((BYTE *) pModule + 0x0E6093C, &camera_pos_corrector, 12) && // Camera Position values (X, Y and Z) peekProc((BYTE *) pModule + 0x1072954, &viewHor, 4) && // Changes in a range from 87.890625 (looking down) to -87.890625 (looking up) peekProc((BYTE *) pModule + 0x1072950, &viewVer, 4) && // Changes in a range from 180 to -180 when moving the view to left/right peekProc((BYTE *) pModule + 0x0E4A638, host) && // Server value: "IP:Port" when in a remote server, "loopback" when on a local server. peekProc((BYTE *) pModule + 0x106CE6C, team); // Team value: 0 when in a FFA game (no team); 1 when in Red team; 2 when in Blue team; 3 when in Spectators. if (! ok) { return false; } if (state == 0) { // If not in-game context.clear(); // Clear context identity.clear(); // Clear identity return true; // This results in all vectors beeing zero which tells Mumble to ignore them. } if (state == 1 && team == 3) { // If in-game as spectator // Set to 0 avatar and camera values. for (int i=0;i<3;i++) { avatar_pos[i] = avatar_front[i] = avatar_top[i] = camera_pos[i] = camera_front[i] = camera_top[i] = 0.0f; } // Set team to SPEC. std::wostringstream oidentity; oidentity << "{\"team\": \"SPEC\"}"; identity = oidentity.str(); return true; // This results in all vectors beeing zero which tells Mumble to ignore them. } host[sizeof(host) - 1] = '\0'; std::string Server(host); // This string can be either "xxx.xxx.xxx.xxx:yyyyy" (or shorter), "loopback" or "" (empty) when loading. Hence 22 size for char. if (!Server.empty()) { if (Server.find("loopback") == std::string::npos) { std::ostringstream newcontext; newcontext << "{\"ipport\": \"" << Server << "\"}"; context = newcontext.str(); } std::wostringstream oidentity; if (team == 0) oidentity << "{\"team\": \"FFA\"}"; else if (team == 1) oidentity << "{\"team\": \"RED\"}"; else if (team == 2) oidentity << "{\"team\": \"BLUE\"}"; else if (team == 3) oidentity << "{\"team\": \"SPEC\"}"; identity = oidentity.str(); } /* Game | Mumble X | Y Y | Z Z | X */ avatar_pos[0] = avatar_pos_corrector[1]; avatar_pos[1] = avatar_pos_corrector[2]; avatar_pos[2] = avatar_pos_corrector[0]; camera_pos[0] = camera_pos_corrector[1]; camera_pos[1] = camera_pos_corrector[2]; camera_pos[2] = camera_pos_corrector[0]; // Scale to meters for (int i=0;i<3;i++) { avatar_pos[i]/=70.0f; camera_pos[i]/=70.0f; } viewVer *= static_cast<float>(M_PI / 180.0f); viewHor *= static_cast<float>(M_PI / 180.0f); avatar_front[0] = camera_front[0] = -sin(viewHor) * cos(viewVer); avatar_front[1] = camera_front[1] = -sin(viewVer); avatar_front[2] = camera_front[2] = cos(viewHor) * cos(viewVer); avatar_top[0] = camera_top[0] = -sin(viewHor) * cos(viewVer); avatar_top[1] = camera_top[1] = -sin(viewVer); avatar_top[2] = camera_top[2] = cos(viewHor) * cos(viewVer); return true; } static int trylock(const std::multimap<std::wstring, unsigned long long int> &pids) { if (! initialize(pids, L"quakelive_steam.exe")) { // Link the game executable return false; } // Check if we can get meaningful data from it float apos[3], afront[3], atop[3], cpos[3], cfront[3], ctop[3]; std::wstring sidentity; std::string scontext; if (fetch(apos, afront, atop, cpos, cfront, ctop, scontext, sidentity)) { return true; } else { generic_unlock(); return false; } } static const std::wstring longdesc() { return std::wstring(L"Supports Quake Live version 1067 with context and identity support."); // Plugin long description } static std::wstring description(L"Quake Live (v1067)"); // Plugin short description static std::wstring shortname(L"Quake Live"); // Plugin short name static int trylock1() { return trylock(std::multimap<std::wstring, unsigned long long int>()); } static MumblePlugin qlplug = { MUMBLE_PLUGIN_MAGIC, description, shortname, NULL, NULL, trylock1, generic_unlock, longdesc, fetch }; static MumblePlugin2 qlplug2 = { MUMBLE_PLUGIN_MAGIC_2, MUMBLE_PLUGIN_VERSION, trylock }; extern "C" __declspec(dllexport) MumblePlugin *getMumblePlugin() { return &qlplug; } extern "C" __declspec(dllexport) MumblePlugin2 *getMumblePlugin2() { return &qlplug2; } <commit_msg>plugins/ql: Added Spectator state value<commit_after>// Copyright 2016 The Mumble Developers. All rights reserved. // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file at the root of the // Mumble source tree or at <https://www.mumble.info/LICENSE>. #include "../mumble_plugin_win32.h" static int fetch(float *avatar_pos, float *avatar_front, float *avatar_top, float *camera_pos, float *camera_front, float *camera_top, std::string &context, std::wstring &identity) { for (int i=0;i<3;i++) { avatar_pos[i] = avatar_front[i] = avatar_top[i] = camera_pos[i] = camera_front[i] = camera_top[i] = 0.0f; } bool ok, state, spec; char host[22]; BYTE team; // Create containers to stuff our raw data into, so we can convert it to Mumble's coordinate system float avatar_pos_corrector[3], camera_pos_corrector[3], viewHor, viewVer; // Peekproc and assign game addresses to our containers, so we can retrieve positional data ok = peekProc((BYTE *) pModule + 0x0188248, &state, 1) && // Magical state value: 1 when in-game and 0 when in main menu. peekProc((BYTE *) pModule + 0x1041B14, &spec, 1) && // Spectator state value: 1 when spectating and 0 when playing. peekProc((BYTE *) pModule + 0x10728C4, &avatar_pos_corrector, 12) && // Avatar Position values (X, Y and Z). peekProc((BYTE *) pModule + 0x0E6093C, &camera_pos_corrector, 12) && // Camera Position values (X, Y and Z). peekProc((BYTE *) pModule + 0x1072954, &viewHor, 4) && // Changes in a range from 87.890625 (looking down) to -87.890625 (looking up). peekProc((BYTE *) pModule + 0x1072950, &viewVer, 4) && // Changes in a range from 180 to -180 when moving the view to left/right. peekProc((BYTE *) pModule + 0x0E4A638, host) && // Server value: "IP:Port" when in a remote server, "loopback" when on a local server. peekProc((BYTE *) pModule + 0x106CE6C, team); // Team value: 0 when in a FFA game (no team); 1 when in Red team; 2 when in Blue team; 3 when in Spectators. if (! ok) { return false; } if (! state) { // If not in-game context.clear(); // Clear context identity.clear(); // Clear identity return true; // This results in all vectors beeing zero which tells Mumble to ignore them. } if (state && spec) { // If in-game as spectator // Set to 0 avatar and camera values. for (int i=0;i<3;i++) { avatar_pos[i] = avatar_front[i] = avatar_top[i] = camera_pos[i] = camera_front[i] = camera_top[i] = 0.0f; } // Set team to SPEC. std::wostringstream oidentity; oidentity << "{\"team\": \"SPEC\"}"; identity = oidentity.str(); return true; // This results in all vectors beeing zero which tells Mumble to ignore them. } host[sizeof(host) - 1] = '\0'; std::string Server(host); // This string can be either "xxx.xxx.xxx.xxx:yyyyy" (or shorter), "loopback" or "" (empty) when loading. Hence 22 size for char. if (!Server.empty()) { if (Server.find("loopback") == std::string::npos) { std::ostringstream newcontext; newcontext << "{\"ipport\": \"" << Server << "\"}"; context = newcontext.str(); } std::wostringstream oidentity; if (team == 0) oidentity << "{\"team\": \"FFA\"}"; else if (team == 1) oidentity << "{\"team\": \"RED\"}"; else if (team == 2) oidentity << "{\"team\": \"BLUE\"}"; else if (team == 3) oidentity << "{\"team\": \"SPEC\"}"; identity = oidentity.str(); } /* Game | Mumble X | Y Y | Z Z | X */ avatar_pos[0] = avatar_pos_corrector[1]; avatar_pos[1] = avatar_pos_corrector[2]; avatar_pos[2] = avatar_pos_corrector[0]; camera_pos[0] = camera_pos_corrector[1]; camera_pos[1] = camera_pos_corrector[2]; camera_pos[2] = camera_pos_corrector[0]; // Scale to meters for (int i=0;i<3;i++) { avatar_pos[i]/=70.0f; camera_pos[i]/=70.0f; } viewVer *= static_cast<float>(M_PI / 180.0f); viewHor *= static_cast<float>(M_PI / 180.0f); avatar_front[0] = camera_front[0] = -sin(viewHor) * cos(viewVer); avatar_front[1] = camera_front[1] = -sin(viewVer); avatar_front[2] = camera_front[2] = cos(viewHor) * cos(viewVer); avatar_top[0] = camera_top[0] = -sin(viewHor) * cos(viewVer); avatar_top[1] = camera_top[1] = -sin(viewVer); avatar_top[2] = camera_top[2] = cos(viewHor) * cos(viewVer); return true; } static int trylock(const std::multimap<std::wstring, unsigned long long int> &pids) { if (! initialize(pids, L"quakelive_steam.exe")) { // Link the game executable return false; } // Check if we can get meaningful data from it float apos[3], afront[3], atop[3], cpos[3], cfront[3], ctop[3]; std::wstring sidentity; std::string scontext; if (fetch(apos, afront, atop, cpos, cfront, ctop, scontext, sidentity)) { return true; } else { generic_unlock(); return false; } } static const std::wstring longdesc() { return std::wstring(L"Supports Quake Live version 1067 with context and identity support."); // Plugin long description } static std::wstring description(L"Quake Live (v1067)"); // Plugin short description static std::wstring shortname(L"Quake Live"); // Plugin short name static int trylock1() { return trylock(std::multimap<std::wstring, unsigned long long int>()); } static MumblePlugin qlplug = { MUMBLE_PLUGIN_MAGIC, description, shortname, NULL, NULL, trylock1, generic_unlock, longdesc, fetch }; static MumblePlugin2 qlplug2 = { MUMBLE_PLUGIN_MAGIC_2, MUMBLE_PLUGIN_VERSION, trylock }; extern "C" __declspec(dllexport) MumblePlugin *getMumblePlugin() { return &qlplug; } extern "C" __declspec(dllexport) MumblePlugin2 *getMumblePlugin2() { return &qlplug2; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include "HammingCode.h" using namespace std; /* void addParity(bool d1, bool d2, bool d3, bool d4, bool d5, bool d6, bool d7, bool d8, bool & p1, bool & p2, bool & p4, bool & p8); void checkParity(bool &d1, bool &d2, bool &d3, bool &d4, bool &d5, bool &d6, bool &d7, bool &d8, bool & p1, bool & p2, bool & p4, bool & p8, bool & err); */ //for use at testing without header file /* int main(){ bool p1,p2,p4,p8,d1=1,d2=1,d3=0,d4=0,d5=0,d6=1,d7=0,d8=0; addParity(d1,d2,d3,d4,d5,d6,d7,d8,p1,p2,p4,p8); checkParity(d1,d2,d3,d4,d5,d6,d7,d8,p1,p2,p4,p8); return 0; }*/ //for testing void addParity(bool d1, bool d2, bool d3, bool d4, bool d5, bool d6, bool d7, bool d8, bool & p1, bool & p2, bool & p4, bool & p8) { p1=d1^d2^d4^d5^d7; p2=d1^d3^d4^d6^d7; p4=d2^d3^d4^d8; p8=d5^d6^d7^d8; /* cout<<p1; cout<<p2; cout<<p4; cout<<p8; //sentData={p1,p2,d1,p4,d2,d3,d4,p8,d5,d6,d7,d8}; */ //for testing } void checkParity(bool &d1, bool &d2, bool &d3, bool &d4, bool &d5, bool &d6, bool &d7, bool &d8, bool & p1, bool & p2, bool & p4, bool & p8, bool & err) { bool bits[] = {p1,p2,d1,p4,d2,d3,d4,p8,d5,d6,d7,d8}; bool r1 = p1 ^ d1 ^ d2 ^ d4 ^ d5 ^ d7; bool r2 = p2 ^ d1 ^ d3 ^ d4 ^ d6 ^ d7; bool r3 = p4 ^ d2 ^ d3 ^ d4 ^ d8; bool r4 = p8 ^ d5 ^ d6 ^ d7 ^ d8; /* cout << r1; cout << r2; cout << r3; cout << r4; */ //for testing if (r1 | r2 | r3 | r4) { int hataliBit=r1+2*r2+4*r3+8*r4 - 1; bits[hataliBit] = !bits[hataliBit]; err = true; } else { /* cout << "\nNo error!\n"; */ //for testing err = false; } p1 = bits[0]; p2 = bits[1]; d1 = bits[2]; p4 = bits[3]; d2 = bits[4]; d3 = bits[5]; d4 = bits[6]; p8 = bits[7]; d5 = bits[8]; d6 = bits[9]; d7 = bits[10]; d8 = bits[11]; } <commit_msg>Update HammingCode.cpp<commit_after> // Owner: Onur Calik, edited by Yigit Suoglu // Contains code for 8 4 Hamming error correction medhod. Works with boolean values #include <iostream> #include <string> #include "HammingCode.h" using namespace std; /* void addParity(bool d1, bool d2, bool d3, bool d4, bool d5, bool d6, bool d7, bool d8, bool & p1, bool & p2, bool & p4, bool & p8); void checkParity(bool &d1, bool &d2, bool &d3, bool &d4, bool &d5, bool &d6, bool &d7, bool &d8, bool & p1, bool & p2, bool & p4, bool & p8, bool & err); */ //for use at testing without header file /* int main(){ bool p1,p2,p4,p8,d1=1,d2=1,d3=0,d4=0,d5=0,d6=1,d7=0,d8=0; addParity(d1,d2,d3,d4,d5,d6,d7,d8,p1,p2,p4,p8); checkParity(d1,d2,d3,d4,d5,d6,d7,d8,p1,p2,p4,p8); return 0; }*/ //for testing void addParity(bool d1, bool d2, bool d3, bool d4, bool d5, bool d6, bool d7, bool d8, bool & p1, bool & p2, bool & p4, bool & p8) // Give your data to dx's and give containers for parity bits to px's (referance) { p1=d1^d2^d4^d5^d7; p2=d1^d3^d4^d6^d7; p4=d2^d3^d4^d8; p8=d5^d6^d7^d8; /* cout<<p1; cout<<p2; cout<<p4; cout<<p8; //sentData={p1,p2,d1,p4,d2,d3,d4,p8,d5,d6,d7,d8}; */ //for testing } void checkParity(bool &d1, bool &d2, bool &d3, bool &d4, bool &d5, bool &d6, bool &d7, bool &d8, bool & p1, bool & p2, bool & p4, bool & p8, bool & err) // Give data to dx's and px's (both referance) also returns err for error feedback { bool bits[] = {p1,p2,d1,p4,d2,d3,d4,p8,d5,d6,d7,d8}; bool r1 = p1 ^ d1 ^ d2 ^ d4 ^ d5 ^ d7; bool r2 = p2 ^ d1 ^ d3 ^ d4 ^ d6 ^ d7; bool r3 = p4 ^ d2 ^ d3 ^ d4 ^ d8; bool r4 = p8 ^ d5 ^ d6 ^ d7 ^ d8; /* cout << r1; cout << r2; cout << r3; cout << r4; */ //for testing if (r1 | r2 | r3 | r4) { int hataliBit=r1+2*r2+4*r3+8*r4 - 1; bits[hataliBit] = !bits[hataliBit]; err = true; } else { /* cout << "\nNo error!\n"; */ //for testing err = false; } p1 = bits[0]; p2 = bits[1]; d1 = bits[2]; p4 = bits[3]; d2 = bits[4]; d3 = bits[5]; d4 = bits[6]; p8 = bits[7]; d5 = bits[8]; d6 = bits[9]; d7 = bits[10]; d8 = bits[11]; } <|endoftext|>
<commit_before>#include "data_type.hpp" #include <bitcoin/format.hpp> namespace libbitcoin { // readable_data_type void readable_data_type::set(uint32_t value) { data_buffer_ = uncast_type(value); prepare(); } void readable_data_type::set(const data_chunk& data) { extend_data(data_buffer_, data); prepare(); } void readable_data_type::set(const hash_digest& data) { extend_data(data_buffer_, data); prepare(); } void readable_data_type::set(const short_hash& data) { extend_data(data_buffer_, data); prepare(); } void readable_data_type::set(const std::string& data) { extend_data(data_buffer_, data); prepare(); } Dbt* readable_data_type::get() { return &dbt_; } const Dbt* readable_data_type::get() const { return &dbt_; } void readable_data_type::prepare() { dbt_.set_data(&data_buffer_[0]); dbt_.set_ulen(data_buffer_.size()); dbt_.set_size(data_buffer_.size()); dbt_.set_flags(DB_DBT_USERMEM); } // writable_data_type writable_data_type::writable_data_type() { dbt_.set_flags(DB_DBT_MALLOC); } writable_data_type::~writable_data_type() { free(dbt_.get_data()); } data_chunk writable_data_type::data() const { std::string raw_depth(reinterpret_cast<const char*>( dbt_.get_data()), dbt_.get_size()); return data_chunk(raw_depth.begin(), raw_depth.end()); } bool writable_data_type::empty() { return dbt_.get_data() == nullptr; } Dbt* writable_data_type::get() { return &dbt_; } const Dbt* writable_data_type::get() const { return &dbt_; } // empty_data_type empty_data_type::empty_data_type() { dbt_.set_flags(DB_DBT_MALLOC|DB_DBT_PARTIAL); dbt_.set_doff(0); dbt_.set_dlen(0); } empty_data_type::~empty_data_type() { free(dbt_.get_data()); } Dbt* empty_data_type::get() { return &dbt_; } const Dbt* empty_data_type::get() const { return &dbt_; } } // namespace libbitcoin <commit_msg>set DB_DBT_READONLY on readable_data_type for bdb<commit_after>#include "data_type.hpp" #include <bitcoin/format.hpp> namespace libbitcoin { // readable_data_type void readable_data_type::set(uint32_t value) { data_buffer_ = uncast_type(value); prepare(); } void readable_data_type::set(const data_chunk& data) { extend_data(data_buffer_, data); prepare(); } void readable_data_type::set(const hash_digest& data) { extend_data(data_buffer_, data); prepare(); } void readable_data_type::set(const short_hash& data) { extend_data(data_buffer_, data); prepare(); } void readable_data_type::set(const std::string& data) { extend_data(data_buffer_, data); prepare(); } Dbt* readable_data_type::get() { return &dbt_; } const Dbt* readable_data_type::get() const { return &dbt_; } void readable_data_type::prepare() { dbt_.set_data(&data_buffer_[0]); dbt_.set_ulen(data_buffer_.size()); dbt_.set_size(data_buffer_.size()); dbt_.set_flags(DB_DBT_USERMEM|DB_DBT_READONLY); } // writable_data_type writable_data_type::writable_data_type() { dbt_.set_flags(DB_DBT_MALLOC); } writable_data_type::~writable_data_type() { free(dbt_.get_data()); } data_chunk writable_data_type::data() const { std::string raw_depth(reinterpret_cast<const char*>( dbt_.get_data()), dbt_.get_size()); return data_chunk(raw_depth.begin(), raw_depth.end()); } bool writable_data_type::empty() { return dbt_.get_data() == nullptr; } Dbt* writable_data_type::get() { return &dbt_; } const Dbt* writable_data_type::get() const { return &dbt_; } // empty_data_type empty_data_type::empty_data_type() { dbt_.set_flags(DB_DBT_MALLOC|DB_DBT_PARTIAL); dbt_.set_doff(0); dbt_.set_dlen(0); } empty_data_type::~empty_data_type() { free(dbt_.get_data()); } Dbt* empty_data_type::get() { return &dbt_; } const Dbt* empty_data_type::get() const { return &dbt_; } } // namespace libbitcoin <|endoftext|>
<commit_before>#include <tesseract/baseapi.h> #include <leptonica/allheaders.h> #include <string> #include <libgen.h> int main(int argc, char *argv[]) { if(argc != 3) { printf("USAGE: %s imagefile outputdir\n", argv[0]); return 1; } std::string input_filename = std::string(argv[1]); std::string input_basename = std::string(basename(argv[1])); std::string output_dir = std::string(argv[2]); tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(); api->Init(NULL, "eng"); Pix *image0 = pixRead(input_filename.c_str()); api->SetImage(image0); l_int32 input_format = pixGetInputFormat(image0); Pix* image = api->GetThresholdedImage(); api->SetImage(image); Boxa* boxes = api->GetComponentImages(tesseract::RIL_TEXTLINE, true, false, 0, NULL, NULL, NULL); printf("Found %d textline image components.\n", boxes->n); int lastindex = input_basename.find_last_of("."); std::string basename = input_basename.substr(0, lastindex).c_str(); std::string extension = input_basename.substr(lastindex + 1).c_str(); std::string outdir = output_dir.c_str(); int linedirLen = outdir.length()+1+basename.length()+strlen("-line_extract_")+extension.length(); char* linedir = (char*)malloc((linedirLen+1)*sizeof(char)); sprintf(linedir, "%s/%s-line_extract_%s", output_dir.c_str(), basename.c_str(), extension.c_str()); printf("Writing to directory [%s]. If this fails, try:\n mkdir -p %s\n\n\n", linedir, linedir); std::string mkdir_cmd = "mkdir -p " + std::string(linedir); system(mkdir_cmd.c_str()); for (int i = 0; i < boxes->n; i++) { BOX* box = boxaGetBox(boxes, i, L_CLONE); PIX* pixd= pixClipRectangle(image, box, NULL); char* linefilename = (char*)malloc((linedirLen+strlen("/line00.")+extension.length()+1)*sizeof(char)); sprintf(linefilename, "%s/line%02d.%s", linedir, i, extension.c_str()); printf(" Writing %s\n", linefilename); pixWrite(linefilename, pixd, input_format); pixDestroy(&pixd); boxDestroy(&box); free(linefilename); } free(linedir); return 0; } <commit_msg>Explicitly free allocated Tesseract API object<commit_after>#include <tesseract/baseapi.h> #include <leptonica/allheaders.h> #include <string> #include <libgen.h> int main(int argc, char *argv[]) { if(argc != 3) { printf("USAGE: %s imagefile outputdir\n", argv[0]); return 1; } std::string input_filename = std::string(argv[1]); std::string input_basename = std::string(basename(argv[1])); std::string output_dir = std::string(argv[2]); tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(); api->Init(NULL, "eng"); Pix *image0 = pixRead(input_filename.c_str()); api->SetImage(image0); l_int32 input_format = pixGetInputFormat(image0); Pix* image = api->GetThresholdedImage(); api->SetImage(image); Boxa* boxes = api->GetComponentImages(tesseract::RIL_TEXTLINE, true, false, 0, NULL, NULL, NULL); printf("Found %d textline image components.\n", boxes->n); int lastindex = input_basename.find_last_of("."); std::string basename = input_basename.substr(0, lastindex).c_str(); std::string extension = input_basename.substr(lastindex + 1).c_str(); std::string outdir = output_dir.c_str(); int linedirLen = outdir.length()+1+basename.length()+strlen("-line_extract_")+extension.length(); char* linedir = (char*)malloc((linedirLen+1)*sizeof(char)); sprintf(linedir, "%s/%s-line_extract_%s", output_dir.c_str(), basename.c_str(), extension.c_str()); printf("Writing to directory [%s]. If this fails, try:\n mkdir -p %s\n\n\n", linedir, linedir); std::string mkdir_cmd = "mkdir -p " + std::string(linedir); system(mkdir_cmd.c_str()); for (int i = 0; i < boxes->n; i++) { BOX* box = boxaGetBox(boxes, i, L_CLONE); PIX* pixd= pixClipRectangle(image, box, NULL); char* linefilename = (char*)malloc((linedirLen+strlen("/line00.")+extension.length()+1)*sizeof(char)); sprintf(linefilename, "%s/line%02d.%s", linedir, i, extension.c_str()); printf(" Writing %s\n", linefilename); pixWrite(linefilename, pixd, input_format); pixDestroy(&pixd); boxDestroy(&box); free(linefilename); } free(linedir); delete api; return 0; } <|endoftext|>
<commit_before>/* Copyright 2016 Stanford University, NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //////////////////////////////////////////////////////////// // THIS EXAMPLE MUST BE BUILT WITH A VERSION // OF GASNET CONFIGURED WITH MPI COMPATIBILITY //////////////////////////////////////////////////////////// #include <cstdio> // Need MPI header file #include <mpi.h> #include "legion.h" using namespace Legion; enum TaskID { TOP_LEVEL_TASK_ID, MPI_INTEROP_TASK_ID, WORKER_TASK_ID, }; // Here is our global MPI-Legion handshake // You can have as many of these as you // want but the common case is just to // have one per Legion-MPI rank pair MPILegionHandshake handshake; // Have a global static number of iterations for // this example, but you can easily configure it // from command line arguments which get passed // to both MPI and Legion const int total_iterations = 10; void worker_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { printf("Legion Doing Work in Rank %lld\n", task->parent_task->index_point[0]); } void mpi_interop_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { printf("Hello from Legion MPI-Interop Task %lld\n", task->index_point[0]); for (int i = 0; i < total_iterations; i++) { // Legion can interop with MPI in blocking and non-blocking // ways. You can use the calls to 'legion_wait_on_mpi' and // 'legion_handoff_to_mpi' in the same way as the MPI thread // does. Alternatively, you can get a phase barrier associated // with a LegionMPIHandshake object which will allow you to // continue launching more sub-tasks without blocking. // For deferred execution we prefer the later style, but // both will work correctly. if (i < (total_iterations/2)) { // This is the blocking way of using handshakes, it // is not the ideal way, but it works correctly // Wait for MPI to give us control to run our worker // This is a blocking call handshake.legion_wait_on_mpi(); // Launch our worker task TaskLauncher worker_launcher(WORKER_TASK_ID, TaskArgument(NULL,0)); Future f = runtime->execute_task(ctx, worker_launcher); // Have to wait for the result before signaling MPI f.get_void_result(); // Perform a non-blocking call to signal // MPI that we are giving it control back handshake.legion_handoff_to_mpi(); } else { // This is the preferred way of using handshakes in Legion TaskLauncher worker_launcher(WORKER_TASK_ID, TaskArgument(NULL,0)); // We can user our handshake as a phase barrier // Record that we will wait on this handshake worker_launcher.add_wait_handshake(handshake); // Advance the handshake to the next version handshake.advance_legion_handshake(); // Then record that we will arrive on this versions worker_launcher.add_arrival_handshake(handshake); // Launch our worker task // No need to wait for anything runtime->execute_task(ctx, worker_launcher); } } } void top_level_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { printf("Hello from Legion Top-Level Task\n"); // Both the application and Legion mappers have access to // the mappings between MPI Ranks and Legion address spaces // The reverse mapping goes the other way const std::map<int,AddressSpace> &forward_mapping = runtime->find_forward_MPI_mapping(); for (std::map<int,AddressSpace>::const_iterator it = forward_mapping.begin(); it != forward_mapping.end(); it++) printf("MPI Rank %d maps to Legion Address Space %d\n", it->first, it->second); int rank = -1, size = -1; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); // Do a must epoch launch to align with the number of MPI ranks MustEpochLauncher must_epoch_launcher; Rect<1> launch_bounds(Point<1>(0),Point<1>(size - 1)); Domain launch_domain = Domain::from_rect<1>(launch_bounds); ArgumentMap args_map; IndexLauncher index_launcher(MPI_INTEROP_TASK_ID, launch_domain, TaskArgument(NULL, 0), args_map); must_epoch_launcher.add_index_task(index_launcher); runtime->execute_must_epoch(ctx, must_epoch_launcher); } int main(int argc, char **argv) { // Perform MPI start-up like normal MPI_Init(&argc,&argv); int rank = -1, size = -1; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); printf("Hello from MPI process %d of %d\n", rank, size); // Configure the Legion runtime with the rank of this process Runtime::configure_MPI_interoperability(rank); // Register our task variants { TaskVariantRegistrar top_level_registrar(TOP_LEVEL_TASK_ID); top_level_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); Runtime::preregister_task_variant<top_level_task>(top_level_registrar, "Top Level Task"); Runtime::set_top_level_task_id(TOP_LEVEL_TASK_ID); } { TaskVariantRegistrar mpi_interop_registrar(MPI_INTEROP_TASK_ID); mpi_interop_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); Runtime::preregister_task_variant<mpi_interop_task>(mpi_interop_registrar, "MPI Interop Task"); } { TaskVariantRegistrar worker_task_registrar(WORKER_TASK_ID); worker_task_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); Runtime::preregister_task_variant<worker_task>(worker_task_registrar, "Worker Task"); } // Create a handshake for passing control between Legion and MPI // Indicate that MPI has initial control and that there is one // participant on each side handshake = Runtime::create_handshake(true/*MPI initial control*/, 1/*MPI participants*/, 1/*Legion participants*/); // Start the Legion runtime in background mode // This call will return immediately Runtime::start(argc, argv, true/*background*/); // Run your MPI program like normal // If you want strict bulk-synchronous execution include // the barriers protected by this variable, otherwise // you can elide them, they are not required for correctness const bool strict_bulk_synchronous_execution = true; for (int i = 0; i < total_iterations; i++) { printf("MPI Doing Work on rank %d\n", rank); if (strict_bulk_synchronous_execution) MPI_Barrier(MPI_COMM_WORLD); // Perform a handoff to Legion, this call is // asynchronous and will return immediately handshake.mpi_handoff_to_legion(); // You can put additional work in here if you like // but it may interfere with Legion work // Wait for Legion to hand control back, // This call will block until a Legion task // running in this same process hands control back handshake.mpi_wait_on_legion(); if (strict_bulk_synchronous_execution) MPI_Barrier(MPI_COMM_WORLD); } // When you're done wait for the Legion runtime to shutdown Runtime::wait_for_shutdown(); // Then finalize MPI like normal MPI_Finalize(); return 0; } <commit_msg>examples: adding a comment about conduit usage to the MPI interoperability example<commit_after>/* Copyright 2016 Stanford University, NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //////////////////////////////////////////////////////////// // THIS EXAMPLE MUST BE BUILT WITH A VERSION // OF GASNET CONFIGURED WITH MPI COMPATIBILITY // // NOTE THAT GASNET ONLY SUPPORTS MPI-COMPATIBILITY // ON SOME CONDUITS. CURRENTLY THESE ARE IBV, GEMINI, // ARIES, MXM, and OFI. IF YOU WOULD LIKE ADDITIONAL // CONDUITS SUPPORTED PLEASE CONTACT THE MAINTAINERS // OF GASNET. //////////////////////////////////////////////////////////// #include <cstdio> // Need MPI header file #include <mpi.h> #include "legion.h" using namespace Legion; enum TaskID { TOP_LEVEL_TASK_ID, MPI_INTEROP_TASK_ID, WORKER_TASK_ID, }; // Here is our global MPI-Legion handshake // You can have as many of these as you // want but the common case is just to // have one per Legion-MPI rank pair MPILegionHandshake handshake; // Have a global static number of iterations for // this example, but you can easily configure it // from command line arguments which get passed // to both MPI and Legion const int total_iterations = 10; void worker_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { printf("Legion Doing Work in Rank %lld\n", task->parent_task->index_point[0]); } void mpi_interop_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { printf("Hello from Legion MPI-Interop Task %lld\n", task->index_point[0]); for (int i = 0; i < total_iterations; i++) { // Legion can interop with MPI in blocking and non-blocking // ways. You can use the calls to 'legion_wait_on_mpi' and // 'legion_handoff_to_mpi' in the same way as the MPI thread // does. Alternatively, you can get a phase barrier associated // with a LegionMPIHandshake object which will allow you to // continue launching more sub-tasks without blocking. // For deferred execution we prefer the later style, but // both will work correctly. if (i < (total_iterations/2)) { // This is the blocking way of using handshakes, it // is not the ideal way, but it works correctly // Wait for MPI to give us control to run our worker // This is a blocking call handshake.legion_wait_on_mpi(); // Launch our worker task TaskLauncher worker_launcher(WORKER_TASK_ID, TaskArgument(NULL,0)); Future f = runtime->execute_task(ctx, worker_launcher); // Have to wait for the result before signaling MPI f.get_void_result(); // Perform a non-blocking call to signal // MPI that we are giving it control back handshake.legion_handoff_to_mpi(); } else { // This is the preferred way of using handshakes in Legion TaskLauncher worker_launcher(WORKER_TASK_ID, TaskArgument(NULL,0)); // We can user our handshake as a phase barrier // Record that we will wait on this handshake worker_launcher.add_wait_handshake(handshake); // Advance the handshake to the next version handshake.advance_legion_handshake(); // Then record that we will arrive on this versions worker_launcher.add_arrival_handshake(handshake); // Launch our worker task // No need to wait for anything runtime->execute_task(ctx, worker_launcher); } } } void top_level_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { printf("Hello from Legion Top-Level Task\n"); // Both the application and Legion mappers have access to // the mappings between MPI Ranks and Legion address spaces // The reverse mapping goes the other way const std::map<int,AddressSpace> &forward_mapping = runtime->find_forward_MPI_mapping(); for (std::map<int,AddressSpace>::const_iterator it = forward_mapping.begin(); it != forward_mapping.end(); it++) printf("MPI Rank %d maps to Legion Address Space %d\n", it->first, it->second); int rank = -1, size = -1; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); // Do a must epoch launch to align with the number of MPI ranks MustEpochLauncher must_epoch_launcher; Rect<1> launch_bounds(Point<1>(0),Point<1>(size - 1)); Domain launch_domain = Domain::from_rect<1>(launch_bounds); ArgumentMap args_map; IndexLauncher index_launcher(MPI_INTEROP_TASK_ID, launch_domain, TaskArgument(NULL, 0), args_map); must_epoch_launcher.add_index_task(index_launcher); runtime->execute_must_epoch(ctx, must_epoch_launcher); } int main(int argc, char **argv) { // Perform MPI start-up like normal MPI_Init(&argc,&argv); int rank = -1, size = -1; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); printf("Hello from MPI process %d of %d\n", rank, size); // Configure the Legion runtime with the rank of this process Runtime::configure_MPI_interoperability(rank); // Register our task variants { TaskVariantRegistrar top_level_registrar(TOP_LEVEL_TASK_ID); top_level_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); Runtime::preregister_task_variant<top_level_task>(top_level_registrar, "Top Level Task"); Runtime::set_top_level_task_id(TOP_LEVEL_TASK_ID); } { TaskVariantRegistrar mpi_interop_registrar(MPI_INTEROP_TASK_ID); mpi_interop_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); Runtime::preregister_task_variant<mpi_interop_task>(mpi_interop_registrar, "MPI Interop Task"); } { TaskVariantRegistrar worker_task_registrar(WORKER_TASK_ID); worker_task_registrar.add_constraint(ProcessorConstraint(Processor::LOC_PROC)); Runtime::preregister_task_variant<worker_task>(worker_task_registrar, "Worker Task"); } // Create a handshake for passing control between Legion and MPI // Indicate that MPI has initial control and that there is one // participant on each side handshake = Runtime::create_handshake(true/*MPI initial control*/, 1/*MPI participants*/, 1/*Legion participants*/); // Start the Legion runtime in background mode // This call will return immediately Runtime::start(argc, argv, true/*background*/); // Run your MPI program like normal // If you want strict bulk-synchronous execution include // the barriers protected by this variable, otherwise // you can elide them, they are not required for correctness const bool strict_bulk_synchronous_execution = true; for (int i = 0; i < total_iterations; i++) { printf("MPI Doing Work on rank %d\n", rank); if (strict_bulk_synchronous_execution) MPI_Barrier(MPI_COMM_WORLD); // Perform a handoff to Legion, this call is // asynchronous and will return immediately handshake.mpi_handoff_to_legion(); // You can put additional work in here if you like // but it may interfere with Legion work // Wait for Legion to hand control back, // This call will block until a Legion task // running in this same process hands control back handshake.mpi_wait_on_legion(); if (strict_bulk_synchronous_execution) MPI_Barrier(MPI_COMM_WORLD); } // When you're done wait for the Legion runtime to shutdown Runtime::wait_for_shutdown(); // Then finalize MPI like normal MPI_Finalize(); return 0; } <|endoftext|>
<commit_before>#ifndef BUFFER_CACHE_ALT_EVICTER_HPP_ #define BUFFER_CACHE_ALT_EVICTER_HPP_ #include <stdint.h> #include <functional> #include "buffer_cache/alt/eviction_bag.hpp" #include "concurrency/cache_line_padded.hpp" #include "concurrency/pubsub.hpp" #include "threading.hpp" class cache_balancer_t; namespace alt { class page_cache_t; class evicter_t : public home_thread_mixin_debug_only_t { public: void add_not_yet_loaded(page_t *page); void add_deferred_loaded(page_t *page); void catch_up_deferred_load(page_t *page); void add_to_evictable_unbacked(page_t *page); void add_to_evictable_disk_backed(page_t *page); bool page_is_in_unevictable_bag(page_t *page) const; bool page_is_in_evicted_bag(page_t *page) const; void move_unevictable_to_evictable(page_t *page); void change_to_correct_eviction_bag(eviction_bag_t *current_bag, page_t *page); eviction_bag_t *correct_eviction_category(page_t *page); eviction_bag_t *unevictable_category() { return &unevictable_; } eviction_bag_t *evicted_category() { return &evicted_; } void remove_page(page_t *page); void reloading_page(page_t *page); // Evicter will be unusable until initialize is called explicit evicter_t(); ~evicter_t(); void initialize(page_cache_t *page_cache, cache_balancer_t *balancer); void update_memory_limit(uint64_t new_memory_limit, uint64_t bytes_loaded_accounted_for, uint64_t access_count_accounted_for, bool read_ahead_ok); uint64_t next_access_time() { guarantee(initialized_); return ++access_time_counter_; } bool initialized() const { return initialized_; } uint64_t memory_limit() const; uint64_t access_count() const; uint64_t get_clamped_bytes_loaded() const; uint64_t in_memory_size() const; // This is decremented past UINT64_MAX to force code to be aware of access time // rollovers. static const uint64_t INITIAL_ACCESS_TIME = UINT64_MAX - 100; private: // Tells the cache balancer about a page being loaded void notify_bytes_loading(int64_t ser_buf_change); // Evicts any evictable pages until under the memory limit void evict_if_necessary(); bool initialized_; page_cache_t *page_cache_; cache_balancer_t *balancer_; uint64_t memory_limit_; // These are updated every time a page is loaded, created, or destroyed, and // cleared when cache memory limits are re-evaluated. This value can go // negative, if you keep deleting blocks or suddenly drop a snapshot. int64_t bytes_loaded_counter_; uint64_t access_count_counter_; // This gets incremented every time a page is accessed. uint64_t access_time_counter_; // These track every page's eviction status. eviction_bag_t unevictable_; eviction_bag_t evictable_disk_backed_; eviction_bag_t evictable_unbacked_; eviction_bag_t evicted_; DISABLE_COPYING(evicter_t); }; } // namespace alt #endif // BUFFER_CACHE_ALT_EVICTER_HPP_ <commit_msg>Removed unused evicter_t::initialized method that I had just added.<commit_after>#ifndef BUFFER_CACHE_ALT_EVICTER_HPP_ #define BUFFER_CACHE_ALT_EVICTER_HPP_ #include <stdint.h> #include <functional> #include "buffer_cache/alt/eviction_bag.hpp" #include "concurrency/cache_line_padded.hpp" #include "concurrency/pubsub.hpp" #include "threading.hpp" class cache_balancer_t; namespace alt { class page_cache_t; class evicter_t : public home_thread_mixin_debug_only_t { public: void add_not_yet_loaded(page_t *page); void add_deferred_loaded(page_t *page); void catch_up_deferred_load(page_t *page); void add_to_evictable_unbacked(page_t *page); void add_to_evictable_disk_backed(page_t *page); bool page_is_in_unevictable_bag(page_t *page) const; bool page_is_in_evicted_bag(page_t *page) const; void move_unevictable_to_evictable(page_t *page); void change_to_correct_eviction_bag(eviction_bag_t *current_bag, page_t *page); eviction_bag_t *correct_eviction_category(page_t *page); eviction_bag_t *unevictable_category() { return &unevictable_; } eviction_bag_t *evicted_category() { return &evicted_; } void remove_page(page_t *page); void reloading_page(page_t *page); // Evicter will be unusable until initialize is called explicit evicter_t(); ~evicter_t(); void initialize(page_cache_t *page_cache, cache_balancer_t *balancer); void update_memory_limit(uint64_t new_memory_limit, uint64_t bytes_loaded_accounted_for, uint64_t access_count_accounted_for, bool read_ahead_ok); uint64_t next_access_time() { guarantee(initialized_); return ++access_time_counter_; } uint64_t memory_limit() const; uint64_t access_count() const; uint64_t get_clamped_bytes_loaded() const; uint64_t in_memory_size() const; // This is decremented past UINT64_MAX to force code to be aware of access time // rollovers. static const uint64_t INITIAL_ACCESS_TIME = UINT64_MAX - 100; private: // Tells the cache balancer about a page being loaded void notify_bytes_loading(int64_t ser_buf_change); // Evicts any evictable pages until under the memory limit void evict_if_necessary(); bool initialized_; page_cache_t *page_cache_; cache_balancer_t *balancer_; uint64_t memory_limit_; // These are updated every time a page is loaded, created, or destroyed, and // cleared when cache memory limits are re-evaluated. This value can go // negative, if you keep deleting blocks or suddenly drop a snapshot. int64_t bytes_loaded_counter_; uint64_t access_count_counter_; // This gets incremented every time a page is accessed. uint64_t access_time_counter_; // These track every page's eviction status. eviction_bag_t unevictable_; eviction_bag_t evictable_disk_backed_; eviction_bag_t evictable_unbacked_; eviction_bag_t evicted_; DISABLE_COPYING(evicter_t); }; } // namespace alt #endif // BUFFER_CACHE_ALT_EVICTER_HPP_ <|endoftext|>
<commit_before>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2002 * Copyright by ESO (in the framework of the ALMA collaboration) * and Cosylab 2002, All rights reserved * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: acsLogSvc.cpp,v 1.21 2008/03/12 15:24:48 bjeram Exp $" * * who when what * -------- -------- ---------------------------------------------- * gchiozzi 2003-04-03 Fixed ACE_OS::string_to_argv for new ACE * bjeram 2002-04-10 added -silent command line options * bjeram 2002-04-10 added terminal signal handler * bjeram 2002-04-10 added -o options whic write ior also to the file * bjeram 2002-04-10 added registration with Naming Service as ACSLogSvc * bjeram 2001-09-20 change of resolving Log Svc * bjeram 2001-09-11 created */ static char *rcsId="@(#) $Id: acsLogSvc.cpp,v 1.21 2008/03/12 15:24:48 bjeram Exp $"; static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId); #include <acslogSvcImpl.h> #include <orbsvcs/CosNamingC.h> #include <tao/IORTable/IORTable.h> #include <maciHelper.h> #include <acserr.h> #include <acsutilPorts.h> CORBA::ORB_var orb; void TerminationSignalHandler(int) { ACS_SHORT_LOG((LM_INFO, "ACSLogSvc is going down (like Bobby Brown :-)) ... ")); orb->shutdown (true); }//TerminationSignalHandler int main(int argc, char *argv[]) { CosNaming::NamingContext_var naming_context; int nargc=0; char **nargv=0; const char *hn=ACSPorts::getIP(); ACE_CString iorFile; if (argc>=2 && !ACE_OS_String::strcmp(argv[1], "-?")){ ACE_OS::printf ("USAGE: acsLogSvc [-ORBInitRef NameService=iiop://yyy:xxxx/NameService] [-ORBEndpoint iiop://ip:port] [-o iorfile] [-silent]\n"); return -1; } // here we have to unset ACS_LOG_CENTRAL that we prevent filtering of log messages char *logCent=getenv("ACS_LOG_CENTRAL"); if (logCent) { unsetenv("ACS_LOG_CENTRAL"); printf("Unset ACS_LOG_CENTRAL which was previously set to %s\n", logCent); }//if // create logging proxy LoggingProxy::ProcessName(argv[0]); ACE_Log_Msg::instance()->local_host(hn); LoggingProxy m_logger (0, 0, 31, 0); LoggingProxy::init (&m_logger); ACS_SHORT_LOG((LM_INFO, "Logging proxy successfully created !")); ACE_CString argStr; for(int i=1; i<argc; i++) { argStr += argv[i]; argStr += " "; if (!ACE_OS_String::strcmp(argv[i], "-o") && (i+1)<argc) { iorFile = argv[i+1]; }//if }//for if (argStr.find ("-ORBEndpoint")==ACE_CString::npos) { argStr = argStr + "-ORBEndpoint iiop://" + hn + ":" + ACSPorts::getLogPort().c_str(); } ACS_SHORT_LOG((LM_INFO, "New command line is: %s", argStr.c_str())); ACE_OS::string_to_argv ((ACE_TCHAR*)argStr.c_str(), nargc, nargv); ACE_OS::signal(SIGINT, TerminationSignalHandler); // Ctrl+C ACE_OS::signal(SIGTERM, TerminationSignalHandler); // termination request try { // Initialize the ORB ACE_OS::printf ("Initialising ORB ... \n"); orb = CORBA::ORB_init (nargc, nargv, 0); ACE_OS::printf ("ORB initialsed !\n"); } catch( CORBA::Exception &ex ) { ACE_PRINT_EXCEPTION (ex, "Failed to initalise ORB"); return -1; } if (!ACSError::init(orb.in())) { ACS_SHORT_LOG ((LM_ERROR, "Failed to initalise the ACS Error System")); return -1; } // resolve naming service try { ACS_SHORT_LOG((LM_INFO, "Trying to connect to the Naming Service ....")); CORBA::Object_var naming_obj = orb->resolve_initial_references ("NameService"); if (!CORBA::is_nil (naming_obj.in ())) { naming_context = CosNaming::NamingContext::_narrow (naming_obj.in ()); ACS_SHORT_LOG((LM_INFO, "Connected to the Name Service")); } else { ACS_SHORT_LOG((LM_ERROR, "Could not connect the Name Service!")); return -1; }//if-else } catch( CORBA::Exception &_ex ) { ACS_SHORT_LOG((LM_ERROR, "Could not connect the Name Service!")); return -1; } // logging service try { CORBA::Object_var log_obj; /* if (argStr.find ("-ORBInitRef NameService=")!=ACE_CString::npos) { // Initialize the ORB ACE_OS::printf ("Initialising ORB ... \n"); orb = CORBA::ORB_init (nargc, nargv, 0); ACE_OS::printf ("ORB initialsed !\n"); //Naming Service ACE_OS::printf ("Resolving Naming service ... \n"); CORBA::Object_var naming_obj = orb->resolve_initial_references ("NameService"); if (!CORBA::is_nil (naming_obj.in ())) { CosNaming::NamingContext_var naming_context = CosNaming::NamingContext::_narrow (naming_obj.in ()); ACE_OS::printf ( "Naming Service resolved !\n"); */ ACE_OS::printf ( "Resolving Logging Service from Naming service ...\n"); CosNaming::Name name; name.length(1); name[0].id = CORBA::string_dup("Log"); log_obj = naming_context->resolve(name); /* } else { ACS_LOG(LM_SOURCE_INFO, "main", (LM_ERROR, "Failed to initialise the Name Service!")); } }//if naming Service else { ACE_OS::printf ("Getting Log from the Manager... \n"); CORBA::ULong status; maci::Manager_ptr manager = maci::MACIHelper::resolveManager (orb.in(), nargc, nargv, 0, 0); log_obj = manager->get_COB(0, "Log", true, status); } */ if (!CORBA::is_nil (log_obj.in())) { DsLogAdmin::Log_var logger = DsLogAdmin::Log::_narrow(log_obj.in()); ACE_OS::printf ( "Logging Service resolved !\n"); m_logger.setCentralizedLogger(logger.in()); } else { ACS_LOG(LM_SOURCE_INFO, "main", (LM_ERROR, "Failed to initialise the Logging Service!")); return -1; }//if-else } catch( CORBA::Exception &__ex ) { ACE_PRINT_EXCEPTION(__ex, "Failed to get and set the centralized logger"); return -1; } try { //Get a reference to the RootPOA ACE_OS::printf("Creating POA ... \n"); CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in()); PortableServer::POAManager_var poa_manager = root_poa->the_POAManager(); CORBA::PolicyList policy_list; policy_list.length(5); policy_list[0] = root_poa->create_request_processing_policy (PortableServer::USE_DEFAULT_SERVANT); policy_list[1] = root_poa->create_id_uniqueness_policy (PortableServer::MULTIPLE_ID); policy_list[2] = root_poa->create_id_assignment_policy(PortableServer::USER_ID); policy_list[3] = root_poa->create_servant_retention_policy(PortableServer::NON_RETAIN); policy_list[4] = root_poa->create_lifespan_policy (PortableServer::PERSISTENT); printf("policies are created !\n"); PortableServer::POA_var poa = root_poa->create_POA("ACSLogSvc", poa_manager.in(), policy_list); ACE_OS::printf("POA created !\n"); for (CORBA::ULong i = 0; i < policy_list.length (); ++i) { CORBA::Policy_ptr policy = policy_list[i]; policy->destroy (); } printf("Policies are destroyed !\n"); ACSLogImpl acsLogSvc (m_logger); poa->set_servant (&acsLogSvc); PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId ("ACSLogSvc"); obj = poa->create_reference_with_id (oid.in(), acsLogSvc._interface_repository_id()); CORBA::String_var ior = orb->object_to_string (obj.in()); // if ther is file name write ior in it if (iorFile.length()!=0) { FILE *output_file = ACE_OS::fopen (iorFile.c_str(), "w"); if (output_file == 0) { ACS_SHORT_LOG ((LM_ERROR, "Cannot open output files for writing IOR: ior.ior")); return -1; }//if int result = ACE_OS::fprintf (output_file, "%s", ior.in()); if (result < 0) { ACS_SHORT_LOG ((LM_ERROR, "ACE_OS::fprintf failed while writing %s to ior.ior", ior.in())); return -1; }//if ACE_OS::fclose (output_file); ACS_SHORT_LOG((LM_INFO, "ACSLogSvc's IOR has been written into: %s", iorFile.c_str())); }//if // adding ACSLog to NamingService if (!CORBA::is_nil (naming_context.in ())) { // register cdb server in Naming service CosNaming::Name name (1); name.length (1); name[0].id = CORBA::string_dup ("ACSLogSvc"); naming_context->rebind (name, obj.in ()); ACS_SHORT_LOG((LM_INFO, "ACSLogSvc service registered with Naming Services")); }//if CORBA::Object_var table_object = orb->resolve_initial_references ("IORTable"); IORTable::Table_var adapter = IORTable::Table::_narrow (table_object.in ()); if (CORBA::is_nil (adapter.in ())) { ACS_SHORT_LOG ((LM_ERROR, "Nil IORTable")); } else { adapter->bind ("ACSLogSvc", ior.in ()); } poa_manager->activate (); ACS_SHORT_LOG((LM_INFO, "ACSLogSvc is waiting for incoming log messages ...")); if (argStr.find ("-ORBEndpoint")!=ACE_CString::npos) m_logger.setStdio(31); orb->run (); ACSError::done(); LoggingProxy::done(); } catch( CORBA::Exception &ex ) { ACE_PRINT_EXCEPTION (ex, "EXCEPTION CAUGHT"); return -1; } return 0; } <commit_msg>Changed ACSLog_i for AcsLogService<commit_after>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) European Southern Observatory, 2002 * Copyright by ESO (in the framework of the ALMA collaboration) * and Cosylab 2002, All rights reserved * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: acsLogSvc.cpp,v 1.22 2009/06/09 00:03:30 javarias Exp $" * * who when what * -------- -------- ---------------------------------------------- * gchiozzi 2003-04-03 Fixed ACE_OS::string_to_argv for new ACE * bjeram 2002-04-10 added -silent command line options * bjeram 2002-04-10 added terminal signal handler * bjeram 2002-04-10 added -o options whic write ior also to the file * bjeram 2002-04-10 added registration with Naming Service as ACSLogSvc * bjeram 2001-09-20 change of resolving Log Svc * bjeram 2001-09-11 created */ static char *rcsId="@(#) $Id: acsLogSvc.cpp,v 1.22 2009/06/09 00:03:30 javarias Exp $"; static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId); #include <acslogSvcImpl.h> #include <orbsvcs/CosNamingC.h> #include <tao/IORTable/IORTable.h> #include <maciHelper.h> #include <acserr.h> #include <acsutilPorts.h> CORBA::ORB_var orb; void TerminationSignalHandler(int) { ACS_SHORT_LOG((LM_INFO, "ACSLogSvc is going down (like Bobby Brown :-)) ... ")); orb->shutdown (true); }//TerminationSignalHandler int main(int argc, char *argv[]) { CosNaming::NamingContext_var naming_context; int nargc=0; char **nargv=0; const char *hn=ACSPorts::getIP(); ACE_CString iorFile; if (argc>=2 && !ACE_OS_String::strcmp(argv[1], "-?")){ ACE_OS::printf ("USAGE: acsLogSvc [-ORBInitRef NameService=iiop://yyy:xxxx/NameService] [-ORBEndpoint iiop://ip:port] [-o iorfile] [-silent]\n"); return -1; } // here we have to unset ACS_LOG_CENTRAL that we prevent filtering of log messages char *logCent=getenv("ACS_LOG_CENTRAL"); if (logCent) { unsetenv("ACS_LOG_CENTRAL"); printf("Unset ACS_LOG_CENTRAL which was previously set to %s\n", logCent); }//if // create logging proxy LoggingProxy::ProcessName(argv[0]); ACE_Log_Msg::instance()->local_host(hn); LoggingProxy m_logger (0, 0, 31, 0); LoggingProxy::init (&m_logger); ACS_SHORT_LOG((LM_INFO, "Logging proxy successfully created !")); ACE_CString argStr; for(int i=1; i<argc; i++) { argStr += argv[i]; argStr += " "; if (!ACE_OS_String::strcmp(argv[i], "-o") && (i+1)<argc) { iorFile = argv[i+1]; }//if }//for if (argStr.find ("-ORBEndpoint")==ACE_CString::npos) { argStr = argStr + "-ORBEndpoint iiop://" + hn + ":" + ACSPorts::getLogPort().c_str(); } ACS_SHORT_LOG((LM_INFO, "New command line is: %s", argStr.c_str())); ACE_OS::string_to_argv ((ACE_TCHAR*)argStr.c_str(), nargc, nargv); ACE_OS::signal(SIGINT, TerminationSignalHandler); // Ctrl+C ACE_OS::signal(SIGTERM, TerminationSignalHandler); // termination request try { // Initialize the ORB ACE_OS::printf ("Initialising ORB ... \n"); orb = CORBA::ORB_init (nargc, nargv, 0); ACE_OS::printf ("ORB initialsed !\n"); } catch( CORBA::Exception &ex ) { ACE_PRINT_EXCEPTION (ex, "Failed to initalise ORB"); return -1; } if (!ACSError::init(orb.in())) { ACS_SHORT_LOG ((LM_ERROR, "Failed to initalise the ACS Error System")); return -1; } // resolve naming service try { ACS_SHORT_LOG((LM_INFO, "Trying to connect to the Naming Service ....")); CORBA::Object_var naming_obj = orb->resolve_initial_references ("NameService"); if (!CORBA::is_nil (naming_obj.in ())) { naming_context = CosNaming::NamingContext::_narrow (naming_obj.in ()); ACS_SHORT_LOG((LM_INFO, "Connected to the Name Service")); } else { ACS_SHORT_LOG((LM_ERROR, "Could not connect the Name Service!")); return -1; }//if-else } catch( CORBA::Exception &_ex ) { ACS_SHORT_LOG((LM_ERROR, "Could not connect the Name Service!")); return -1; } // logging service try { CORBA::Object_var log_obj; /* if (argStr.find ("-ORBInitRef NameService=")!=ACE_CString::npos) { // Initialize the ORB ACE_OS::printf ("Initialising ORB ... \n"); orb = CORBA::ORB_init (nargc, nargv, 0); ACE_OS::printf ("ORB initialsed !\n"); //Naming Service ACE_OS::printf ("Resolving Naming service ... \n"); CORBA::Object_var naming_obj = orb->resolve_initial_references ("NameService"); if (!CORBA::is_nil (naming_obj.in ())) { CosNaming::NamingContext_var naming_context = CosNaming::NamingContext::_narrow (naming_obj.in ()); ACE_OS::printf ( "Naming Service resolved !\n"); */ ACE_OS::printf ( "Resolving Logging Service from Naming service ...\n"); CosNaming::Name name; name.length(1); name[0].id = CORBA::string_dup("Log"); log_obj = naming_context->resolve(name); /* } else { ACS_LOG(LM_SOURCE_INFO, "main", (LM_ERROR, "Failed to initialise the Name Service!")); } }//if naming Service else { ACE_OS::printf ("Getting Log from the Manager... \n"); CORBA::ULong status; maci::Manager_ptr manager = maci::MACIHelper::resolveManager (orb.in(), nargc, nargv, 0, 0); log_obj = manager->get_COB(0, "Log", true, status); } */ if (!CORBA::is_nil (log_obj.in())) { Logging::AcsLogService_var logger = Logging::AcsLogService::_narrow(log_obj.in()); ACE_OS::printf ( "Logging Service resolved !\n"); m_logger.setCentralizedLogger(logger.in()); } else { ACS_LOG(LM_SOURCE_INFO, "main", (LM_ERROR, "Failed to initialise the Logging Service!")); return -1; }//if-else } catch( CORBA::Exception &__ex ) { ACE_PRINT_EXCEPTION(__ex, "Failed to get and set the centralized logger"); return -1; } try { //Get a reference to the RootPOA ACE_OS::printf("Creating POA ... \n"); CORBA::Object_var obj = orb->resolve_initial_references("RootPOA"); PortableServer::POA_var root_poa = PortableServer::POA::_narrow(obj.in()); PortableServer::POAManager_var poa_manager = root_poa->the_POAManager(); CORBA::PolicyList policy_list; policy_list.length(5); policy_list[0] = root_poa->create_request_processing_policy (PortableServer::USE_DEFAULT_SERVANT); policy_list[1] = root_poa->create_id_uniqueness_policy (PortableServer::MULTIPLE_ID); policy_list[2] = root_poa->create_id_assignment_policy(PortableServer::USER_ID); policy_list[3] = root_poa->create_servant_retention_policy(PortableServer::NON_RETAIN); policy_list[4] = root_poa->create_lifespan_policy (PortableServer::PERSISTENT); printf("policies are created !\n"); PortableServer::POA_var poa = root_poa->create_POA("ACSLogSvc", poa_manager.in(), policy_list); ACE_OS::printf("POA created !\n"); for (CORBA::ULong i = 0; i < policy_list.length (); ++i) { CORBA::Policy_ptr policy = policy_list[i]; policy->destroy (); } printf("Policies are destroyed !\n"); ACSLogImpl acsLogSvc (m_logger); poa->set_servant (&acsLogSvc); PortableServer::ObjectId_var oid = PortableServer::string_to_ObjectId ("ACSLogSvc"); obj = poa->create_reference_with_id (oid.in(), acsLogSvc._interface_repository_id()); CORBA::String_var ior = orb->object_to_string (obj.in()); // if ther is file name write ior in it if (iorFile.length()!=0) { FILE *output_file = ACE_OS::fopen (iorFile.c_str(), "w"); if (output_file == 0) { ACS_SHORT_LOG ((LM_ERROR, "Cannot open output files for writing IOR: ior.ior")); return -1; }//if int result = ACE_OS::fprintf (output_file, "%s", ior.in()); if (result < 0) { ACS_SHORT_LOG ((LM_ERROR, "ACE_OS::fprintf failed while writing %s to ior.ior", ior.in())); return -1; }//if ACE_OS::fclose (output_file); ACS_SHORT_LOG((LM_INFO, "ACSLogSvc's IOR has been written into: %s", iorFile.c_str())); }//if // adding ACSLog to NamingService if (!CORBA::is_nil (naming_context.in ())) { // register cdb server in Naming service CosNaming::Name name (1); name.length (1); name[0].id = CORBA::string_dup ("ACSLogSvc"); naming_context->rebind (name, obj.in ()); ACS_SHORT_LOG((LM_INFO, "ACSLogSvc service registered with Naming Services")); }//if CORBA::Object_var table_object = orb->resolve_initial_references ("IORTable"); IORTable::Table_var adapter = IORTable::Table::_narrow (table_object.in ()); if (CORBA::is_nil (adapter.in ())) { ACS_SHORT_LOG ((LM_ERROR, "Nil IORTable")); } else { adapter->bind ("ACSLogSvc", ior.in ()); } poa_manager->activate (); ACS_SHORT_LOG((LM_INFO, "ACSLogSvc is waiting for incoming log messages ...")); if (argStr.find ("-ORBEndpoint")!=ACE_CString::npos) m_logger.setStdio(31); orb->run (); ACSError::done(); LoggingProxy::done(); } catch( CORBA::Exception &ex ) { ACE_PRINT_EXCEPTION (ex, "EXCEPTION CAUGHT"); return -1; } return 0; } <|endoftext|>
<commit_before>/* OpenSceneGraph example, osgcluster. * * 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 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 <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <iostream> #if !defined (WIN32) || defined(__CYGWIN__) #include <sys/ioctl.h> #include <sys/uio.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/time.h> #include <net/if.h> #include <netdb.h> #endif #include <string.h> #if defined(__linux) #include <unistd.h> #include <linux/sockios.h> #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) #include <unistd.h> #include <sys/sockio.h> #elif defined(__sgi) #include <unistd.h> #include <net/soioctl.h> #elif defined(__CYGWIN__) #include <unistd.h> #elif defined (__GNU__) #include <unistd.h> #elif defined(__sun) #include <unistd.h> #include <sys/sockio.h> #elif defined (__APPLE__) #include <unistd.h> #include <sys/sockio.h> #elif defined (WIN32) #include <winsock.h> #include <stdio.h> #elif defined (__hpux) #include <unistd.h> #else #error Teach me how to build on this system #endif #include "broadcaster.h" #define _VERBOSE 1 Broadcaster::Broadcaster( void ) { #if defined (__linux) || defined(__CYGWIN__) _ifr_name = "eth0"; #elif defined(__sun) _ifr_name = "hme0"; #elif !defined (WIN32) _ifr_name = "ef0"; #endif _port = 0; _initialized = false; _buffer = 0L; _address = 0; } Broadcaster::~Broadcaster( void ) { #if defined (WIN32) && !defined(__CYGWIN__) closesocket( _so); #else close( _so ); #endif } bool Broadcaster::init( void ) { #if defined (WIN32) && !defined(__CYGWIN__) WORD version = MAKEWORD(1,1); WSADATA wsaData; // First, we start up Winsock WSAStartup(version, &wsaData); #endif if( _port == 0 ) { fprintf( stderr, "Broadcaster::init() - port not defined\n" ); return false; } if( (_so = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 ) { perror( "Socket" ); return false; } #if defined (WIN32) && !defined(__CYGWIN__) const BOOL on = TRUE; #else int on = 1; #endif #if defined (WIN32) && !defined(__CYGWIN__) setsockopt( _so, SOL_SOCKET, SO_REUSEADDR, (const char *) &on, sizeof(int)); #else setsockopt( _so, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); #endif saddr.sin_family = AF_INET; saddr.sin_port = htons( _port ); if( _address == 0 ) { #if defined (WIN32) && !defined(__CYGWIN__) setsockopt( _so, SOL_SOCKET, SO_BROADCAST, (const char *) &on, sizeof(int)); #else setsockopt( _so, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)); #endif #if !defined (WIN32) || defined(__CYGWIN__) struct ifreq ifr; #endif strcpy( ifr.ifr_name, _ifr_name.c_str()); #if defined (WIN32) // get the server address saddr.sin_addr.s_addr = htonl(INADDR_BROADCAST); } #else if( (ioctl( _so, SIOCGIFBRDADDR, &ifr)) < 0 ) { printf(" ifr.ifr_name = %s\n",ifr.ifr_name); perror( "Broadcaster::init() Cannot get Broadcast Address" ); return false; } saddr.sin_addr.s_addr = (((sockaddr_in *)&ifr.ifr_broadaddr)->sin_addr.s_addr); } else { saddr.sin_addr.s_addr = _address; } #endif #define _VERBOSE 1 #ifdef _VERBOSE unsigned char *ptr = (unsigned char *)&saddr.sin_addr.s_addr; printf( "Broadcast address : %u.%u.%u.%u\n", ptr[0], ptr[1], ptr[2], ptr[3] ); #endif _initialized = true; return _initialized; } void Broadcaster::setIFRName( const std::string& name ) { _ifr_name = name; } void Broadcaster::setHost( const char *hostname ) { struct hostent *h; if( (h = gethostbyname( hostname )) == 0L ) { fprintf( stderr, "Broadcaster::setHost() - Cannot resolve an address for \"%s\".\n", hostname ); _address = 0; } else _address = *(( unsigned long *)h->h_addr); } void Broadcaster::setPort( const short port ) { _port = port; } void Broadcaster::setBuffer( void *buffer, const unsigned int size ) { _buffer = buffer; _buffer_size = size; } void Broadcaster::sync( void ) { if(!_initialized) init(); if( _buffer == 0L ) { fprintf( stderr, "Broadcaster::sync() - No buffer\n" ); return; } #if defined (WIN32) && !defined(__CYGWIN__) unsigned int size = sizeof( SOCKADDR_IN ); sendto( _so, (const char *)_buffer, _buffer_size, 0, (struct sockaddr *)&saddr, size ); int err = WSAGetLastError (); if (err!=0) fprintf( stderr, "Broadcaster::sync() - error %d\n",err ); #else unsigned int size = sizeof( struct sockaddr_in ); sendto( _so, (const void *)_buffer, _buffer_size, 0, (struct sockaddr *)&saddr, size ); std::cout<<"sento("<<_buffer<<", "<<_buffer_size<<std::endl; #endif } <commit_msg>VS build fix<commit_after>/* OpenSceneGraph example, osgcluster. * * 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 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 <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <iostream> #if !defined (WIN32) || defined(__CYGWIN__) #include <sys/ioctl.h> #include <sys/uio.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/time.h> #include <net/if.h> #include <netdb.h> #endif #include <string.h> #if defined(__linux) #include <unistd.h> #include <linux/sockios.h> #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) #include <unistd.h> #include <sys/sockio.h> #elif defined(__sgi) #include <unistd.h> #include <net/soioctl.h> #elif defined(__CYGWIN__) #include <unistd.h> #elif defined (__GNU__) #include <unistd.h> #elif defined(__sun) #include <unistd.h> #include <sys/sockio.h> #elif defined (__APPLE__) #include <unistd.h> #include <sys/sockio.h> #elif defined (WIN32) #include <winsock.h> #include <stdio.h> #elif defined (__hpux) #include <unistd.h> #else #error Teach me how to build on this system #endif #include "broadcaster.h" #define _VERBOSE 1 Broadcaster::Broadcaster( void ) { #if defined (__linux) || defined(__CYGWIN__) _ifr_name = "eth0"; #elif defined(__sun) _ifr_name = "hme0"; #elif !defined (WIN32) _ifr_name = "ef0"; #endif _port = 0; _initialized = false; _buffer = 0L; _address = 0; } Broadcaster::~Broadcaster( void ) { #if defined (WIN32) && !defined(__CYGWIN__) closesocket( _so); #else close( _so ); #endif } bool Broadcaster::init( void ) { #if defined (WIN32) && !defined(__CYGWIN__) WORD version = MAKEWORD(1,1); WSADATA wsaData; // First, we start up Winsock WSAStartup(version, &wsaData); #endif if( _port == 0 ) { fprintf( stderr, "Broadcaster::init() - port not defined\n" ); return false; } if( (_so = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 ) { perror( "Socket" ); return false; } #if defined (WIN32) && !defined(__CYGWIN__) const BOOL on = TRUE; #else int on = 1; #endif #if defined (WIN32) && !defined(__CYGWIN__) setsockopt( _so, SOL_SOCKET, SO_REUSEADDR, (const char *) &on, sizeof(int)); #else setsockopt( _so, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); #endif saddr.sin_family = AF_INET; saddr.sin_port = htons( _port ); if( _address == 0 ) { #if defined (WIN32) && !defined(__CYGWIN__) setsockopt( _so, SOL_SOCKET, SO_BROADCAST, (const char *) &on, sizeof(int)); #else setsockopt( _so, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)); #endif #if !defined (WIN32) || defined(__CYGWIN__) struct ifreq ifr; strcpy( ifr.ifr_name, _ifr_name.c_str()); #endif #if defined (WIN32) // get the server address saddr.sin_addr.s_addr = htonl(INADDR_BROADCAST); } #else if( (ioctl( _so, SIOCGIFBRDADDR, &ifr)) < 0 ) { printf(" ifr.ifr_name = %s\n",ifr.ifr_name); perror( "Broadcaster::init() Cannot get Broadcast Address" ); return false; } saddr.sin_addr.s_addr = (((sockaddr_in *)&ifr.ifr_broadaddr)->sin_addr.s_addr); } else { saddr.sin_addr.s_addr = _address; } #endif #define _VERBOSE 1 #ifdef _VERBOSE unsigned char *ptr = (unsigned char *)&saddr.sin_addr.s_addr; printf( "Broadcast address : %u.%u.%u.%u\n", ptr[0], ptr[1], ptr[2], ptr[3] ); #endif _initialized = true; return _initialized; } void Broadcaster::setIFRName( const std::string& name ) { _ifr_name = name; } void Broadcaster::setHost( const char *hostname ) { struct hostent *h; if( (h = gethostbyname( hostname )) == 0L ) { fprintf( stderr, "Broadcaster::setHost() - Cannot resolve an address for \"%s\".\n", hostname ); _address = 0; } else _address = *(( unsigned long *)h->h_addr); } void Broadcaster::setPort( const short port ) { _port = port; } void Broadcaster::setBuffer( void *buffer, const unsigned int size ) { _buffer = buffer; _buffer_size = size; } void Broadcaster::sync( void ) { if(!_initialized) init(); if( _buffer == 0L ) { fprintf( stderr, "Broadcaster::sync() - No buffer\n" ); return; } #if defined (WIN32) && !defined(__CYGWIN__) unsigned int size = sizeof( SOCKADDR_IN ); sendto( _so, (const char *)_buffer, _buffer_size, 0, (struct sockaddr *)&saddr, size ); int err = WSAGetLastError (); if (err!=0) fprintf( stderr, "Broadcaster::sync() - error %d\n",err ); #else unsigned int size = sizeof( struct sockaddr_in ); sendto( _so, (const void *)_buffer, _buffer_size, 0, (struct sockaddr *)&saddr, size ); std::cout<<"sento("<<_buffer<<", "<<_buffer_size<<std::endl; #endif } <|endoftext|>
<commit_before>/* ModbusIP_ESP8266.cpp - Source for Modbus IP ESP8266 AT Library Copyright (C) 2015 Andr Sarmento Barbosa */ #include "ModbusIP_ESP8266AT.h" ModbusIP::ModbusIP() { } void ModbusIP::config(ESP8266 &wifi, String ssid, String password) { //Check errors //Enable serial log wifi.setOprToStationSoftAP(); wifi.joinAP(ssid, password); wifi.enableMUX(); wifi.startTCPServer(MODBUSIP_PORT); wifi.setTCPServerTimeout(MODBUSIP_TIMEOUT); _wifi = &wifi; } void ModbusIP::task() { uint8_t buffer[128] = {0}; uint8_t mux_id; uint32_t len = _wifi->recv(&mux_id, buffer, sizeof(buffer), 100); if (len > 0) { int i = 0; while (i < 7) { _MBAP[i] = buffer[i]; i++; } _len = _MBAP[4] << 8 | _MBAP[5]; _len--; // Do not count with last byte from MBAP if (_MBAP[2] !=0 || _MBAP[3] !=0) return; //Not a MODBUSIP packet if (_len > MODBUSIP_MAXFRAME) return; //Length is over MODBUSIP_MAXFRAME _frame = (byte*) malloc(_len); i = 0; while (i < _len){ _frame[i] = buffer[7+i]; //Forget MBAP and take just modbus pdu i++; } this->receivePDU(_frame); if (_reply != MB_REPLY_OFF) { //MBAP _MBAP[4] = (_len+1) >> 8; //_len+1 for last byte from MBAP _MBAP[5] = (_len+1) & 0x00FF; buffer[4] = _MBAP[4]; buffer[5] = _MBAP[5]; i = 0; while (i < _len){ buffer[i+7] = _frame[i]; i++; } _wifi->send(mux_id, buffer, _len + 7); _wifi->releaseTCP(mux_id); } free(_frame); _len = 0; } } <commit_msg>Release TCP connection anyway<commit_after>/* ModbusIP_ESP8266.cpp - Source for Modbus IP ESP8266 AT Library Copyright (C) 2015 Andr Sarmento Barbosa */ #include "ModbusIP_ESP8266AT.h" ModbusIP::ModbusIP() { } void ModbusIP::config(ESP8266 &wifi, String ssid, String password) { //Check errors //Enable serial log wifi.setOprToStationSoftAP(); wifi.joinAP(ssid, password); wifi.enableMUX(); wifi.startTCPServer(MODBUSIP_PORT); wifi.setTCPServerTimeout(MODBUSIP_TIMEOUT); _wifi = &wifi; } void ModbusIP::task() { uint8_t buffer[128] = {0}; uint8_t mux_id; uint32_t len = _wifi->recv(&mux_id, buffer, sizeof(buffer), 100); if (len > 0) { int i = 0; while (i < 7) { _MBAP[i] = buffer[i]; i++; } _len = _MBAP[4] << 8 | _MBAP[5]; _len--; // Do not count with last byte from MBAP if (_MBAP[2] !=0 || _MBAP[3] !=0) return; //Not a MODBUSIP packet if (_len > MODBUSIP_MAXFRAME) return; //Length is over MODBUSIP_MAXFRAME _frame = (byte*) malloc(_len); i = 0; while (i < _len){ _frame[i] = buffer[7+i]; //Forget MBAP and take just modbus pdu i++; } this->receivePDU(_frame); if (_reply != MB_REPLY_OFF) { //MBAP _MBAP[4] = (_len+1) >> 8; //_len+1 for last byte from MBAP _MBAP[5] = (_len+1) & 0x00FF; buffer[4] = _MBAP[4]; buffer[5] = _MBAP[5]; i = 0; while (i < _len){ buffer[i+7] = _frame[i]; i++; } _wifi->send(mux_id, buffer, _len + 7); } _wifi->releaseTCP(mux_id); free(_frame); _len = 0; } } <|endoftext|>
<commit_before>#include <algorithm> #include <vector> #include "caffe/layer.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/vision_layers.hpp" namespace caffe { template <typename Dtype> void SliceLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const SliceParameter& slice_param = this->layer_param_.slice_param(); slice_dim_ = slice_param.slice_dim(); CHECK_GE(slice_dim_, 0); CHECK_LE(slice_dim_, 1) << "Can only slice num and channels"; slice_point_.clear(); std::copy(slice_param.slice_point().begin(), slice_param.slice_point().end(), std::back_inserter(slice_point_)); } template <typename Dtype> void SliceLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { count_ = 0; num_ = bottom[0]->num(); channels_ = bottom[0]->channels(); height_ = bottom[0]->height(); width_ = bottom[0]->width(); if (slice_point_.size() != 0) { CHECK_EQ(slice_point_.size(), top.size() - 1); if (slice_dim_ == 0) { CHECK_LE(top.size(), num_); } else { CHECK_LE(top.size(), channels_); } int prev = 0; vector<int> slices; for (int i = 0; i < slice_point_.size(); ++i) { CHECK_GT(slice_point_[i], prev); slices.push_back(slice_point_[i] - prev); prev = slice_point_[i]; } if (slice_dim_ == 0) { slices.push_back(num_ - prev); for (int i = 0; i < top.size(); ++i) { top[i]->Reshape(slices[i], channels_, height_, width_); count_ += top[i]->count(); } } else { slices.push_back(channels_ - prev); for (int i = 0; i < top.size(); ++i) { top[i]->Reshape(num_, slices[i], height_, width_); count_ += top[i]->count(); } } } else { if (slice_dim_ == 0) { CHECK_EQ(num_ % top.size(), 0) << "Number of top blobs (" << top.size() << ") " << "should evenly divide input num ( " << num_ << ")"; num_ = num_ / top.size(); } else { CHECK_EQ(channels_ % top.size(), 0) << "Number of top blobs (" << top.size() << ") " << "should evenly divide input channels ( " << channels_ << ")"; channels_ = channels_ / top.size(); } for (int i = 0; i < top.size(); ++i) { top[i]->Reshape(num_, channels_, height_, width_); count_ += top[i]->count(); } } CHECK_EQ(count_, bottom[0]->count()); } template <typename Dtype> void SliceLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->mutable_cpu_data(); if (slice_dim_ == 0) { int offset_num = 0; for (int i = 0; i < top.size(); ++i) { Blob<Dtype>* blob = top[i]; Dtype* top_data = blob->mutable_cpu_data(); caffe_copy(blob->count(), bottom_data + bottom[0]->offset(offset_num), top_data); offset_num += blob->num(); } } else if (slice_dim_ == 1) { int offset_channel = 0; for (int i = 0; i < top.size(); ++i) { Blob<Dtype>* blob = top[i]; Dtype* top_data = blob->mutable_cpu_data(); const int num_elem = blob->channels() * blob->height() * blob->width(); for (int n = 0; n < num_; ++n) { caffe_copy(num_elem, bottom_data + bottom[0]->offset(n, offset_channel), top_data + blob->offset(n)); } offset_channel += blob->channels(); } } // slice_dim_ is guaranteed to be 0 or 1 by SetUp. } template <typename Dtype> void SliceLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (!propagate_down[0]) { return; } Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); if (slice_dim_ == 0) { int offset_num = 0; for (int i = 0; i < top.size(); ++i) { Blob<Dtype>* blob = top[i]; const Dtype* top_diff = blob->cpu_diff(); caffe_copy(blob->count(), top_diff, bottom_diff + bottom[0]->offset(offset_num)); offset_num += blob->num(); } } else if (slice_dim_ == 1) { int offset_channel = 0; for (int i = 0; i < top.size(); ++i) { Blob<Dtype>* blob = top[i]; const Dtype* top_diff = blob->cpu_diff(); const int num_elem = blob->channels() * blob->height() * blob->width(); for (int n = 0; n < num_; ++n) { caffe_copy(num_elem, top_diff + blob->offset(n), bottom_diff + bottom[0]->offset(n, offset_channel)); } offset_channel += blob->channels(); } } // slice_dim_ is guaranteed to be 0 or 1 by SetUp. } #ifdef CPU_ONLY STUB_GPU(SliceLayer); #endif INSTANTIATE_CLASS(SliceLayer); } // namespace caffe <commit_msg>SliceLayer: fix whitespace<commit_after>#include <algorithm> #include <vector> #include "caffe/layer.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/vision_layers.hpp" namespace caffe { template <typename Dtype> void SliceLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const SliceParameter& slice_param = this->layer_param_.slice_param(); slice_dim_ = slice_param.slice_dim(); CHECK_GE(slice_dim_, 0); CHECK_LE(slice_dim_, 1) << "Can only slice num and channels"; slice_point_.clear(); std::copy(slice_param.slice_point().begin(), slice_param.slice_point().end(), std::back_inserter(slice_point_)); } template <typename Dtype> void SliceLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { count_ = 0; num_ = bottom[0]->num(); channels_ = bottom[0]->channels(); height_ = bottom[0]->height(); width_ = bottom[0]->width(); if (slice_point_.size() != 0) { CHECK_EQ(slice_point_.size(), top.size() - 1); if (slice_dim_ == 0) { CHECK_LE(top.size(), num_); } else { CHECK_LE(top.size(), channels_); } int prev = 0; vector<int> slices; for (int i = 0; i < slice_point_.size(); ++i) { CHECK_GT(slice_point_[i], prev); slices.push_back(slice_point_[i] - prev); prev = slice_point_[i]; } if (slice_dim_ == 0) { slices.push_back(num_ - prev); for (int i = 0; i < top.size(); ++i) { top[i]->Reshape(slices[i], channels_, height_, width_); count_ += top[i]->count(); } } else { slices.push_back(channels_ - prev); for (int i = 0; i < top.size(); ++i) { top[i]->Reshape(num_, slices[i], height_, width_); count_ += top[i]->count(); } } } else { if (slice_dim_ == 0) { CHECK_EQ(num_ % top.size(), 0) << "Number of top blobs (" << top.size() << ") " << "should evenly divide input num ( " << num_ << ")"; num_ = num_ / top.size(); } else { CHECK_EQ(channels_ % top.size(), 0) << "Number of top blobs (" << top.size() << ") " << "should evenly divide input channels ( " << channels_ << ")"; channels_ = channels_ / top.size(); } for (int i = 0; i < top.size(); ++i) { top[i]->Reshape(num_, channels_, height_, width_); count_ += top[i]->count(); } } CHECK_EQ(count_, bottom[0]->count()); } template <typename Dtype> void SliceLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->mutable_cpu_data(); if (slice_dim_ == 0) { int offset_num = 0; for (int i = 0; i < top.size(); ++i) { Blob<Dtype>* blob = top[i]; Dtype* top_data = blob->mutable_cpu_data(); caffe_copy(blob->count(), bottom_data + bottom[0]->offset(offset_num), top_data); offset_num += blob->num(); } } else if (slice_dim_ == 1) { int offset_channel = 0; for (int i = 0; i < top.size(); ++i) { Blob<Dtype>* blob = top[i]; Dtype* top_data = blob->mutable_cpu_data(); const int num_elem = blob->channels() * blob->height() * blob->width(); for (int n = 0; n < num_; ++n) { caffe_copy(num_elem, bottom_data + bottom[0]->offset(n, offset_channel), top_data + blob->offset(n)); } offset_channel += blob->channels(); } } // slice_dim_ is guaranteed to be 0 or 1 by SetUp. } template <typename Dtype> void SliceLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (!propagate_down[0]) { return; } Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); if (slice_dim_ == 0) { int offset_num = 0; for (int i = 0; i < top.size(); ++i) { Blob<Dtype>* blob = top[i]; const Dtype* top_diff = blob->cpu_diff(); caffe_copy(blob->count(), top_diff, bottom_diff + bottom[0]->offset(offset_num)); offset_num += blob->num(); } } else if (slice_dim_ == 1) { int offset_channel = 0; for (int i = 0; i < top.size(); ++i) { Blob<Dtype>* blob = top[i]; const Dtype* top_diff = blob->cpu_diff(); const int num_elem = blob->channels() * blob->height() * blob->width(); for (int n = 0; n < num_; ++n) { caffe_copy(num_elem, top_diff + blob->offset(n), bottom_diff + bottom[0]->offset(n, offset_channel)); } offset_channel += blob->channels(); } } // slice_dim_ is guaranteed to be 0 or 1 by SetUp. } #ifdef CPU_ONLY STUB_GPU(SliceLayer); #endif INSTANTIATE_CLASS(SliceLayer); } // namespace caffe <|endoftext|>
<commit_before>//===- lib/ReaderWriter/ELF/Mips/MipsLinkingContext.cpp -------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Atoms.h" #include "MipsLinkingContext.h" #include "MipsRelocationPass.h" #include "MipsTargetHandler.h" #include "llvm/ADT/StringSwitch.h" using namespace lld; using namespace lld::elf; MipsLinkingContext::MipsLinkingContext(llvm::Triple triple) : ELFLinkingContext(triple, std::unique_ptr<TargetHandlerBase>( new MipsTargetHandler(*this))) {} MipsTargetLayout<Mips32ElELFType> &MipsLinkingContext::getTargetLayout() { auto &layout = getTargetHandler<Mips32ElELFType>().targetLayout(); return static_cast<MipsTargetLayout<Mips32ElELFType> &>(layout); } const MipsTargetLayout<Mips32ElELFType> & MipsLinkingContext::getTargetLayout() const { auto &layout = getTargetHandler<Mips32ElELFType>().targetLayout(); return static_cast<MipsTargetLayout<Mips32ElELFType> &>(layout); } bool MipsLinkingContext::isLittleEndian() const { return Mips32ElELFType::TargetEndianness == llvm::support::little; } void MipsLinkingContext::addPasses(PassManager &pm) { auto pass = createMipsRelocationPass(*this); if (pass) pm.add(std::move(pass)); ELFLinkingContext::addPasses(pm); } <commit_msg>[Mips] Remove unnecessary #include pragma.<commit_after>//===- lib/ReaderWriter/ELF/Mips/MipsLinkingContext.cpp -------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Atoms.h" #include "MipsLinkingContext.h" #include "MipsRelocationPass.h" #include "MipsTargetHandler.h" using namespace lld; using namespace lld::elf; MipsLinkingContext::MipsLinkingContext(llvm::Triple triple) : ELFLinkingContext(triple, std::unique_ptr<TargetHandlerBase>( new MipsTargetHandler(*this))) {} MipsTargetLayout<Mips32ElELFType> &MipsLinkingContext::getTargetLayout() { auto &layout = getTargetHandler<Mips32ElELFType>().targetLayout(); return static_cast<MipsTargetLayout<Mips32ElELFType> &>(layout); } const MipsTargetLayout<Mips32ElELFType> & MipsLinkingContext::getTargetLayout() const { auto &layout = getTargetHandler<Mips32ElELFType>().targetLayout(); return static_cast<MipsTargetLayout<Mips32ElELFType> &>(layout); } bool MipsLinkingContext::isLittleEndian() const { return Mips32ElELFType::TargetEndianness == llvm::support::little; } void MipsLinkingContext::addPasses(PassManager &pm) { auto pass = createMipsRelocationPass(*this); if (pass) pm.add(std::move(pass)); ELFLinkingContext::addPasses(pm); } <|endoftext|>
<commit_before>#pragma once #include <b1/session/shared_bytes.hpp> namespace eosio::session { // An immutable structure to represent a key/value pairing. class key_value final { public: friend key_value make_kv(shared_bytes key, shared_bytes value); template <typename Key, typename Value, typename Allocator> friend key_value make_kv(const Key* the_key, size_t key_length, const Value* the_value, size_t value_length, Allocator& a); template <typename Allocator> friend key_value make_kv(const void* key, size_t key_length, const void* value, size_t value_length, Allocator& a); template <typename Key, typename Value> friend key_value make_kv(const Key* the_key, size_t key_length, const Value* the_value, size_t value_length); friend key_value make_kv(const void* key, size_t key_length, const void* value, size_t value_length); public: const shared_bytes& key() const; const shared_bytes& value() const; bool operator==(const key_value& other) const; bool operator!=(const key_value& other) const; static const key_value invalid; private: key_value() = default; private: shared_bytes m_key; shared_bytes m_value; }; // Instantiates a key_value instance from the given key/value shared_bytes. // // \param key The key. // \param value The value. // \returns A key_value instance. // \remarks This factory does not guarentee that the the memory used for the key/value will be contiguous in memory. inline key_value make_kv(shared_bytes key, shared_bytes value) { auto result = key_value{}; result.m_key = std::move(key); result.m_value = std::move(value); return result; } // Instantiaties a key_value instance from the given key/value pointers. // // \tparam Key The pointer type of the key. // \tparam Value The pointer type of the value. // \tparam Allocator The memory allocator type used to manage the shared_bytes memory. This type mush implement the // "memory allocator" concept. \param the_key A pointer to the key. \param key_length The size of the memory pointed by // the key. \param the_value A pointer to the value. \param value_length The size of the memory pointed by the value. // \param a The memory allocator used to managed the memory used by the key_value instance. // \returns A key_value instance. // \remarks This factory guarentees that the memory needed for the key and value will be contiguous in memory. template <typename Key, typename Value, typename Allocator> key_value make_kv(const Key* the_key, size_t key_length, const Value* the_value, size_t value_length, Allocator& a) { auto total_key_length = key_length * sizeof(Key); auto total_value_length = value_length * sizeof(Value); return make_kv(reinterpret_cast<const void*>(the_key), total_key_length, reinterpret_cast<const void*>(the_value), total_value_length, a); } template <typename Key, typename Value> key_value make_kv(const Key* the_key, size_t key_length, const Value* the_value, size_t value_length) { return make_kv(reinterpret_cast<const void*>(the_key), key_length * sizeof(Key), reinterpret_cast<const void*>(the_value), value_length * sizeof(Key)); } inline key_value make_kv(const void* key, size_t key_length, const void* value, size_t value_length) { auto kv = key_value{}; kv.m_key = make_shared_bytes(key, key_length); kv.m_value = make_shared_bytes(value, value_length); return kv; } // Instantiaties a key_value instance from the given key/value pointers. // // \tparam Allocator The memory allocator type used to manage the shared_bytes memory. This type mush implement the // "memory allocator" concept. \param key A pointer to the key. \param key_length The size of the memory pointed by the // key. \param value A pointer to the value. \param value_length The size of the memory pointed by the value. \param a // The memory allocator used to managed the memory used by the key_value instance. \returns A key_value instance. // \remarks This factory guarentees that the memory needed for the key and value will be contiguous in memory. template <typename Allocator> key_value make_kv(const void* key, size_t key_length, const void* value, size_t value_length, Allocator& a) { auto chunk_size = sizeof(shared_bytes::control_block) + key_length + value_length; auto* chunk = reinterpret_cast<int8_t*>(a->allocate(chunk_size)); auto key_bytes = shared_bytes{}; key_bytes.m_chunk_start = chunk; key_bytes.m_chunk_end = chunk + chunk_size; key_bytes.m_control_block = reinterpret_cast<shared_bytes::control_block*>(chunk); key_bytes.m_control_block->memory_allocator_address = reinterpret_cast<uint64_t>(&a->free_function()); key_bytes.m_control_block->use_count = 2; key_bytes.m_data_start = chunk + sizeof(shared_bytes::control_block); key_bytes.m_data_end = key_bytes.m_data_start + key_length; memcpy(key_bytes.m_data_start, key, key_length); auto value_bytes = shared_bytes{}; value_bytes.m_chunk_start = key_bytes.m_chunk_start; value_bytes.m_chunk_end = key_bytes.m_chunk_end; value_bytes.m_control_block = key_bytes.m_control_block; value_bytes.m_data_start = key_bytes.m_data_end; value_bytes.m_data_end = value_bytes.m_data_start + value_length; memcpy(value_bytes.m_data_start, value, value_length); return make_kv(std::move(key_bytes), std::move(value_bytes)); } inline const key_value key_value::invalid{}; inline const shared_bytes& key_value::key() const { return m_key; } inline const shared_bytes& key_value::value() const { return m_value; } inline bool key_value::operator==(const key_value& other) const { return m_key == other.m_key && m_value == other.m_value; } inline bool key_value::operator!=(const key_value& other) const { return !(*this == other); } } // namespace eosio::session <commit_msg>Added control block structure to shared_bytes.<commit_after>#pragma once #include <b1/session/shared_bytes.hpp> #include <cassert> namespace eosio::session { // An immutable structure to represent a key/value pairing. class key_value final { public: friend key_value make_kv(shared_bytes key, shared_bytes value); template <typename Key, typename Value, typename Allocator> friend key_value make_kv(const Key* the_key, size_t key_length, const Value* the_value, size_t value_length, Allocator& a); template <typename Allocator> friend key_value make_kv(const void* key, size_t key_length, const void* value, size_t value_length, Allocator& a); template <typename Key, typename Value> friend key_value make_kv(const Key* the_key, size_t key_length, const Value* the_value, size_t value_length); friend key_value make_kv(const void* key, size_t key_length, const void* value, size_t value_length); public: const shared_bytes& key() const; const shared_bytes& value() const; bool operator==(const key_value& other) const; bool operator!=(const key_value& other) const; static const key_value invalid; private: key_value() = default; private: shared_bytes m_key; shared_bytes m_value; }; // Instantiates a key_value instance from the given key/value shared_bytes. // // \param key The key. // \param value The value. // \returns A key_value instance. // \remarks This factory does not guarentee that the the memory used for the key/value will be contiguous in memory. inline key_value make_kv(shared_bytes key, shared_bytes value) { auto result = key_value{}; result.m_key = std::move(key); result.m_value = std::move(value); return result; } // Instantiaties a key_value instance from the given key/value pointers. // // \tparam Key The pointer type of the key. // \tparam Value The pointer type of the value. // \tparam Allocator The memory allocator type used to manage the shared_bytes memory. This type mush implement the // "memory allocator" concept. \param the_key A pointer to the key. \param key_length The size of the memory pointed by // the key. \param the_value A pointer to the value. \param value_length The size of the memory pointed by the value. // \param a The memory allocator used to managed the memory used by the key_value instance. // \returns A key_value instance. // \remarks This factory guarentees that the memory needed for the key and value will be contiguous in memory. template <typename Key, typename Value, typename Allocator> key_value make_kv(const Key* the_key, size_t key_length, const Value* the_value, size_t value_length, Allocator& a) { auto total_key_length = key_length * sizeof(Key); auto total_value_length = value_length * sizeof(Value); return make_kv(reinterpret_cast<const void*>(the_key), total_key_length, reinterpret_cast<const void*>(the_value), total_value_length, a); } template <typename Key, typename Value> key_value make_kv(const Key* the_key, size_t key_length, const Value* the_value, size_t value_length) { return make_kv(reinterpret_cast<const void*>(the_key), key_length * sizeof(Key), reinterpret_cast<const void*>(the_value), value_length * sizeof(Key)); } inline key_value make_kv(const void* key, size_t key_length, const void* value, size_t value_length) { auto kv = key_value{}; kv.m_key = make_shared_bytes(key, key_length); kv.m_value = make_shared_bytes(value, value_length); return kv; } // Instantiaties a key_value instance from the given key/value pointers. // // \tparam Allocator The memory allocator type used to manage the shared_bytes memory. This type mush implement the // "memory allocator" concept. \param key A pointer to the key. \param key_length The size of the memory pointed by the // key. \param value A pointer to the value. \param value_length The size of the memory pointed by the value. \param a // The memory allocator used to managed the memory used by the key_value instance. \returns A key_value instance. // \remarks This factory guarentees that the memory needed for the key and value will be contiguous in memory. template <typename Allocator> key_value make_kv(const void* key, size_t key_length, const void* value, size_t value_length, Allocator& a) { assert(key && key_length > 0); assert(value && value_length > 0); auto chunk_size = sizeof(shared_bytes::control_block) + key_length + value_length; auto* chunk = reinterpret_cast<int8_t*>(a->allocate(chunk_size)); auto key_bytes = shared_bytes{}; key_bytes.m_chunk_start = chunk; key_bytes.m_chunk_end = chunk + chunk_size; key_bytes.m_control_block = reinterpret_cast<shared_bytes::control_block*>(chunk); key_bytes.m_control_block->memory_allocator_address = reinterpret_cast<uint64_t>(&a->free_function()); key_bytes.m_control_block->use_count = 2; key_bytes.m_data_start = chunk + sizeof(shared_bytes::control_block); key_bytes.m_data_end = key_bytes.m_data_start + key_length; memcpy(key_bytes.m_data_start, key, key_length); auto value_bytes = shared_bytes{}; value_bytes.m_chunk_start = key_bytes.m_chunk_start; value_bytes.m_chunk_end = key_bytes.m_chunk_end; value_bytes.m_control_block = key_bytes.m_control_block; value_bytes.m_data_start = key_bytes.m_data_end; value_bytes.m_data_end = value_bytes.m_data_start + value_length; memcpy(value_bytes.m_data_start, value, value_length); return make_kv(std::move(key_bytes), std::move(value_bytes)); } inline const key_value key_value::invalid{}; inline const shared_bytes& key_value::key() const { return m_key; } inline const shared_bytes& key_value::value() const { return m_value; } inline bool key_value::operator==(const key_value& other) const { return m_key == other.m_key && m_value == other.m_value; } inline bool key_value::operator!=(const key_value& other) const { return !(*this == other); } } // namespace eosio::session <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // File: NekVectorFwd.hpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: // /////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_VECTOR_FWD_HPP #define NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_VECTOR_FWD_HPP #include <boost/typeof/typeof.hpp> #include <LibUtilities/LinearAlgebra/Space.h> #include <boost/type_traits.hpp> #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() namespace Nektar { struct VariableSizedVector {}; // \param DataType The type of data held by each element of the vector. // \param dim The number of elements in the vector. If set to 0, the vector // will have a variable number of elements. // \param space The space of the vector. template<typename DataType, typename dim = VariableSizedVector, typename space = DefaultSpace> class NekVector; BOOST_TYPEOF_REGISTER_TEMPLATE(NekVector, 3); template<typename T> struct IsVector : public boost::false_type {}; template<typename DataType, typename dim, typename space> struct IsVector<NekVector<DataType, dim, space> > : public boost::true_type {}; } #endif //NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_VECTOR_FWD_HPP <commit_msg>Added IsVariableSizedVector metafunction.<commit_after>/////////////////////////////////////////////////////////////////////////////// // // File: NekVectorFwd.hpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: // /////////////////////////////////////////////////////////////////////////////// #ifndef NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_VECTOR_FWD_HPP #define NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_VECTOR_FWD_HPP #include <boost/typeof/typeof.hpp> #include <LibUtilities/LinearAlgebra/Space.h> #include <boost/type_traits.hpp> #include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP() namespace Nektar { struct VariableSizedVector {}; // \param DataType The type of data held by each element of the vector. // \param dim The number of elements in the vector. If set to 0, the vector // will have a variable number of elements. // \param space The space of the vector. template<typename DataType, typename dim = VariableSizedVector, typename space = DefaultSpace> class NekVector; BOOST_TYPEOF_REGISTER_TEMPLATE(NekVector, 3); template<typename T> struct IsVector : public boost::false_type {}; template<typename DataType, typename dim, typename space> struct IsVector<NekVector<DataType, dim, space> > : public boost::true_type {}; template<typename T> struct IsVariableSizedVector : public boost::false_type {}; template<typename DataType, typename space> struct IsVariableSizedVector<NekVector<DataType, VariableSizedVector, space> > : public boost::true_type {}; } #endif //NEKTAR_LIB_UTILITIES_LINEAR_ALGEBRA_NEK_VECTOR_FWD_HPP <|endoftext|>
<commit_before>#include "scenes.h" #include <cstdio> #include <cmath> /* MC::MC() { } MC::MC(ftRender::SubImage image) { im = image; this->body = NULL; this->bodyType = FT_Kinematic; setPosition(0, 0); setRectSize(ftVec2(1.0f, 1.0f)); scale = 1.0f; } void MC::draw() { ftVec2 pos = this->getPosition(); drawImage(im, pos.x, pos.y, this->getAngle(), scale, this->getColor()); } */ void BaseScene::init() { screenC.setViewport(fountain::getWinRect()); cursorID = ftRender::getPicture("res/image/cursor.png"); otherInit(); } void BaseScene::otherInit() { } void BaseScene::update() { otherUpdate(); } void BaseScene::otherUpdate() { } void BaseScene::draw() { drawBG(); otherDraw(); drawCursor(); } void BaseScene::drawBG() { screenC.update(); } void BaseScene::otherDraw() { } void BaseScene::drawCursor() { screenC.update(); ftRender::transformBegin(); ftRender::ftTranslate(screenC.mouseToWorld(fountain::sysMouse.getPos())); ftRender::drawAlphaPic(cursorID); ftRender::transformEnd(); } void OpenScene::otherInit() { } void OpenScene::otherUpdate() { if (fountain::sysMouse.getState(FT_LButton) == FT_ButtonDown) fountain::sceneSelector.gotoScene(new GameScene()); } void OpenScene::otherDraw() { mainCamera.update(); } void MC::draw() { ftVec2 pos = this->getPosition(); drawImage(image, pos.x, pos.y, this->getAngle(), 1.0f, this->getColor()); } ftColor OC::randColor() { float r = ftAlgorithm::randRangef(0.6f, 1.0f); float g = ftAlgorithm::randRangef(0.45f, 1.0f); float b = ftAlgorithm::randRangef(0.0f, 0.2f); return ftColor(r, g, b); } void OC::draw() { ftVec2 pos = this->getPosition(); ftRender::transformBegin(pos.x, pos.y, this->getAngle(), 1.0f, this->getColor()); ftRender::drawShape(shape); ftRender::transformEnd(); ftRender::useColor(FT_White); } void OC::update() { this->move(speed); } void GameScene::otherInit() { ftRender::setClearColor(ftColor("#E30039")); mc.image = ftRender::getImage("res/image/me.png"); OC x; x.shape = ftShape(10.0f); for (int i = 0; i < 100; i++) { x.setColor(OC::randColor()); x.speed = ftVec2(ftAlgorithm::randRangef(-5.0f, 5.0f), ftAlgorithm::randRangef(-5.0f, 5.0f)); ocPool.add(x); } } void GameScene::otherUpdate() { ftVec2 mcPos = mc.getPosition(); ftVec2 target = mainCamera.mouseToWorld(fountain::sysMouse.getPos()); ftVec2 deltaV = target - mcPos; mc.move(deltaV * (mainClock.getDeltaT() * 3.0f)); float d = std::atan(deltaV.y / deltaV.x); if (deltaV.x > 0) d -= 3.14159f / 2.0f; else d += 3.14159f / 2.0f; mc.setAngle(d); ftVec2 camPos = mainCamera.getPosition(); deltaV = mcPos - camPos; mainCamera.move(deltaV * (mainClock.getDeltaT() * 2.0f)); ocPool.update(); } void GameScene::otherDraw() { mainCamera.update(); mc.draw(); ocPool.draw(); } <commit_msg>TimeWell: color change<commit_after>#include "scenes.h" #include <cstdio> #include <cmath> /* MC::MC() { } MC::MC(ftRender::SubImage image) { im = image; this->body = NULL; this->bodyType = FT_Kinematic; setPosition(0, 0); setRectSize(ftVec2(1.0f, 1.0f)); scale = 1.0f; } void MC::draw() { ftVec2 pos = this->getPosition(); drawImage(im, pos.x, pos.y, this->getAngle(), scale, this->getColor()); } */ void BaseScene::init() { screenC.setViewport(fountain::getWinRect()); cursorID = ftRender::getPicture("res/image/cursor.png"); otherInit(); } void BaseScene::otherInit() { } void BaseScene::update() { otherUpdate(); } void BaseScene::otherUpdate() { } void BaseScene::draw() { drawBG(); otherDraw(); drawCursor(); } void BaseScene::drawBG() { screenC.update(); } void BaseScene::otherDraw() { } void BaseScene::drawCursor() { screenC.update(); ftRender::transformBegin(); ftRender::ftTranslate(screenC.mouseToWorld(fountain::sysMouse.getPos())); ftRender::drawAlphaPic(cursorID); ftRender::transformEnd(); } void OpenScene::otherInit() { } void OpenScene::otherUpdate() { if (fountain::sysMouse.getState(FT_LButton) == FT_ButtonDown) fountain::sceneSelector.gotoScene(new GameScene()); } void OpenScene::otherDraw() { mainCamera.update(); } void MC::draw() { ftVec2 pos = this->getPosition(); drawImage(image, pos.x, pos.y, this->getAngle(), 1.0f, this->getColor()); } ftColor OC::randColor() { float a[3]; a[0] = ftAlgorithm::randRangef(0.6f, 1.0f); a[1] = ftAlgorithm::randRangef(0.0f, 0.45f); a[2] = ftAlgorithm::randRangef(0.0f, 0.2f); int rn = (int)ftAlgorithm::randRangef(0.0f, 2.99f); float r = a[rn]; int gn = (int)ftAlgorithm::randRangef(0.0f, 2.99f); while (gn == rn) gn = (int)ftAlgorithm::randRangef(0.0f, 2.99f); float g = a[gn]; int bn = (int)ftAlgorithm::randRangef(0.0f, 2.99f); while (bn == rn || bn == gn) bn = (int)ftAlgorithm::randRangef(0.0f, 2.99f); float b = a[bn]; return ftColor(r, g, b); } void OC::draw() { ftVec2 pos = this->getPosition(); ftRender::transformBegin(pos.x, pos.y, this->getAngle(), 1.0f, this->getColor()); ftRender::drawShape(shape); ftRender::transformEnd(); ftRender::useColor(FT_White); } void OC::update() { this->move(speed); } void GameScene::otherInit() { ftRender::setClearColor(ftColor("#E30039")); mc.image = ftRender::getImage("res/image/me.png"); OC x; x.shape = ftShape(10.0f); for (int i = 0; i < 100; i++) { x.setColor(OC::randColor()); x.speed = ftVec2(ftAlgorithm::randRangef(-5.0f, 5.0f), ftAlgorithm::randRangef(-5.0f, 5.0f)); ocPool.add(x); } } void GameScene::otherUpdate() { ftVec2 mcPos = mc.getPosition(); ftVec2 target = mainCamera.mouseToWorld(fountain::sysMouse.getPos()); ftVec2 deltaV = target - mcPos; mc.move(deltaV * (mainClock.getDeltaT() * 3.0f)); float d = std::atan(deltaV.y / deltaV.x); if (deltaV.x > 0) d -= 3.14159f / 2.0f; else d += 3.14159f / 2.0f; mc.setAngle(d); ftVec2 camPos = mainCamera.getPosition(); deltaV = mcPos - camPos; mainCamera.move(deltaV * (mainClock.getDeltaT() * 2.0f)); ocPool.update(); } void GameScene::otherDraw() { mainCamera.update(); mc.draw(); ocPool.draw(); } <|endoftext|>
<commit_before>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 David Shah <david@symbioticeda.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "timing.h" #include <algorithm> #include <unordered_map> #include <utility> #include "log.h" #include "util.h" NEXTPNR_NAMESPACE_BEGIN typedef std::vector<const PortRef *> PortRefVector; typedef std::map<int, unsigned> DelayFrequency; struct Timing { Context *ctx; bool update; delay_t min_slack; PortRefVector current_path; PortRefVector *crit_path; DelayFrequency *slack_histogram; Timing(Context *ctx, bool update, PortRefVector *crit_path = nullptr, DelayFrequency *slack_histogram = nullptr) : ctx(ctx), update(update), min_slack(1.0e12 / ctx->target_freq), crit_path(crit_path), slack_histogram(slack_histogram) { } delay_t follow_net(NetInfo *net, int path_length, delay_t slack) { delay_t net_budget = slack / (path_length + 1); for (auto &usr : net->users) { if (crit_path) current_path.push_back(&usr); // If budget override is less than existing budget, then do not increment // path length int pl = path_length + 1; auto budget = ctx->getBudgetOverride(net, usr, net_budget); if (budget < net_budget) { net_budget = budget; pl = std::max(1, path_length); } auto delay = ctx->slack_redist_iter > 0 ? ctx->getNetinfoRouteDelay(net, usr) : delay_t(); net_budget = std::min(net_budget, follow_user_port(usr, pl, slack - delay)); if (update) usr.budget = std::min(usr.budget, delay + net_budget); if (crit_path) current_path.pop_back(); } return net_budget; } // Follow a path, returning budget to annotate delay_t follow_user_port(PortRef &user, int path_length, delay_t slack) { delay_t value; if (ctx->getPortClock(user.cell, user.port) != IdString()) { // At the end of a timing path (arguably, should check setup time // here too) value = slack / path_length; if (slack < min_slack) { min_slack = slack; if (crit_path) *crit_path = current_path; } if (slack_histogram) { int slack_ps = ctx->getDelayNS(slack) * 1000; (*slack_histogram)[slack_ps]++; } } else { // Default to the path ending here, if no further paths found value = slack / path_length; // Follow outputs of the user for (auto port : user.cell->ports) { if (port.second.type == PORT_OUT) { DelayInfo comb_delay; // Look up delay through this path bool is_path = ctx->getCellDelay(user.cell, user.port, port.first, comb_delay); if (is_path) { NetInfo *net = port.second.net; if (net) { delay_t path_budget = follow_net(net, path_length, slack - comb_delay.maxDelay()); value = std::min(value, path_budget); } } } } } return value; } delay_t walk_paths() { delay_t default_slack = delay_t(1.0e12 / ctx->target_freq); // Go through all clocked drivers and distribute the available path // slack evenly into the budget of every sink on the path for (auto &cell : ctx->cells) { for (auto port : cell.second->ports) { if (port.second.type == PORT_OUT) { IdString clock_domain = ctx->getPortClock(cell.second.get(), port.first); if (clock_domain != IdString()) { delay_t slack = default_slack; // TODO: clock constraints DelayInfo clkToQ; if (ctx->getCellDelay(cell.second.get(), clock_domain, port.first, clkToQ)) slack -= clkToQ.maxDelay(); if (port.second.net) follow_net(port.second.net, 0, slack); } } } } return min_slack; } void assign_budget() { // Clear delays to a very high value first delay_t default_slack = delay_t(1.0e12 / ctx->target_freq); for (auto &net : ctx->nets) { for (auto &usr : net.second->users) { usr.budget = default_slack; } } walk_paths(); } }; void assign_budget(Context *ctx, bool quiet) { if (!quiet) { log_break(); log_info("Annotating ports with timing budgets for target frequency %.2f MHz\n", ctx->target_freq/1e6); } Timing timing(ctx, true /* update */); timing.assign_budget(); if (!quiet || ctx->verbose) { for (auto &net : ctx->nets) { for (auto &user : net.second->users) { // Post-update check if (!ctx->auto_freq && user.budget < 0) log_warning("port %s.%s, connected to net '%s', has negative " "timing budget of %fns\n", user.cell->name.c_str(ctx), user.port.c_str(ctx), net.first.c_str(ctx), ctx->getDelayNS(user.budget)); else if (ctx->verbose) log_info("port %s.%s, connected to net '%s', has " "timing budget of %fns\n", user.cell->name.c_str(ctx), user.port.c_str(ctx), net.first.c_str(ctx), ctx->getDelayNS(user.budget)); } } } // For slack redistribution, if user has not specified a frequency // dynamically adjust the target frequency to be the currently // achieved maximum if (ctx->auto_freq && ctx->slack_redist_iter > 0) { delay_t default_slack = delay_t(1.0e12 / ctx->target_freq); ctx->target_freq = 1e12 / (default_slack - timing.min_slack); if (ctx->verbose) log_info("minimum slack for this assign = %d, target Fmax for next " "update = %.2f MHz\n", timing.min_slack, ctx->target_freq / 1e6); } if (!quiet) log_info("Checksum: 0x%08x\n", ctx->checksum()); } void timing_analysis(Context *ctx, bool print_histogram, bool print_path) { PortRefVector crit_path; DelayFrequency slack_histogram; Timing timing(ctx, false /* update */, print_path ? &crit_path : nullptr, print_histogram ? &slack_histogram : nullptr); auto min_slack = timing.walk_paths(); if (print_path) { if (crit_path.empty()) { log_info("Design contains no timing paths\n"); } else { delay_t total = 0; log_break(); log_info("Critical path report:\n"); log_info("curr total\n"); auto &front = crit_path.front(); auto &front_port = front->cell->ports.at(front->port); auto &front_driver = front_port.net->driver; auto last_port = ctx->getPortClock(front_driver.cell, front_driver.port); for (auto sink : crit_path) { auto sink_cell = sink->cell; auto &port = sink_cell->ports.at(sink->port); auto net = port.net; auto &driver = net->driver; auto driver_cell = driver.cell; DelayInfo comb_delay; ctx->getCellDelay(sink_cell, last_port, driver.port, comb_delay); total += comb_delay.maxDelay(); log_info("%4d %4d Source %s.%s\n", comb_delay.maxDelay(), total, driver_cell->name.c_str(ctx), driver.port.c_str(ctx)); auto net_delay = ctx->getNetinfoRouteDelay(net, *sink); total += net_delay; auto driver_loc = ctx->getBelLocation(driver_cell->bel); auto sink_loc = ctx->getBelLocation(sink_cell->bel); log_info("%4d %4d Net %s budget %d (%d,%d) -> (%d,%d)\n", net_delay, total, net->name.c_str(ctx), sink->budget, driver_loc.x, driver_loc.y, sink_loc.x, sink_loc.y); log_info(" Sink %s.%s\n", sink_cell->name.c_str(ctx), sink->port.c_str(ctx)); last_port = sink->port; } log_break(); } } delay_t default_slack = delay_t(1.0e12 / ctx->target_freq); log_info("estimated Fmax = %.2f MHz\n", 1e6 / (default_slack - min_slack)); if (print_histogram && slack_histogram.size() > 0) { constexpr unsigned num_bins = 20; unsigned bar_width = 60; auto min_slack = slack_histogram.begin()->first; auto max_slack = slack_histogram.rbegin()->first; auto bin_size = (max_slack - min_slack) / num_bins; std::vector<unsigned> bins(num_bins + 1); unsigned max_freq = 0; for (const auto &i : slack_histogram) { auto &bin = bins[(i.first - min_slack) / bin_size]; bin += i.second; max_freq = std::max(max_freq, bin); } bar_width = std::min(bar_width, max_freq); log_break(); log_info("Slack histogram:\n"); log_info(" legend: * represents %d endpoint(s)\n", max_freq / bar_width); for (unsigned i = 0; i < bins.size(); ++i) log_info("%6d < ps < %6d |%s\n", min_slack + bin_size * i, min_slack + bin_size * (i + 1), std::string(bins[i] * bar_width / max_freq, '*').c_str()); } } NEXTPNR_NAMESPACE_END <commit_msg>Add net_delays bool to Timing class to control net delay consideration<commit_after>/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 David Shah <david@symbioticeda.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "timing.h" #include <algorithm> #include <unordered_map> #include <utility> #include "log.h" #include "util.h" NEXTPNR_NAMESPACE_BEGIN typedef std::vector<const PortRef *> PortRefVector; typedef std::map<int, unsigned> DelayFrequency; struct Timing { Context *ctx; bool net_delays; bool update; delay_t min_slack; PortRefVector current_path; PortRefVector *crit_path; DelayFrequency *slack_histogram; Timing(Context *ctx, bool net_delays, bool update, PortRefVector *crit_path = nullptr, DelayFrequency *slack_histogram = nullptr) : ctx(ctx), net_delays(net_delays), update(update), min_slack(1.0e12 / ctx->target_freq), crit_path(crit_path), slack_histogram(slack_histogram) { } delay_t follow_net(NetInfo *net, int path_length, delay_t slack) { delay_t net_budget = slack / (path_length + 1); for (auto &usr : net->users) { if (crit_path) current_path.push_back(&usr); // If budget override is less than existing budget, then do not increment // path length int pl = path_length + 1; auto budget = ctx->getBudgetOverride(net, usr, net_budget); if (budget < net_budget) { net_budget = budget; pl = std::max(1, path_length); } auto delay = net_delays ? ctx->getNetinfoRouteDelay(net, usr) : delay_t(); net_budget = std::min(net_budget, follow_user_port(usr, pl, slack - delay)); if (update) usr.budget = std::min(usr.budget, delay + net_budget); if (crit_path) current_path.pop_back(); } return net_budget; } // Follow a path, returning budget to annotate delay_t follow_user_port(PortRef &user, int path_length, delay_t slack) { delay_t value; if (ctx->getPortClock(user.cell, user.port) != IdString()) { // At the end of a timing path (arguably, should check setup time // here too) value = slack / path_length; if (slack < min_slack) { min_slack = slack; if (crit_path) *crit_path = current_path; } if (slack_histogram) { int slack_ps = ctx->getDelayNS(slack) * 1000; (*slack_histogram)[slack_ps]++; } } else { // Default to the path ending here, if no further paths found value = slack / path_length; // Follow outputs of the user for (auto port : user.cell->ports) { if (port.second.type == PORT_OUT) { DelayInfo comb_delay; // Look up delay through this path bool is_path = ctx->getCellDelay(user.cell, user.port, port.first, comb_delay); if (is_path) { NetInfo *net = port.second.net; if (net) { delay_t path_budget = follow_net(net, path_length, slack - comb_delay.maxDelay()); value = std::min(value, path_budget); } } } } } return value; } delay_t walk_paths() { delay_t default_slack = delay_t(1.0e12 / ctx->target_freq); // Go through all clocked drivers and distribute the available path // slack evenly into the budget of every sink on the path for (auto &cell : ctx->cells) { for (auto port : cell.second->ports) { if (port.second.type == PORT_OUT) { IdString clock_domain = ctx->getPortClock(cell.second.get(), port.first); if (clock_domain != IdString()) { delay_t slack = default_slack; // TODO: clock constraints DelayInfo clkToQ; if (ctx->getCellDelay(cell.second.get(), clock_domain, port.first, clkToQ)) slack -= clkToQ.maxDelay(); if (port.second.net) follow_net(port.second.net, 0, slack); } } } } return min_slack; } void assign_budget() { // Clear delays to a very high value first delay_t default_slack = delay_t(1.0e12 / ctx->target_freq); for (auto &net : ctx->nets) { for (auto &usr : net.second->users) { usr.budget = default_slack; } } walk_paths(); } }; void assign_budget(Context *ctx, bool quiet) { if (!quiet) { log_break(); log_info("Annotating ports with timing budgets for target frequency %.2f MHz\n", ctx->target_freq/1e6); } Timing timing(ctx, ctx->slack_redist_iter > 0 /* net_delays */, true /* update */); timing.assign_budget(); if (!quiet || ctx->verbose) { for (auto &net : ctx->nets) { for (auto &user : net.second->users) { // Post-update check if (!ctx->auto_freq && user.budget < 0) log_warning("port %s.%s, connected to net '%s', has negative " "timing budget of %fns\n", user.cell->name.c_str(ctx), user.port.c_str(ctx), net.first.c_str(ctx), ctx->getDelayNS(user.budget)); else if (ctx->verbose) log_info("port %s.%s, connected to net '%s', has " "timing budget of %fns\n", user.cell->name.c_str(ctx), user.port.c_str(ctx), net.first.c_str(ctx), ctx->getDelayNS(user.budget)); } } } // For slack redistribution, if user has not specified a frequency // dynamically adjust the target frequency to be the currently // achieved maximum if (ctx->auto_freq && ctx->slack_redist_iter > 0) { delay_t default_slack = delay_t(1.0e12 / ctx->target_freq); ctx->target_freq = 1e12 / (default_slack - timing.min_slack); if (ctx->verbose) log_info("minimum slack for this assign = %d, target Fmax for next " "update = %.2f MHz\n", timing.min_slack, ctx->target_freq / 1e6); } if (!quiet) log_info("Checksum: 0x%08x\n", ctx->checksum()); } void timing_analysis(Context *ctx, bool print_histogram, bool print_path) { PortRefVector crit_path; DelayFrequency slack_histogram; Timing timing(ctx, true /* net_delays */, false /* update */, print_path ? &crit_path : nullptr, print_histogram ? &slack_histogram : nullptr); auto min_slack = timing.walk_paths(); if (print_path) { if (crit_path.empty()) { log_info("Design contains no timing paths\n"); } else { delay_t total = 0; log_break(); log_info("Critical path report:\n"); log_info("curr total\n"); auto &front = crit_path.front(); auto &front_port = front->cell->ports.at(front->port); auto &front_driver = front_port.net->driver; auto last_port = ctx->getPortClock(front_driver.cell, front_driver.port); for (auto sink : crit_path) { auto sink_cell = sink->cell; auto &port = sink_cell->ports.at(sink->port); auto net = port.net; auto &driver = net->driver; auto driver_cell = driver.cell; DelayInfo comb_delay; ctx->getCellDelay(sink_cell, last_port, driver.port, comb_delay); total += comb_delay.maxDelay(); log_info("%4d %4d Source %s.%s\n", comb_delay.maxDelay(), total, driver_cell->name.c_str(ctx), driver.port.c_str(ctx)); auto net_delay = ctx->getNetinfoRouteDelay(net, *sink); total += net_delay; auto driver_loc = ctx->getBelLocation(driver_cell->bel); auto sink_loc = ctx->getBelLocation(sink_cell->bel); log_info("%4d %4d Net %s budget %d (%d,%d) -> (%d,%d)\n", net_delay, total, net->name.c_str(ctx), sink->budget, driver_loc.x, driver_loc.y, sink_loc.x, sink_loc.y); log_info(" Sink %s.%s\n", sink_cell->name.c_str(ctx), sink->port.c_str(ctx)); last_port = sink->port; } log_break(); } } delay_t default_slack = delay_t(1.0e12 / ctx->target_freq); log_info("estimated Fmax = %.2f MHz\n", 1e6 / (default_slack - min_slack)); if (print_histogram && slack_histogram.size() > 0) { constexpr unsigned num_bins = 20; unsigned bar_width = 60; auto min_slack = slack_histogram.begin()->first; auto max_slack = slack_histogram.rbegin()->first; auto bin_size = (max_slack - min_slack) / num_bins; std::vector<unsigned> bins(num_bins + 1); unsigned max_freq = 0; for (const auto &i : slack_histogram) { auto &bin = bins[(i.first - min_slack) / bin_size]; bin += i.second; max_freq = std::max(max_freq, bin); } bar_width = std::min(bar_width, max_freq); log_break(); log_info("Slack histogram:\n"); log_info(" legend: * represents %d endpoint(s)\n", max_freq / bar_width); for (unsigned i = 0; i < bins.size(); ++i) log_info("%6d < ps < %6d |%s\n", min_slack + bin_size * i, min_slack + bin_size * (i + 1), std::string(bins[i] * bar_width / max_freq, '*').c_str()); } } NEXTPNR_NAMESPACE_END <|endoftext|>
<commit_before>//===- PromoteMemoryToRegister.cpp - Convert memory refs to regs ----------===// // // This file is used to promote memory references to be register references. A // simple example of the transformation performed by this function is: // // FROM CODE TO CODE // %X = alloca int, uint 1 ret int 42 // store int 42, int *%X // %Y = load int* %X // ret int %Y // // The code is transformed by looping over all of the alloca instruction, // calculating dominator frontiers, then inserting phi-nodes following the usual // SSA construction algorithm. This code does not modify the CFG of the // function. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/PromoteMemToReg.h" #include "llvm/Analysis/Dominators.h" #include "llvm/iMemory.h" #include "llvm/iPHINode.h" #include "llvm/iTerminators.h" #include "llvm/Function.h" #include "llvm/Constant.h" #include "llvm/Type.h" #include "llvm/Support/CFG.h" #include "Support/StringExtras.h" /// isAllocaPromotable - Return true if this alloca is legal for promotion. /// This is true if there are only loads and stores to the alloca... /// bool isAllocaPromotable(const AllocaInst *AI, const TargetData &TD) { // FIXME: If the memory unit is of pointer or integer type, we can permit // assignments to subsections of the memory unit. // Only allow direct loads and stores... for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end(); UI != UE; ++UI) // Loop over all of the uses of the alloca if (!isa<LoadInst>(*UI)) if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) { if (SI->getOperand(0) == AI) return false; // Don't allow a store of the AI, only INTO the AI. } else { return false; // Not a load or store? } return true; } namespace { struct PromoteMem2Reg { const std::vector<AllocaInst*> &Allocas; // the alloca instructions.. std::vector<unsigned> VersionNumbers; // Current version counters DominanceFrontier &DF; const TargetData &TD; std::map<Instruction*, unsigned> AllocaLookup; // reverse mapping of above std::vector<std::vector<BasicBlock*> > PhiNodes;// Idx corresponds 2 Allocas // List of instructions to remove at end of pass std::vector<Instruction *> KillList; std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes; // the PhiNodes we're adding public: PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominanceFrontier &df, const TargetData &td) : Allocas(A), DF(df), TD(td) {} void run(); private: void RenamePass(BasicBlock *BB, BasicBlock *Pred, std::vector<Value*> &IncVals, std::set<BasicBlock*> &Visited); bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx); }; } // end of anonymous namespace void PromoteMem2Reg::run() { // If there is nothing to do, bail out... if (Allocas.empty()) return; Function &F = *DF.getRoot()->getParent(); VersionNumbers.resize(Allocas.size()); for (unsigned i = 0, e = Allocas.size(); i != e; ++i) { assert(isAllocaPromotable(Allocas[i], TD) && "Cannot promote non-promotable alloca!"); assert(Allocas[i]->getParent()->getParent() == &F && "All allocas should be in the same function, which is same as DF!"); AllocaLookup[Allocas[i]] = i; } // Add each alloca to the KillList. Note: KillList is destroyed MOST recently // added to least recently. KillList.assign(Allocas.begin(), Allocas.end()); // Calculate the set of write-locations for each alloca. This is analogous to // counting the number of 'redefinitions' of each variable. std::vector<std::vector<BasicBlock*> > WriteSets;// Idx corresponds to Allocas WriteSets.resize(Allocas.size()); for (unsigned i = 0; i != Allocas.size(); ++i) { AllocaInst *AI = Allocas[i]; for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E; ++U) if (StoreInst *SI = dyn_cast<StoreInst>(*U)) // jot down the basic-block it came from WriteSets[i].push_back(SI->getParent()); } // Compute the locations where PhiNodes need to be inserted. Look at the // dominance frontier of EACH basic-block we have a write in // PhiNodes.resize(Allocas.size()); for (unsigned i = 0; i != Allocas.size(); ++i) { for (unsigned j = 0; j != WriteSets[i].size(); j++) { // Look up the DF for this write, add it to PhiNodes DominanceFrontier::const_iterator it = DF.find(WriteSets[i][j]); if (it != DF.end()) { const DominanceFrontier::DomSetType &S = it->second; for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end(); P != PE; ++P) QueuePhiNode(*P, i); } } // Perform iterative step for (unsigned k = 0; k != PhiNodes[i].size(); k++) { DominanceFrontier::const_iterator it = DF.find(PhiNodes[i][k]); if (it != DF.end()) { const DominanceFrontier::DomSetType &S = it->second; for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end(); P != PE; ++P) QueuePhiNode(*P, i); } } } // Set the incoming values for the basic block to be null values for all of // the alloca's. We do this in case there is a load of a value that has not // been stored yet. In this case, it will get this null value. // std::vector<Value *> Values(Allocas.size()); for (unsigned i = 0, e = Allocas.size(); i != e; ++i) Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType()); // Walks all basic blocks in the function performing the SSA rename algorithm // and inserting the phi nodes we marked as necessary // std::set<BasicBlock*> Visited; // The basic blocks we've already visited RenamePass(F.begin(), 0, Values, Visited); // Remove all instructions marked by being placed in the KillList... // while (!KillList.empty()) { Instruction *I = KillList.back(); KillList.pop_back(); // If there are any uses of these instructions left, they must be in // sections of dead code that were not processed on the dominance frontier. // Just delete the users now. // while (!I->use_empty()) { Instruction *U = cast<Instruction>(I->use_back()); if (!U->use_empty()) // If uses remain in dead code segment... U->replaceAllUsesWith(Constant::getNullValue(U->getType())); U->getParent()->getInstList().erase(U); } I->getParent()->getInstList().erase(I); } } // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific // Alloca returns true if there wasn't already a phi-node for that variable // bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo) { // Look up the basic-block in question std::vector<PHINode*> &BBPNs = NewPhiNodes[BB]; if (BBPNs.empty()) BBPNs.resize(Allocas.size()); // If the BB already has a phi node added for the i'th alloca then we're done! if (BBPNs[AllocaNo]) return false; // Create a PhiNode using the dereferenced type... and add the phi-node to the // BasicBlock. PHINode *PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(), Allocas[AllocaNo]->getName() + "." + utostr(VersionNumbers[AllocaNo]++), BB->begin()); // Add null incoming values for all predecessors. This ensures that if one of // the predecessors is not found in the depth-first traversal of the CFG (ie, // because it is an unreachable predecessor), that all PHI nodes will have the // correct number of entries for their predecessors. Value *NullVal = Constant::getNullValue(PN->getType()); // This is necessary because adding incoming values to the PHI node adds uses // to the basic blocks being used, which can invalidate the predecessor // iterator! std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB)); for (unsigned i = 0, e = Preds.size(); i != e; ++i) PN->addIncoming(NullVal, Preds[i]); BBPNs[AllocaNo] = PN; PhiNodes[AllocaNo].push_back(BB); return true; } void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred, std::vector<Value*> &IncomingVals, std::set<BasicBlock*> &Visited) { // If this is a BB needing a phi node, lookup/create the phinode for each // variable we need phinodes for. std::vector<PHINode *> &BBPNs = NewPhiNodes[BB]; for (unsigned k = 0; k != BBPNs.size(); ++k) if (PHINode *PN = BBPNs[k]) { // The PHI node may have multiple entries for this predecessor. We must // make sure we update all of them. for (unsigned i = 0, e = PN->getNumOperands(); i != e; i += 2) { if (PN->getOperand(i+1) == Pred) // At this point we can assume that the array has phi nodes.. let's // update the incoming data. PN->setOperand(i, IncomingVals[k]); } // also note that the active variable IS designated by the phi node IncomingVals[k] = PN; } // don't revisit nodes if (Visited.count(BB)) return; // mark as visited Visited.insert(BB); // keep track of the value of each variable we're watching.. how? for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II) { Instruction *I = II; // get the instruction if (LoadInst *LI = dyn_cast<LoadInst>(I)) { if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) { std::map<Instruction*, unsigned>::iterator AI = AllocaLookup.find(Src); if (AI != AllocaLookup.end()) { Value *V = IncomingVals[AI->second]; // walk the use list of this load and replace all uses with r LI->replaceAllUsesWith(V); KillList.push_back(LI); // Mark the load to be deleted } } } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { // Delete this instruction and mark the name as the current holder of the // value if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) { std::map<Instruction *, unsigned>::iterator ai =AllocaLookup.find(Dest); if (ai != AllocaLookup.end()) { // what value were we writing? IncomingVals[ai->second] = SI->getOperand(0); KillList.push_back(SI); // Mark the store to be deleted } } } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I)) { // Recurse across our successors for (unsigned i = 0; i != TI->getNumSuccessors(); i++) { std::vector<Value*> OutgoingVals(IncomingVals); RenamePass(TI->getSuccessor(i), BB, OutgoingVals, Visited); } } } } /// PromoteMemToReg - Promote the specified list of alloca instructions into /// scalar registers, inserting PHI nodes as appropriate. This function makes /// use of DominanceFrontier information. This function does not modify the CFG /// of the function at all. All allocas must be from the same function. /// void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas, DominanceFrontier &DF, const TargetData &TD) { PromoteMem2Reg(Allocas, DF, TD).run(); } <commit_msg>* Minor cleanups * Eliminate the KillList instance variable, instead, just delete loads and stores as they are "renamed", and delete allocas when they are done * Make the 'visited' set an instance variable to avoid passing it on the stack.<commit_after>//===- PromoteMemoryToRegister.cpp - Convert memory refs to regs ----------===// // // This file is used to promote memory references to be register references. A // simple example of the transformation performed by this function is: // // FROM CODE TO CODE // %X = alloca int, uint 1 ret int 42 // store int 42, int *%X // %Y = load int* %X // ret int %Y // // The code is transformed by looping over all of the alloca instruction, // calculating dominator frontiers, then inserting phi-nodes following the usual // SSA construction algorithm. This code does not modify the CFG of the // function. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Utils/PromoteMemToReg.h" #include "llvm/Analysis/Dominators.h" #include "llvm/iMemory.h" #include "llvm/iPHINode.h" #include "llvm/iTerminators.h" #include "llvm/Function.h" #include "llvm/Constant.h" #include "llvm/Type.h" #include "llvm/Support/CFG.h" #include "Support/StringExtras.h" /// isAllocaPromotable - Return true if this alloca is legal for promotion. /// This is true if there are only loads and stores to the alloca... /// bool isAllocaPromotable(const AllocaInst *AI, const TargetData &TD) { // FIXME: If the memory unit is of pointer or integer type, we can permit // assignments to subsections of the memory unit. // Only allow direct loads and stores... for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end(); UI != UE; ++UI) // Loop over all of the uses of the alloca if (!isa<LoadInst>(*UI)) if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) { if (SI->getOperand(0) == AI) return false; // Don't allow a store of the AI, only INTO the AI. } else { return false; // Not a load or store? } return true; } namespace { struct PromoteMem2Reg { const std::vector<AllocaInst*> &Allocas; // the alloca instructions.. std::vector<unsigned> VersionNumbers; // Current version counters DominanceFrontier &DF; const TargetData &TD; std::map<Instruction*, unsigned> AllocaLookup; // reverse mapping of above std::vector<std::vector<BasicBlock*> > PhiNodes;// Idx corresponds 2 Allocas // NewPhiNodes - The PhiNodes we're adding. std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes; // Visited - The set of basic blocks the renamer has already visited. std::set<BasicBlock*> Visited; public: PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominanceFrontier &df, const TargetData &td) : Allocas(A), DF(df), TD(td) {} void run(); private: void RenamePass(BasicBlock *BB, BasicBlock *Pred, std::vector<Value*> &IncVals); bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx); }; } // end of anonymous namespace void PromoteMem2Reg::run() { Function &F = *DF.getRoot()->getParent(); VersionNumbers.resize(Allocas.size()); for (unsigned i = 0, e = Allocas.size(); i != e; ++i) { assert(isAllocaPromotable(Allocas[i], TD) && "Cannot promote non-promotable alloca!"); assert(Allocas[i]->getParent()->getParent() == &F && "All allocas should be in the same function, which is same as DF!"); AllocaLookup[Allocas[i]] = i; } // Calculate the set of write-locations for each alloca. This is analogous to // counting the number of 'redefinitions' of each variable. std::vector<std::vector<BasicBlock*> > WriteSets;// Idx corresponds to Allocas WriteSets.resize(Allocas.size()); for (unsigned i = 0; i != Allocas.size(); ++i) { AllocaInst *AI = Allocas[i]; for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E; ++U) if (StoreInst *SI = dyn_cast<StoreInst>(*U)) // jot down the basic-block it came from WriteSets[i].push_back(SI->getParent()); } // Compute the locations where PhiNodes need to be inserted. Look at the // dominance frontier of EACH basic-block we have a write in // PhiNodes.resize(Allocas.size()); for (unsigned i = 0; i != Allocas.size(); ++i) { for (unsigned j = 0; j != WriteSets[i].size(); j++) { // Look up the DF for this write, add it to PhiNodes DominanceFrontier::const_iterator it = DF.find(WriteSets[i][j]); if (it != DF.end()) { const DominanceFrontier::DomSetType &S = it->second; for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end(); P != PE; ++P) QueuePhiNode(*P, i); } } // Perform iterative step for (unsigned k = 0; k != PhiNodes[i].size(); k++) { DominanceFrontier::const_iterator it = DF.find(PhiNodes[i][k]); if (it != DF.end()) { const DominanceFrontier::DomSetType &S = it->second; for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end(); P != PE; ++P) QueuePhiNode(*P, i); } } } // Set the incoming values for the basic block to be null values for all of // the alloca's. We do this in case there is a load of a value that has not // been stored yet. In this case, it will get this null value. // std::vector<Value *> Values(Allocas.size()); for (unsigned i = 0, e = Allocas.size(); i != e; ++i) Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType()); // Walks all basic blocks in the function performing the SSA rename algorithm // and inserting the phi nodes we marked as necessary // RenamePass(F.begin(), 0, Values); Visited.clear(); // Remove the allocas themselves from the function... for (unsigned i = 0, e = Allocas.size(); i != e; ++i) { Instruction *A = Allocas[i]; // If there are any uses of the alloca instructions left, they must be in // sections of dead code that were not processed on the dominance frontier. // Just delete the users now. // if (!A->use_empty()) A->replaceAllUsesWith(Constant::getNullValue(A->getType())); A->getParent()->getInstList().erase(A); } } // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific // Alloca returns true if there wasn't already a phi-node for that variable // bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo) { // Look up the basic-block in question std::vector<PHINode*> &BBPNs = NewPhiNodes[BB]; if (BBPNs.empty()) BBPNs.resize(Allocas.size()); // If the BB already has a phi node added for the i'th alloca then we're done! if (BBPNs[AllocaNo]) return false; // Create a PhiNode using the dereferenced type... and add the phi-node to the // BasicBlock. PHINode *PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(), Allocas[AllocaNo]->getName() + "." + utostr(VersionNumbers[AllocaNo]++), BB->begin()); // Add null incoming values for all predecessors. This ensures that if one of // the predecessors is not found in the depth-first traversal of the CFG (ie, // because it is an unreachable predecessor), that all PHI nodes will have the // correct number of entries for their predecessors. Value *NullVal = Constant::getNullValue(PN->getType()); // This is necessary because adding incoming values to the PHI node adds uses // to the basic blocks being used, which can invalidate the predecessor // iterator! std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB)); for (unsigned i = 0, e = Preds.size(); i != e; ++i) PN->addIncoming(NullVal, Preds[i]); BBPNs[AllocaNo] = PN; PhiNodes[AllocaNo].push_back(BB); return true; } void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred, std::vector<Value*> &IncomingVals) { // If this is a BB needing a phi node, lookup/create the phinode for each // variable we need phinodes for. std::vector<PHINode *> &BBPNs = NewPhiNodes[BB]; for (unsigned k = 0; k != BBPNs.size(); ++k) if (PHINode *PN = BBPNs[k]) { // The PHI node may have multiple entries for this predecessor. We must // make sure we update all of them. for (unsigned i = 0, e = PN->getNumOperands(); i != e; i += 2) { if (PN->getOperand(i+1) == Pred) // At this point we can assume that the array has phi nodes.. let's // update the incoming data. PN->setOperand(i, IncomingVals[k]); } // also note that the active variable IS designated by the phi node IncomingVals[k] = PN; } // don't revisit nodes if (Visited.count(BB)) return; // mark as visited Visited.insert(BB); BasicBlock::iterator II = BB->begin(); while (1) { Instruction *I = II++; // get the instruction, increment iterator if (LoadInst *LI = dyn_cast<LoadInst>(I)) { if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) { std::map<Instruction*, unsigned>::iterator AI = AllocaLookup.find(Src); if (AI != AllocaLookup.end()) { Value *V = IncomingVals[AI->second]; // walk the use list of this load and replace all uses with r LI->replaceAllUsesWith(V); BB->getInstList().erase(LI); } } } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { // Delete this instruction and mark the name as the current holder of the // value if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) { std::map<Instruction *, unsigned>::iterator ai =AllocaLookup.find(Dest); if (ai != AllocaLookup.end()) { // what value were we writing? IncomingVals[ai->second] = SI->getOperand(0); BB->getInstList().erase(SI); } } } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I)) { // Recurse across our successors for (unsigned i = 0; i != TI->getNumSuccessors(); i++) { std::vector<Value*> OutgoingVals(IncomingVals); RenamePass(TI->getSuccessor(i), BB, OutgoingVals); } break; } } } /// PromoteMemToReg - Promote the specified list of alloca instructions into /// scalar registers, inserting PHI nodes as appropriate. This function makes /// use of DominanceFrontier information. This function does not modify the CFG /// of the function at all. All allocas must be from the same function. /// void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas, DominanceFrontier &DF, const TargetData &TD) { // If there is nothing to do, bail out... if (Allocas.empty()) return; PromoteMem2Reg(Allocas, DF, TD).run(); } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <archie/utils/unique_tuple.h> #include <archie/utils/typeholder.h> #include <archie/utils/get.h> #include <archie/utils/select.h> #include <string> #include <memory> #include <list> namespace detail { struct PackedStruct { struct Id : archie::utils::TypeHolder<unsigned> { using TypeHolder::TypeHolder; }; struct Name : archie::utils::TypeHolder<std::string> { using TypeHolder::TypeHolder; }; struct Value : archie::utils::TypeHolder<int> { using TypeHolder::TypeHolder; }; struct Amount : archie::utils::TypeHolder<unsigned> { using TypeHolder::TypeHolder; }; using type = archie::utils::UniqueTuple<Id, Name, Value, Amount>; }; } struct PackedStruct : detail::PackedStruct::type { using Id = detail::PackedStruct::Id; using Name = detail::PackedStruct::Name; using Value = detail::PackedStruct::Value; using Amount = detail::PackedStruct::Amount; using BaseType = detail::PackedStruct::type; using BaseType::BaseType; }; namespace au = archie::utils; namespace { struct aggregates_test : ::testing::Test { std::unique_ptr<PackedStruct> pack; }; TEST_F(aggregates_test, canCreate) { pack = std::make_unique<PackedStruct>(1, "Aqq", -20, 10); EXPECT_EQ(1, au::get<PackedStruct::Id>(*pack)); EXPECT_EQ("Aqq", *au::get<PackedStruct::Name>(*pack)); EXPECT_EQ(-20, au::get<PackedStruct::Value>(*pack)); pack.reset(); } TEST_F(aggregates_test, canSelect) { pack = std::make_unique<PackedStruct>(1, "Aqq", -20, 10); auto select = au::Select<PackedStruct::Id, PackedStruct::Value>::from(*pack); EXPECT_EQ(1, au::get<PackedStruct::Id>(select)); EXPECT_EQ(-20, au::get<PackedStruct::Value>(select)); } TEST_F(aggregates_test, canSelectCollection) { std::list<PackedStruct> collection; collection.emplace_back(1, "Aqq", -20, 10); collection.emplace_back(2, "Bqq", -10, 20); collection.emplace_back(3, "Cqq", -30, 400); auto select = au::Select<PackedStruct::Id>::from(std::begin(collection), std::end(collection)); ASSERT_EQ(3, select.size()); EXPECT_EQ(1, au::get<PackedStruct::Id>(select[0])); EXPECT_EQ(2, au::get<PackedStruct::Id>(select[1])); EXPECT_EQ(3, au::get<PackedStruct::Id>(select[2])); } TEST_F(aggregates_test, canSelectCollectionIf) { std::list<PackedStruct> collection; collection.emplace_back(1, "Aqq", -20, 10); collection.emplace_back(2, "Bqq", -10, 20); collection.emplace_back(3, "Cqq", -30, 400); auto isOdd = [](auto&& item) { return (*au::get<PackedStruct::Id>(item) % 2) != 0; }; auto select = au::Select<PackedStruct::Id>::from_if( std::begin(collection), std::end(collection), isOdd); ASSERT_EQ(2, select.size()); EXPECT_EQ(1, au::get<PackedStruct::Id>(select[0])); EXPECT_EQ(3, au::get<PackedStruct::Id>(select[1])); } } <commit_msg>apply<commit_after>#include <gtest/gtest.h> #include <archie/utils/unique_tuple.h> #include <archie/utils/typeholder.h> #include <archie/utils/get.h> #include <archie/utils/select.h> #include <string> #include <memory> #include <list> namespace detail { struct PackedStruct { struct Id : archie::utils::TypeHolder<unsigned> { using TypeHolder::TypeHolder; }; struct Name : archie::utils::TypeHolder<std::string> { using TypeHolder::TypeHolder; }; struct Value : archie::utils::TypeHolder<int> { using TypeHolder::TypeHolder; }; struct Amount : archie::utils::TypeHolder<unsigned> { using TypeHolder::TypeHolder; }; using type = archie::utils::UniqueTuple<Id, Name, Value, Amount>; }; } struct PackedStruct : detail::PackedStruct::type { using Id = detail::PackedStruct::Id; using Name = detail::PackedStruct::Name; using Value = detail::PackedStruct::Value; using Amount = detail::PackedStruct::Amount; using BaseType = detail::PackedStruct::type; using BaseType::BaseType; }; namespace au = archie::utils; template <typename... Args> struct Apply { template <typename Func, typename... Types> static auto call(Func func, au::UniqueTuple<Types...> const& ut) -> decltype(func(std::declval<Args>()...)) { return func(au::get<Args>(ut)...); } }; namespace { struct aggregates_test : ::testing::Test { std::unique_ptr<PackedStruct> pack; }; TEST_F(aggregates_test, canCreate) { pack = std::make_unique<PackedStruct>(1, "Aqq", -20, 10); EXPECT_EQ(1, au::get<PackedStruct::Id>(*pack)); EXPECT_EQ("Aqq", *au::get<PackedStruct::Name>(*pack)); EXPECT_EQ(-20, au::get<PackedStruct::Value>(*pack)); pack.reset(); } TEST_F(aggregates_test, canSelect) { pack = std::make_unique<PackedStruct>(1, "Aqq", -20, 10); auto select = au::Select<PackedStruct::Id, PackedStruct::Value>::from(*pack); EXPECT_EQ(1, au::get<PackedStruct::Id>(select)); EXPECT_EQ(-20, au::get<PackedStruct::Value>(select)); } TEST_F(aggregates_test, canSelectCollection) { std::list<PackedStruct> collection; collection.emplace_back(1, "Aqq", -20, 10); collection.emplace_back(2, "Bqq", -10, 20); collection.emplace_back(3, "Cqq", -30, 400); auto select = au::Select<PackedStruct::Id>::from(std::begin(collection), std::end(collection)); ASSERT_EQ(3, select.size()); EXPECT_EQ(1, au::get<PackedStruct::Id>(select[0])); EXPECT_EQ(2, au::get<PackedStruct::Id>(select[1])); EXPECT_EQ(3, au::get<PackedStruct::Id>(select[2])); } TEST_F(aggregates_test, canSelectCollectionIf) { std::list<PackedStruct> collection; collection.emplace_back(1, "Aqq", -20, 10); collection.emplace_back(2, "Bqq", -10, 20); collection.emplace_back(3, "Cqq", -30, 400); auto isOdd = [](auto&& item) { return (*au::get<PackedStruct::Id>(item) % 2) != 0; }; auto select = au::Select<PackedStruct::Id>::from_if( std::begin(collection), std::end(collection), isOdd); ASSERT_EQ(2, select.size()); EXPECT_EQ(1, au::get<PackedStruct::Id>(select[0])); EXPECT_EQ(3, au::get<PackedStruct::Id>(select[1])); } TEST_F(aggregates_test, canApply) { PackedStruct pack(1, "Aqq", -20, 10); auto func = [](auto&& value) { EXPECT_TRUE(value < 0); }; Apply<PackedStruct::Value>::call(func, pack); } } <|endoftext|>
<commit_before>#include "TATUInterpreter.h" TATUInterpreter::Interpreter(unsigned char *string, unsigned int length){ int i; switch(string[0]){ case COMMAND_SET: command.OBJ.TYPE = TATU_SET; if(string[4] == CODE_INFO){ command.OBJ.CODE = TATU_CODE_INFO; // Not implemented yet } else if(string[4] == CODE_STATE){ command.OBJ.CODE = TATU_CODE_STATE; command.OBJ.PIN = ((unsigned int) string[10]) - 49; command.OBJ.STATE = ((unsigned int) string[12]) - 49; } else break; ERROR = false; return; case COMMAND_GET: command.OBJ.TYPE = TATU_GET; if(string[4] == CODE_ALL){ command.OBJ.CODE = TATU_CODE_ALL; } else if(string[4] == CODE_INFO){ command.OBJ.CODE = TATU_CODE_INFO; // Not implemented yet } else if(string[4] == CODE_STATE){ command.OBJ.CODE = TATU_CODE_STATE; command.OBJ.PIN = ((unsigned int) string[9]) - 49; } else break; ERROR = false; return; case COMMAND_EDIT: command.OBJ.TYPE = TATU_EDIT; if(string[5] == CODE_INFO){ command.OBJ.CODE = TATU_CODE_INFO; // Not implemented yet } else if(string[5] == CODE_STATE){ command.OBJ.CODE = TATU_CODE_STATE; command.OBJ.PIN = ((unsigned int) string[11]) - 49; command.OBJ.STATE = ((unsigned int) string[13]) - 49; } else break; ERROR = false; return; case COMMAND_POST: command.OBJ.TYPE = TATU_POST; ERROR = false; return; } ERROR = true; } <commit_msg>Update TATUInterpreter.cpp<commit_after>#include "TATUInterpreter.h" void TATUInterpreter::Interpreter(unsigned char *string, unsigned int length){ int i; switch(string[0]){ case COMMAND_SET: command.OBJ.TYPE = TATU_SET; if(string[4] == CODE_INFO){ command.OBJ.CODE = TATU_CODE_INFO; // Not implemented yet } else if(string[4] == CODE_STATE){ command.OBJ.CODE = TATU_CODE_STATE; command.OBJ.PIN = ((unsigned int) string[10]) - 49; command.OBJ.STATE = ((unsigned int) string[12]) - 49; } else break; ERROR = false; return; case COMMAND_GET: command.OBJ.TYPE = TATU_GET; if(string[4] == CODE_ALL){ command.OBJ.CODE = TATU_CODE_ALL; } else if(string[4] == CODE_INFO){ command.OBJ.CODE = TATU_CODE_INFO; // Not implemented yet } else if(string[4] == CODE_STATE){ command.OBJ.CODE = TATU_CODE_STATE; command.OBJ.PIN = ((unsigned int) string[9]) - 49; } else break; ERROR = false; return; case COMMAND_EDIT: command.OBJ.TYPE = TATU_EDIT; if(string[5] == CODE_INFO){ command.OBJ.CODE = TATU_CODE_INFO; // Not implemented yet } else if(string[5] == CODE_STATE){ command.OBJ.CODE = TATU_CODE_STATE; command.OBJ.PIN = ((unsigned int) string[11]) - 49; command.OBJ.STATE = ((unsigned int) string[13]) - 49; } else break; ERROR = false; return; case COMMAND_POST: command.OBJ.TYPE = TATU_POST; ERROR = false; return; } ERROR = true; } bool TATUInterpreter::getERROR(){ return ERROR; } <|endoftext|>
<commit_before>#include <assert.h> #include <algorithm> #include <cmath> #include <iostream> #include <iomanip> #include <set> #include <ftl/ftl.h> #include "timestamp.h" // Find the sum of all the multiples of 3 or 5 below 1000. int problem1() { return ftl::range(1000) .filter_lazy([](let x){ return x % 3 == 0 || x % 5 == 0; }) .sum(); } // By considering the terms in the Fibonacci sequence whose values do not exceed // four million, find the sum of the even-valued terms. int problem2() { return ftl::unfold(std::make_tuple(1, 1), [](let x){ return std::make_tuple(std::get<1>(x), std::get<0>(x) + std::get<1>(x)); }) .map_lazy([](let x){ return std::get<0>(x); }) .take_while([](let x){ return x < 4'000'000; }) .filter_lazy([](let x){ return x % 2 == 0; }) .sum(); } // What is the largest prime factor of the number 600851475143> uint64_t smallest_prime_factor(int64_t num) { return ftl::iota(2llu) .filter_lazy([num](let p){ return (num % p) == 0; }) .head(); } uint64_t largest_prime_factor(uint64_t num) { let p = smallest_prime_factor(num); return p == num ? p : largest_prime_factor(num / p); } uint64_t problem3() { return largest_prime_factor(600851475143llu); } // Find the difference between the sum of the squares of the first one hundred // natural numbers and the square of the sum. uint64_t problem6() { let n = 100; let square = [](let x){ return x * x; }; let sum_squares = ftl::range(1, n + 1).map_lazy(square).sum(); let square_sum = square(ftl::range(1, n + 1).sum()); return square_sum - sum_squares; } // What is the value of the first triangle number to have over five hundred // divisors? uint64_t problem12() { let num_divisors = [](let n) { let sqrtn = static_cast<uint64_t>(std::sqrt(n + 0.99)); return ftl::range(1llu, sqrtn) .filter_lazy([n](let i) { return n % i == 0; }) .map_lazy([](let _) { return 1llu; }) .sum() * 2 + (sqrtn * sqrtn == 1 ? 1 : 0); }; return ftl::iota(1llu) .map_lazy([](let x) { return x * (x + 1) / 2; }) .filter_lazy([&num_divisors](let x){ return num_divisors(x) > 500llu; }) .head(); } uint64_t problem14() { let chain_length = [](let n){ return ftl::unfold(n, [](let i){ if (i == 1) { return ftl::optional<uint64_t>(); } else if (i % 2 == 0) { return ftl::make_optional(i / 2); } else { return ftl::make_optional(3 * i + 1); } }) .map_lazy([](let _){ return 1; }) .sum(); }; return std::get<0>(ftl::range(1llu, 1'000'000llu) .map_lazy([chain_length](let i){ return std::make_tuple(i, chain_length(i)); }) .reduce(std::make_tuple(0llu, 0), [](let acc, let val){ if (std::get<1>(acc) < std::get<1>(val)) { return val; } else { return acc; } })); } // Find the sum of all the positive integers which cannot be written as the sum // of two abundant numbers. uint64_t problem23() { let max_num = 28123; let is_abundant_impl = [](let n){ let sqrtn = static_cast<int>(std::sqrt(n + 0.99)); let sum_divisors = ftl::range(1, sqrtn + 1) .filter_lazy([n](let i){ return n % i == 0; }) .map_lazy([n](let i){ return i == 1 || i * i == n ? i : i + n / i; }) .sum(); return sum_divisors > n; }; let is_abundant = ftl::memoize<decltype(is_abundant_impl), int>( is_abundant_impl); let abundants = ftl::range(1, max_num + 1).filter(is_abundant); let is_sum_abundants = [&is_abundant, &abundants](let n){ return abundants .filter_lazy([n](let k){ return k < n; }) .filter_lazy([n, &is_abundant](let k){ return is_abundant(n - k); }) .any(); }; return ftl::range(1, max_num + 1) .filter_lazy([&is_sum_abundants](let i){ return !is_sum_abundants(i); }) .sum(); } template <typename Func> void do_run(const std::string &name, const Func &f) { uint64_t t_start = timestamp_ms(); let res = f(); uint64_t t_stop = timestamp_ms(); std::cout << std::setw(10) << std::left << name << " | " << std::setw(10) << std::right << res << " | " << std::setw(5) << t_stop - t_start << "ms" << std::endl; } #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define RUN(f) do_run(TOSTRING(f), (f)) int main() { const char* spacing = "----------------------------------"; std::cout << spacing << std::endl << "| Project Euler examples |" << std::endl << spacing << std::endl; RUN(problem1); RUN(problem2); RUN(problem3); RUN(problem6); RUN(problem12); RUN(problem14); RUN(problem23); std::cout << spacing << std::endl; } <commit_msg>moved to int<commit_after>#include <assert.h> #include <algorithm> #include <cmath> #include <iostream> #include <iomanip> #include <set> #include <ftl/ftl.h> #include "timestamp.h" // Find the sum of all the multiples of 3 or 5 below 1000. int problem1() { return ftl::range(1000) .filter_lazy([](let x){ return x % 3 == 0 || x % 5 == 0; }) .sum(); } // By considering the terms in the Fibonacci sequence whose values do not exceed // four million, find the sum of the even-valued terms. int problem2() { return ftl::unfold(std::make_tuple(1, 1), [](let x){ return std::make_tuple(std::get<1>(x), std::get<0>(x) + std::get<1>(x)); }) .map_lazy([](let x){ return std::get<0>(x); }) .take_while([](let x){ return x < 4'000'000; }) .filter_lazy([](let x){ return x % 2 == 0; }) .sum(); } // What is the largest prime factor of the number 600851475143> uint64_t smallest_prime_factor(int64_t num) { return ftl::iota(2llu) .filter_lazy([num](let p){ return (num % p) == 0; }) .head(); } uint64_t largest_prime_factor(uint64_t num) { let p = smallest_prime_factor(num); return p == num ? p : largest_prime_factor(num / p); } uint64_t problem3() { return largest_prime_factor(600851475143llu); } // Find the difference between the sum of the squares of the first one hundred // natural numbers and the square of the sum. uint64_t problem6() { let n = 100; let square = [](let x){ return x * x; }; let sum_squares = ftl::range(1, n + 1).map_lazy(square).sum(); let square_sum = square(ftl::range(1, n + 1).sum()); return square_sum - sum_squares; } // What is the value of the first triangle number to have over five hundred // divisors? uint64_t problem12() { let num_divisors = [](let n) { let sqrtn = static_cast<int>(std::sqrt(n + 0.99)); return ftl::range(1, sqrtn) .filter_lazy([n](let i) { return n % i == 0; }) .map_lazy([](let _) { return 1; }) .sum() * 2 + (sqrtn * sqrtn == 1 ? 1 : 0); }; return ftl::iota(1) .map_lazy([](let x) { return x * (x + 1) / 2; }) .filter_lazy([&num_divisors](let x){ return num_divisors(x) > 500; }) .head(); } uint64_t problem14() { let chain_length = [](let n){ return ftl::unfold(n, [](let i){ if (i == 1) { return ftl::optional<uint64_t>(); } else if (i % 2 == 0) { return ftl::make_optional(i / 2); } else { return ftl::make_optional(3 * i + 1); } }) .map_lazy([](let _){ return 1; }) .sum(); }; return std::get<0>(ftl::range(1llu, 1'000'000llu) .map_lazy([chain_length](let i){ return std::make_tuple(i, chain_length(i)); }) .reduce(std::make_tuple(0llu, 0), [](let acc, let val){ if (std::get<1>(acc) < std::get<1>(val)) { return val; } else { return acc; } })); } // Find the sum of all the positive integers which cannot be written as the sum // of two abundant numbers. uint64_t problem23() { let max_num = 28123; let is_abundant_impl = [](let n){ let sqrtn = static_cast<int>(std::sqrt(n + 0.99)); let sum_divisors = ftl::range(1, sqrtn + 1) .filter_lazy([n](let i){ return n % i == 0; }) .map_lazy([n](let i){ return i == 1 || i * i == n ? i : i + n / i; }) .sum(); return sum_divisors > n; }; let is_abundant = ftl::memoize<decltype(is_abundant_impl), int>( is_abundant_impl); let abundants = ftl::range(1, max_num + 1).filter(is_abundant); let is_sum_abundants = [&is_abundant, &abundants](let n){ return abundants .filter_lazy([n](let k){ return k < n; }) .filter_lazy([n, &is_abundant](let k){ return is_abundant(n - k); }) .any(); }; return ftl::range(1, max_num + 1) .filter_lazy([&is_sum_abundants](let i){ return !is_sum_abundants(i); }) .sum(); } template <typename Func> void do_run(const std::string &name, const Func &f) { uint64_t t_start = timestamp_ms(); let res = f(); uint64_t t_stop = timestamp_ms(); std::cout << std::setw(10) << std::left << name << " | " << std::setw(10) << std::right << res << " | " << std::setw(5) << t_stop - t_start << "ms" << std::endl; } #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define RUN(f) do_run(TOSTRING(f), (f)) int main() { const char* spacing = "----------------------------------"; std::cout << spacing << std::endl << "| Project Euler examples |" << std::endl << spacing << std::endl; RUN(problem1); RUN(problem2); RUN(problem3); RUN(problem6); RUN(problem12); RUN(problem14); RUN(problem23); std::cout << spacing << std::endl; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlideSorterView.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: kz $ $Date: 2008-04-03 14:38:09 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_SLIDESORTER_SLIDE_SORTER_VIEW_HXX #define SD_SLIDESORTER_SLIDE_SORTER_VIEW_HXX #include "View.hxx" #include "model/SlsSharedPageDescriptor.hxx" #include <sfx2/viewfrm.hxx> #ifndef _PRESENTATION_HXX #include "pres.hxx" #endif #ifndef _SV_GEN_HXX #include <tools/gen.hxx> #endif #include <memory> #include <boost/shared_ptr.hpp> class Point; namespace sdr { namespace contact { class ObjectContact; } } namespace sd { namespace slidesorter { class SlideSorter; } } namespace sd { namespace slidesorter { namespace controller { class SlideSorterController; } } } namespace sd { namespace slidesorter { namespace cache { class PageCache; } } } namespace sd { namespace slidesorter { namespace model { class SlideSorterModel; } } } namespace sd { namespace slidesorter { namespace view { class Layouter; class ViewOverlay; class SlideSorterView : public View { public: TYPEINFO(); /** Create a new view for the slide sorter. @param rViewShell This reference is simply passed to the base class and not used by this class. */ SlideSorterView (SlideSorter& rSlideSorter); virtual ~SlideSorterView (void); enum Orientation { HORIZONTAL, VERTICAL }; void SetOrientation (const Orientation eOrientation); Orientation GetOrientation (void) const; void RequestRepaint (void); void RequestRepaint (const model::SharedPageDescriptor& rDescriptor); Rectangle GetModelArea (void); enum CoordinateSystem { CS_SCREEN, CS_MODEL }; enum BoundingBoxType { BBT_SHAPE, BBT_INFO }; /** Return the rectangle that bounds the page object represented by the given page descriptor. @param rDescriptor The descriptor of the page for which to return the bounding box. @param eCoordinateSystem Specifies whether to return the screen or model coordinates. @param eBoundingBoxType Specifies whether to return the bounding box of only the page object or the one that additionally includes other displayed information like page name and fader symbol. */ Rectangle GetPageBoundingBox ( const model::SharedPageDescriptor& rpDescriptor, CoordinateSystem eCoordinateSystem, BoundingBoxType eBoundingBoxType) const; /** Return the rectangle that bounds the page object represented by the given page index . @param nIndex The index of the page for which to return the bounding box. @param eCoordinateSystem Specifies whether to return the screen or model coordinates. @param eBoundingBoxType Specifies whether to return the bounding box of only the page object or the one that additionally includes other displayed information like page name and fader symbol. */ Rectangle GetPageBoundingBox ( sal_Int32 nIndex, CoordinateSystem eCoordinateSystem, BoundingBoxType eBoundingBoxType) const; /** Return the index of the page that is rendered at the given position. @param rPosition The position is expected to be in pixel coordinates. @return The returned index is -1 when there is no page object at the given position. */ sal_Int32 GetPageIndexAtPoint (const Point& rPosition) const; sal_Int32 GetFadePageIndexAtPoint (const Point& rPosition) const; view::Layouter& GetLayouter (void); virtual void ModelHasChanged (void); void LocalModelHasChanged(void); /** This method is typically called before a model change takes place. All references to model data are released. PostModelChange() has to be called to complete the handling of the model change. When the calls to Pre- and PostModelChange() are very close to each other you may call HandleModelChange() instead. */ void PreModelChange (void); /** This method is typically called after a model change took place. References to model data are re-allocated. Call this method only after PreModelChange() has been called. */ void PostModelChange (void); /** This method is a convenience function that simply calls PreModelChange() and then PostModelChange(). */ void HandleModelChange (void); void HandleDrawModeChange (void); virtual void Resize (void); virtual void CompleteRedraw ( OutputDevice* pDevice, const Region& rPaintArea, USHORT nPaintMode, ::sdr::contact::ViewObjectContactRedirector* pRedirector = 0L); virtual void InvalidateOneWin ( ::Window& rWindow); virtual void InvalidateOneWin ( ::Window& rWindow, const Rectangle& rPaintArea ); void Layout (void); /** This tells the view that it has to re-determine the visibility of the page objects before painting them the next time. */ void InvalidatePageObjectVisibilities (void); /** Return the window to which this view renders its output. */ ::sd::Window* GetWindow (void) const; ::boost::shared_ptr<cache::PageCache> GetPreviewCache (void); view::ViewOverlay& GetOverlay (void); /** Set the bounding box of the insertion marker in model coordinates. It will be painted as a dark rectangle that fills the given box. */ void SetInsertionMarker (const Rectangle& rBBox); /** Specify whether the insertion marker will be painted or not. */ void SetInsertionMarkerVisibility (bool bVisible); /** Set the size and position of the selection rectangle. It will be painted as a dashed rectangle. */ void SetSelectionRectangle (const Rectangle& rBox); /** Specify whether the selection rectangle will be painted or not. */ void SetSelectionRectangleVisibility (bool bVisible); ::sdr::contact::ObjectContact& GetObjectContact (void) const; typedef ::std::pair<sal_Int32,sal_Int32> PageRange; /** Return the range of currently visible page objects including the first and last one in that range. @return The returned pair of page object indices is empty when the second index is lower than the first. */ PageRange GetVisiblePageRange (void); /** Return the size of the area where the page numbers are displayed. @return The returned size is given in model coordinates. */ Size GetPageNumberAreaModelSize (void) const; /** Return the size of the border around the original SdrPageObj. */ SvBorder GetModelBorder (void) const; /** Add a shape to the page. Typically used from inside PostModelChange(). */ void AddSdrObject (SdrObject& rObject); protected: virtual void Notify (SfxBroadcaster& rBroadcaster, const SfxHint& rHint); private: SlideSorter& mrSlideSorter; model::SlideSorterModel& mrModel; /// This model is used for the maPage object. SdrModel maPageModel; /** This page acts as container for the page objects that represent the pages of the document that is represented by the SlideSorterModel. */ SdrPage* mpPage; ::std::auto_ptr<Layouter> mpLayouter; bool mbPageObjectVisibilitiesValid; ::boost::shared_ptr<cache::PageCache> mpPreviewCache; ::std::auto_ptr<ViewOverlay> mpViewOverlay; int mnFirstVisiblePageIndex; int mnLastVisiblePageIndex; SvBorder maPagePixelBorder; bool mbModelChangedWhileModifyEnabled; Size maPreviewSize; bool mbPreciousFlagUpdatePending; Size maPageNumberAreaModelSize; SvBorder maModelBorder; Orientation meOrientation; /** Adapt the coordinates of the given bounding box according to the other parameters. @param rModelPageObjectBoundingBox Bounding box given in model coordinates that bounds only the page object. @param eCoordinateSystem When CS_SCREEN is given then the bounding box is converted into screen coordinates. @param eBoundingBoxType When BBT_INFO is given then the bounding box is made larger so that it encloses all relevant displayed information. */ void AdaptBoundingBox ( Rectangle& rModelPageObjectBoundingBox, CoordinateSystem eCoordinateSystem, BoundingBoxType eBoundingBoxType) const; /** Determine the visibility of all page objects. */ void DeterminePageObjectVisibilities (void); /** Update the page borders used by the layouter by using those returned by the first page. Call this function when the model changes, especially when the number of pages changes, or when the window is resized as the borders may be device dependent. */ void UpdatePageBorders (void); void UpdatePreciousFlags (void); }; } } } // end of namespace ::sd::slidesorter::view #endif <commit_msg>INTEGRATION: CWS changefileheader (1.11.298); FILE MERGED 2008/04/01 15:35:56 thb 1.11.298.3: #i85898# Stripping all external header guards 2008/04/01 12:39:18 thb 1.11.298.2: #i85898# Stripping all external header guards 2008/03/31 13:58:52 rt 1.11.298.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: SlideSorterView.hxx,v $ * $Revision: 1.14 $ * * 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. * ************************************************************************/ #ifndef SD_SLIDESORTER_SLIDE_SORTER_VIEW_HXX #define SD_SLIDESORTER_SLIDE_SORTER_VIEW_HXX #include "View.hxx" #include "model/SlsSharedPageDescriptor.hxx" #include <sfx2/viewfrm.hxx> #include "pres.hxx" #include <tools/gen.hxx> #include <memory> #include <boost/shared_ptr.hpp> class Point; namespace sdr { namespace contact { class ObjectContact; } } namespace sd { namespace slidesorter { class SlideSorter; } } namespace sd { namespace slidesorter { namespace controller { class SlideSorterController; } } } namespace sd { namespace slidesorter { namespace cache { class PageCache; } } } namespace sd { namespace slidesorter { namespace model { class SlideSorterModel; } } } namespace sd { namespace slidesorter { namespace view { class Layouter; class ViewOverlay; class SlideSorterView : public View { public: TYPEINFO(); /** Create a new view for the slide sorter. @param rViewShell This reference is simply passed to the base class and not used by this class. */ SlideSorterView (SlideSorter& rSlideSorter); virtual ~SlideSorterView (void); enum Orientation { HORIZONTAL, VERTICAL }; void SetOrientation (const Orientation eOrientation); Orientation GetOrientation (void) const; void RequestRepaint (void); void RequestRepaint (const model::SharedPageDescriptor& rDescriptor); Rectangle GetModelArea (void); enum CoordinateSystem { CS_SCREEN, CS_MODEL }; enum BoundingBoxType { BBT_SHAPE, BBT_INFO }; /** Return the rectangle that bounds the page object represented by the given page descriptor. @param rDescriptor The descriptor of the page for which to return the bounding box. @param eCoordinateSystem Specifies whether to return the screen or model coordinates. @param eBoundingBoxType Specifies whether to return the bounding box of only the page object or the one that additionally includes other displayed information like page name and fader symbol. */ Rectangle GetPageBoundingBox ( const model::SharedPageDescriptor& rpDescriptor, CoordinateSystem eCoordinateSystem, BoundingBoxType eBoundingBoxType) const; /** Return the rectangle that bounds the page object represented by the given page index . @param nIndex The index of the page for which to return the bounding box. @param eCoordinateSystem Specifies whether to return the screen or model coordinates. @param eBoundingBoxType Specifies whether to return the bounding box of only the page object or the one that additionally includes other displayed information like page name and fader symbol. */ Rectangle GetPageBoundingBox ( sal_Int32 nIndex, CoordinateSystem eCoordinateSystem, BoundingBoxType eBoundingBoxType) const; /** Return the index of the page that is rendered at the given position. @param rPosition The position is expected to be in pixel coordinates. @return The returned index is -1 when there is no page object at the given position. */ sal_Int32 GetPageIndexAtPoint (const Point& rPosition) const; sal_Int32 GetFadePageIndexAtPoint (const Point& rPosition) const; view::Layouter& GetLayouter (void); virtual void ModelHasChanged (void); void LocalModelHasChanged(void); /** This method is typically called before a model change takes place. All references to model data are released. PostModelChange() has to be called to complete the handling of the model change. When the calls to Pre- and PostModelChange() are very close to each other you may call HandleModelChange() instead. */ void PreModelChange (void); /** This method is typically called after a model change took place. References to model data are re-allocated. Call this method only after PreModelChange() has been called. */ void PostModelChange (void); /** This method is a convenience function that simply calls PreModelChange() and then PostModelChange(). */ void HandleModelChange (void); void HandleDrawModeChange (void); virtual void Resize (void); virtual void CompleteRedraw ( OutputDevice* pDevice, const Region& rPaintArea, USHORT nPaintMode, ::sdr::contact::ViewObjectContactRedirector* pRedirector = 0L); virtual void InvalidateOneWin ( ::Window& rWindow); virtual void InvalidateOneWin ( ::Window& rWindow, const Rectangle& rPaintArea ); void Layout (void); /** This tells the view that it has to re-determine the visibility of the page objects before painting them the next time. */ void InvalidatePageObjectVisibilities (void); /** Return the window to which this view renders its output. */ ::sd::Window* GetWindow (void) const; ::boost::shared_ptr<cache::PageCache> GetPreviewCache (void); view::ViewOverlay& GetOverlay (void); /** Set the bounding box of the insertion marker in model coordinates. It will be painted as a dark rectangle that fills the given box. */ void SetInsertionMarker (const Rectangle& rBBox); /** Specify whether the insertion marker will be painted or not. */ void SetInsertionMarkerVisibility (bool bVisible); /** Set the size and position of the selection rectangle. It will be painted as a dashed rectangle. */ void SetSelectionRectangle (const Rectangle& rBox); /** Specify whether the selection rectangle will be painted or not. */ void SetSelectionRectangleVisibility (bool bVisible); ::sdr::contact::ObjectContact& GetObjectContact (void) const; typedef ::std::pair<sal_Int32,sal_Int32> PageRange; /** Return the range of currently visible page objects including the first and last one in that range. @return The returned pair of page object indices is empty when the second index is lower than the first. */ PageRange GetVisiblePageRange (void); /** Return the size of the area where the page numbers are displayed. @return The returned size is given in model coordinates. */ Size GetPageNumberAreaModelSize (void) const; /** Return the size of the border around the original SdrPageObj. */ SvBorder GetModelBorder (void) const; /** Add a shape to the page. Typically used from inside PostModelChange(). */ void AddSdrObject (SdrObject& rObject); protected: virtual void Notify (SfxBroadcaster& rBroadcaster, const SfxHint& rHint); private: SlideSorter& mrSlideSorter; model::SlideSorterModel& mrModel; /// This model is used for the maPage object. SdrModel maPageModel; /** This page acts as container for the page objects that represent the pages of the document that is represented by the SlideSorterModel. */ SdrPage* mpPage; ::std::auto_ptr<Layouter> mpLayouter; bool mbPageObjectVisibilitiesValid; ::boost::shared_ptr<cache::PageCache> mpPreviewCache; ::std::auto_ptr<ViewOverlay> mpViewOverlay; int mnFirstVisiblePageIndex; int mnLastVisiblePageIndex; SvBorder maPagePixelBorder; bool mbModelChangedWhileModifyEnabled; Size maPreviewSize; bool mbPreciousFlagUpdatePending; Size maPageNumberAreaModelSize; SvBorder maModelBorder; Orientation meOrientation; /** Adapt the coordinates of the given bounding box according to the other parameters. @param rModelPageObjectBoundingBox Bounding box given in model coordinates that bounds only the page object. @param eCoordinateSystem When CS_SCREEN is given then the bounding box is converted into screen coordinates. @param eBoundingBoxType When BBT_INFO is given then the bounding box is made larger so that it encloses all relevant displayed information. */ void AdaptBoundingBox ( Rectangle& rModelPageObjectBoundingBox, CoordinateSystem eCoordinateSystem, BoundingBoxType eBoundingBoxType) const; /** Determine the visibility of all page objects. */ void DeterminePageObjectVisibilities (void); /** Update the page borders used by the layouter by using those returned by the first page. Call this function when the model changes, especially when the number of pages changes, or when the window is resized as the borders may be device dependent. */ void UpdatePageBorders (void); void UpdatePreciousFlags (void); }; } } } // end of namespace ::sd::slidesorter::view #endif <|endoftext|>
<commit_before>/** * @file Cognition.cpp * * @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a> * Implementation of the class Cognition */ #include "Cognition.h" #include "Tools/Debug/DebugDrawings3D.h" ///////////////////////////////////// // Modules ///////////////////////////////////// // Infrastructure #include "Modules/Infrastructure/IO/Sensor.h" #include "Modules/Infrastructure/IO/Actuator.h" #include "Modules/Infrastructure/LEDSetter/LEDSetter.h" #include "Modules/Infrastructure/Debug/Debug.h" #include "Modules/Infrastructure/Debug/DebugExecutor.h" #include "Modules/Infrastructure/Debug/StopwatchSender.h" #include "Modules/Infrastructure/Debug/RoboViz.h" #include "Modules/Infrastructure/Debug/CameraDebug.h" #include "Modules/Infrastructure/Debug/FrameRateCheck.h" #include "Modules/Infrastructure/TeamCommunicator/TeamCommSender.h" #include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiver.h" #include "Modules/Infrastructure/TeamCommunicator/RCTCHandler.h" #include "Modules/Infrastructure/GameController/GameController.h" #include "Modules/Infrastructure/OpenCV/OpenCVImageProvider.h" #include "Modules/Infrastructure/BatteryAlert/BatteryAlert.h" #include "Modules/Infrastructure/Camera/CameraInfoSetter.h" // Perception #include "Modules/Perception/CameraMatrixCorrector/CameraMatrixCorrector.h" #include "Modules/Perception/KinematicChainProvider/KinematicChainProvider.h" #include "Modules/Perception/VisualCortex/ImageCorrector.h" #include "Modules/Perception/VisualCortex/BaseColorClassifier.h" #include "Modules/Perception/VisualCortex/FieldColorClassifier.h" #include "Modules/Perception/VisualCortex/ColorProvider.h" #include "Modules/Perception/VisualCortex/GridProvider.h" #include "Modules/Perception/VisualCortex/ImageProcessor.h" #include "Modules/Perception/VirtualVisionProcessor/VirtualVisionProcessor.h" #include "Modules/Perception/PerceptProjector/PerceptProjector.h" #include "Modules/Perception/PerceptionsVisualization/PerceptionsVisualization.h" #include "Modules/Perception/OpenCV/FieldSideDetector.h" #include "Modules/Perception/OpenCV/OpenCVDebug.h" #include "Modules/Perception/ArtificialHorizonCalculator/ArtificialHorizonCalculator.h" // Modeling #include "Modules/Modeling/BodyStateProvider/BodyStateProvider.h" #include "Modules/Modeling/BallLocator/ParticleFilterBallLocator/ParticleFilterBallLocator.h" #include "Modules/Modeling/BallLocator/KalmanFilterBallLocator/KalmanFilterBallLocator.h" #include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocator.h" #include "Modules/Modeling/GoalLocator/ActiveGoalLocator/ActiveGoalLocator.h" #include "Modules/Modeling/GoalLocator/WholeGoalLocator/WholeGoalLocator.h" #include "Modules/Modeling/GoalLocator/DummyActiveGoalLocator/DummyActiveGoalLocator.h" #include "Modules/Modeling/SelfLocator/GPS_SelfLocator/GPS_SelfLocator.h" #include "Modules/Modeling/SelfLocator/OdometrySelfLocator/OdometrySelfLocator.h" #include "Modules/Modeling/ObstacleLocator/UltraSoundObstacleLocator.h" #include "Modules/Modeling/ObstacleLocator/VisualObstacleLocator.h" #include "Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h" #include "Modules/Modeling/FieldCompass/FieldCompass.h" #include "Modules/Modeling/SoccerStrategyProvider/SoccerStrategyProvider.h" #include "Modules/Modeling/PlayersLocator/PlayersLocator.h" #include "Modules/Modeling/PotentialFieldProvider/PotentialFieldProvider.h" #include "Modules/Modeling/AttentionAnalyzer/AttentionAnalyzer.h" #include "Modules/Modeling/PathPlanner/PathPlanner.h" #include "Modules/Modeling/CollisionDetector/CollisionDetector.h" // Behavior #include "Modules/BehaviorControl/SensorBehaviorControl/SensorBehaviorControl.h" #include "Modules/BehaviorControl/SimpleMotionBehaviorControl/SimpleMotionBehaviorControl.h" #include "Modules/BehaviorControl/XABSLBehaviorControl2011/XABSLBehaviorControl2011.h" #include "Modules/BehaviorControl/XABSLBehaviorControl/XABSLBehaviorControl.h" #include "Modules/BehaviorControl/CalibrationBehaviorControl/CalibrationBehaviorControl.h" // Experiment #include "Modules/Experiment/Evolution/Evolution.h" //#include "Modules/Experiment/VisualAttention/SaliencyMap/SaliencyMapProvider.h" // tools using namespace std; Cognition::Cognition() : ModuleManagerWithDebug("Cognition") { } Cognition::~Cognition() { } #define REGISTER_MODULE(module) \ g_message("Register "#module);\ registerModule<module>(std::string(#module)); void Cognition::init(naoth::ProcessInterface& platformInterface, const naoth::PlatformBase& platform) { g_message("Cognition register start"); // register of the modules // input module ModuleCreator<Sensor>* sensor = registerModule<Sensor>(std::string("Sensor"), true); sensor->getModuleT()->init(platformInterface, platform); /* * to register a module use * REGISTER_MODULE(ModuleClassName); * * Remark: to enable the module don't forget * to set the value in modules.cfg */ // -- BEGIN MODULES -- // infrastructure REGISTER_MODULE(RCTCHandler); REGISTER_MODULE(TeamCommReceiver); REGISTER_MODULE(GameController); REGISTER_MODULE(OpenCVImageProvider); REGISTER_MODULE(BatteryAlert); REGISTER_MODULE(CameraInfoSetter); // perception REGISTER_MODULE(CameraMatrixCorrector); REGISTER_MODULE(KinematicChainProvider); REGISTER_MODULE(ArtificialHorizonCalculator); REGISTER_MODULE(ImageCorrector); REGISTER_MODULE(FieldColorClassifier); REGISTER_MODULE(BaseColorClassifier); REGISTER_MODULE(ColorProvider); REGISTER_MODULE(GridProvider); REGISTER_MODULE(ImageProcessor); REGISTER_MODULE(VirtualVisionProcessor); REGISTER_MODULE(FieldSideDetector); REGISTER_MODULE(OpenCVDebug); // scene analysers // (analyze the visual information seen in the image) REGISTER_MODULE(WholeGoalLocator); REGISTER_MODULE(PerceptProjector); REGISTER_MODULE(PerceptionsVisualization); // modeling REGISTER_MODULE(BodyStateProvider); REGISTER_MODULE(ParticleFilterBallLocator); REGISTER_MODULE(KalmanFilterBallLocator); REGISTER_MODULE(ActiveGoalLocator); REGISTER_MODULE(GPS_SelfLocator); REGISTER_MODULE(OdometrySelfLocator); REGISTER_MODULE(UltraSoundObstacleLocator); REGISTER_MODULE(VisualObstacleLocator); REGISTER_MODULE(MonteCarloSelfLocator); REGISTER_MODULE(DummyActiveGoalLocator); // has to be after MonteCarloSelfLocator REGISTER_MODULE(FieldCompass); REGISTER_MODULE(TeamBallLocator); REGISTER_MODULE(PlayersLocator); REGISTER_MODULE(PotentialFieldProvider); REGISTER_MODULE(AttentionAnalyzer); REGISTER_MODULE(SoccerStrategyProvider); REGISTER_MODULE(PathPlanner); REGISTER_MODULE(CollisionDetector) // behavior REGISTER_MODULE(SensorBehaviorControl); REGISTER_MODULE(SimpleMotionBehaviorControl); REGISTER_MODULE(CalibrationBehaviorControl); REGISTER_MODULE(XABSLBehaviorControl2011); REGISTER_MODULE(XABSLBehaviorControl); // experiment REGISTER_MODULE(Evolution); //REGISTER_MODULE(SaliencyMapProvider); // infrastructure REGISTER_MODULE(TeamCommSender); // debug REGISTER_MODULE(FrameRateCheck); REGISTER_MODULE(LEDSetter); REGISTER_MODULE(Debug); REGISTER_MODULE(RoboViz); REGISTER_MODULE(StopwatchSender); REGISTER_MODULE(DebugExecutor); REGISTER_MODULE(CameraDebug); // -- END MODULES -- // output module ModuleCreator<Actuator>* actuator = registerModule<Actuator>(std::string("Actuator"), true); actuator->getModuleT()->init(platformInterface, platform); // loat external modules //packageLoader.loadPackages("Packages/", *this); // use the configuration in order to set whether a module is activated or not const naoth::Configuration& config = Platform::getInstance().theConfiguration; list<string>::const_iterator name = getExecutionList().begin(); for(;name != getExecutionList().end(); ++name) { bool active = false; if(config.hasKey("modules", *name)) { active = config.getBool("modules", *name); } setModuleEnabled(*name, active); if(active) { g_message("activating module %s", (*name).c_str()); } }//end for // auto-generate the execution list //calculateExecutionList(); g_message("Cognition register end"); stopwatch.start(); }//end init void Cognition::call() { // BEGIN cognition frame rate measuring stopwatch.stop(); stopwatch.start(); PLOT("_CognitionCycle", stopwatch.lastValue); // END cognition frame rate measuring STOPWATCH_START("CognitionExecute"); //GT_TRACE("beginning to iterate over all modules"); // execute all modules list<AbstractModuleCreator*>::const_iterator iter; for (iter = getModuleExecutionList().begin(); iter != getModuleExecutionList().end(); ++iter) { // get entry AbstractModuleCreator* module = *iter;//getModule(*iter); if (module != NULL && module->isEnabled()) { //std::string name(module->getModule()->getName()); //GT_TRACE("executing " << name); module->execute(); }//end if }//end for all modules //GT_TRACE("end module iteration"); STOPWATCH_STOP("CognitionExecute"); // HACK: reset all the debug stuff before executing the modules STOPWATCH_START("Debug ~ Init"); DebugBufferedOutput::getInstance().update(); DebugDrawings::getInstance().update(); DebugImageDrawings::getInstance().reset(); DebugDrawings3D::getInstance().update(); STOPWATCH_STOP("Debug ~ Init"); }//end call <commit_msg>bugfix: macros should require semicolons<commit_after>/** * @file Cognition.cpp * * @author <a href="mailto:mellmann@informatik.hu-berlin.de">Heinrich Mellmann</a> * Implementation of the class Cognition */ #include "Cognition.h" #include "Tools/Debug/DebugDrawings3D.h" ///////////////////////////////////// // Modules ///////////////////////////////////// // Infrastructure #include "Modules/Infrastructure/IO/Sensor.h" #include "Modules/Infrastructure/IO/Actuator.h" #include "Modules/Infrastructure/LEDSetter/LEDSetter.h" #include "Modules/Infrastructure/Debug/Debug.h" #include "Modules/Infrastructure/Debug/DebugExecutor.h" #include "Modules/Infrastructure/Debug/StopwatchSender.h" #include "Modules/Infrastructure/Debug/RoboViz.h" #include "Modules/Infrastructure/Debug/CameraDebug.h" #include "Modules/Infrastructure/Debug/FrameRateCheck.h" #include "Modules/Infrastructure/TeamCommunicator/TeamCommSender.h" #include "Modules/Infrastructure/TeamCommunicator/TeamCommReceiver.h" #include "Modules/Infrastructure/TeamCommunicator/RCTCHandler.h" #include "Modules/Infrastructure/GameController/GameController.h" #include "Modules/Infrastructure/OpenCV/OpenCVImageProvider.h" #include "Modules/Infrastructure/BatteryAlert/BatteryAlert.h" #include "Modules/Infrastructure/Camera/CameraInfoSetter.h" // Perception #include "Modules/Perception/CameraMatrixCorrector/CameraMatrixCorrector.h" #include "Modules/Perception/KinematicChainProvider/KinematicChainProvider.h" #include "Modules/Perception/VisualCortex/ImageCorrector.h" #include "Modules/Perception/VisualCortex/BaseColorClassifier.h" #include "Modules/Perception/VisualCortex/FieldColorClassifier.h" #include "Modules/Perception/VisualCortex/ColorProvider.h" #include "Modules/Perception/VisualCortex/GridProvider.h" #include "Modules/Perception/VisualCortex/ImageProcessor.h" #include "Modules/Perception/VirtualVisionProcessor/VirtualVisionProcessor.h" #include "Modules/Perception/PerceptProjector/PerceptProjector.h" #include "Modules/Perception/PerceptionsVisualization/PerceptionsVisualization.h" #include "Modules/Perception/OpenCV/FieldSideDetector.h" #include "Modules/Perception/OpenCV/OpenCVDebug.h" #include "Modules/Perception/ArtificialHorizonCalculator/ArtificialHorizonCalculator.h" // Modeling #include "Modules/Modeling/BodyStateProvider/BodyStateProvider.h" #include "Modules/Modeling/BallLocator/ParticleFilterBallLocator/ParticleFilterBallLocator.h" #include "Modules/Modeling/BallLocator/KalmanFilterBallLocator/KalmanFilterBallLocator.h" #include "Modules/Modeling/BallLocator/TeamBallLocator/TeamBallLocator.h" #include "Modules/Modeling/GoalLocator/ActiveGoalLocator/ActiveGoalLocator.h" #include "Modules/Modeling/GoalLocator/WholeGoalLocator/WholeGoalLocator.h" #include "Modules/Modeling/GoalLocator/DummyActiveGoalLocator/DummyActiveGoalLocator.h" #include "Modules/Modeling/SelfLocator/GPS_SelfLocator/GPS_SelfLocator.h" #include "Modules/Modeling/SelfLocator/OdometrySelfLocator/OdometrySelfLocator.h" #include "Modules/Modeling/ObstacleLocator/UltraSoundObstacleLocator.h" #include "Modules/Modeling/ObstacleLocator/VisualObstacleLocator.h" #include "Modules/Modeling/SelfLocator/MonteCarloSelfLocator/MonteCarloSelfLocator.h" #include "Modules/Modeling/FieldCompass/FieldCompass.h" #include "Modules/Modeling/SoccerStrategyProvider/SoccerStrategyProvider.h" #include "Modules/Modeling/PlayersLocator/PlayersLocator.h" #include "Modules/Modeling/PotentialFieldProvider/PotentialFieldProvider.h" #include "Modules/Modeling/AttentionAnalyzer/AttentionAnalyzer.h" #include "Modules/Modeling/PathPlanner/PathPlanner.h" #include "Modules/Modeling/CollisionDetector/CollisionDetector.h" // Behavior #include "Modules/BehaviorControl/SensorBehaviorControl/SensorBehaviorControl.h" #include "Modules/BehaviorControl/SimpleMotionBehaviorControl/SimpleMotionBehaviorControl.h" #include "Modules/BehaviorControl/XABSLBehaviorControl2011/XABSLBehaviorControl2011.h" #include "Modules/BehaviorControl/XABSLBehaviorControl/XABSLBehaviorControl.h" #include "Modules/BehaviorControl/CalibrationBehaviorControl/CalibrationBehaviorControl.h" // Experiment #include "Modules/Experiment/Evolution/Evolution.h" //#include "Modules/Experiment/VisualAttention/SaliencyMap/SaliencyMapProvider.h" // tools using namespace std; Cognition::Cognition() : ModuleManagerWithDebug("Cognition") { } Cognition::~Cognition() { } #define REGISTER_MODULE(module) \ g_message("Register "#module);\ registerModule<module>(std::string(#module)) void Cognition::init(naoth::ProcessInterface& platformInterface, const naoth::PlatformBase& platform) { g_message("Cognition register start"); // register of the modules // input module ModuleCreator<Sensor>* sensor = registerModule<Sensor>(std::string("Sensor"), true); sensor->getModuleT()->init(platformInterface, platform); /* * to register a module use * REGISTER_MODULE(ModuleClassName); * * Remark: to enable the module don't forget * to set the value in modules.cfg */ // -- BEGIN MODULES -- // infrastructure REGISTER_MODULE(RCTCHandler); REGISTER_MODULE(TeamCommReceiver); REGISTER_MODULE(GameController); REGISTER_MODULE(OpenCVImageProvider); REGISTER_MODULE(BatteryAlert); REGISTER_MODULE(CameraInfoSetter); // perception REGISTER_MODULE(CameraMatrixCorrector); REGISTER_MODULE(KinematicChainProvider); REGISTER_MODULE(ArtificialHorizonCalculator); REGISTER_MODULE(ImageCorrector); REGISTER_MODULE(FieldColorClassifier); REGISTER_MODULE(BaseColorClassifier); REGISTER_MODULE(ColorProvider); REGISTER_MODULE(GridProvider); REGISTER_MODULE(ImageProcessor); REGISTER_MODULE(VirtualVisionProcessor); REGISTER_MODULE(FieldSideDetector); REGISTER_MODULE(OpenCVDebug); // scene analysers // (analyze the visual information seen in the image) REGISTER_MODULE(WholeGoalLocator); REGISTER_MODULE(PerceptProjector); REGISTER_MODULE(PerceptionsVisualization); // modeling REGISTER_MODULE(BodyStateProvider); REGISTER_MODULE(ParticleFilterBallLocator); REGISTER_MODULE(KalmanFilterBallLocator); REGISTER_MODULE(ActiveGoalLocator); REGISTER_MODULE(GPS_SelfLocator); REGISTER_MODULE(OdometrySelfLocator); REGISTER_MODULE(UltraSoundObstacleLocator); REGISTER_MODULE(VisualObstacleLocator); REGISTER_MODULE(MonteCarloSelfLocator); REGISTER_MODULE(DummyActiveGoalLocator); // has to be after MonteCarloSelfLocator REGISTER_MODULE(FieldCompass); REGISTER_MODULE(TeamBallLocator); REGISTER_MODULE(PlayersLocator); REGISTER_MODULE(PotentialFieldProvider); REGISTER_MODULE(AttentionAnalyzer); REGISTER_MODULE(SoccerStrategyProvider); REGISTER_MODULE(PathPlanner); REGISTER_MODULE(CollisionDetector); // behavior REGISTER_MODULE(SensorBehaviorControl); REGISTER_MODULE(SimpleMotionBehaviorControl); REGISTER_MODULE(CalibrationBehaviorControl); REGISTER_MODULE(XABSLBehaviorControl2011); REGISTER_MODULE(XABSLBehaviorControl); // experiment REGISTER_MODULE(Evolution); //REGISTER_MODULE(SaliencyMapProvider); // infrastructure REGISTER_MODULE(TeamCommSender); // debug REGISTER_MODULE(FrameRateCheck); REGISTER_MODULE(LEDSetter); REGISTER_MODULE(Debug); REGISTER_MODULE(RoboViz); REGISTER_MODULE(StopwatchSender); REGISTER_MODULE(DebugExecutor); REGISTER_MODULE(CameraDebug); // -- END MODULES -- // output module ModuleCreator<Actuator>* actuator = registerModule<Actuator>(std::string("Actuator"), true); actuator->getModuleT()->init(platformInterface, platform); // loat external modules //packageLoader.loadPackages("Packages/", *this); // use the configuration in order to set whether a module is activated or not const naoth::Configuration& config = Platform::getInstance().theConfiguration; list<string>::const_iterator name = getExecutionList().begin(); for(;name != getExecutionList().end(); ++name) { bool active = false; if(config.hasKey("modules", *name)) { active = config.getBool("modules", *name); } setModuleEnabled(*name, active); if(active) { g_message("activating module %s", (*name).c_str()); } }//end for // auto-generate the execution list //calculateExecutionList(); g_message("Cognition register end"); stopwatch.start(); }//end init void Cognition::call() { // BEGIN cognition frame rate measuring stopwatch.stop(); stopwatch.start(); PLOT("_CognitionCycle", stopwatch.lastValue); // END cognition frame rate measuring STOPWATCH_START("CognitionExecute"); //GT_TRACE("beginning to iterate over all modules"); // execute all modules list<AbstractModuleCreator*>::const_iterator iter; for (iter = getModuleExecutionList().begin(); iter != getModuleExecutionList().end(); ++iter) { // get entry AbstractModuleCreator* module = *iter;//getModule(*iter); if (module != NULL && module->isEnabled()) { //std::string name(module->getModule()->getName()); //GT_TRACE("executing " << name); module->execute(); }//end if }//end for all modules //GT_TRACE("end module iteration"); STOPWATCH_STOP("CognitionExecute"); // HACK: reset all the debug stuff before executing the modules STOPWATCH_START("Debug ~ Init"); DebugBufferedOutput::getInstance().update(); DebugDrawings::getInstance().update(); DebugImageDrawings::getInstance().reset(); DebugDrawings3D::getInstance().update(); STOPWATCH_STOP("Debug ~ Init"); }//end call <|endoftext|>
<commit_before>#include "StdAfx.h" #include "Controller.h" #include "ControllerManager.h" #include "ControllerFilters.h" #include "ObstacleContext.h" #include "RigidDynamic.h" #include "Shape.h" #include "ControllerState.h" #include "ControllerStats.h" using namespace System::Linq; Controller::Controller(PxController* controller, PhysX::ControllerManager^ owner) { ThrowIfNull(controller, "controller"); ThrowIfNullOrDisposed(owner, "owner"); _controller = controller; _controllerManager = owner; ObjectTable::Add((intptr_t)controller, this, owner); // The Actor class holds the PxActor, but should not dispose of it, as it is owned entirely // by the PxController instance PxRigidDynamic* actor = controller->getActor(); _actor = gcnew PhysX::RigidDynamic(actor, nullptr); _actor->UnmanagedOwner = false; // The Shape class holds the PxShape, but should not dispose of it, as it is owned entirely // by the PxActor of the PxController instance _shape = _actor->GetShape(0); _shape->UnmanagedOwner = false; } Controller::~Controller() { this->!Controller(); } Controller::!Controller() { OnDisposing(this, nullptr); if (this->Disposed) return; _controller->release(); _controller = NULL; UserData = nullptr; OnDisposed(this, nullptr); } bool Controller::Disposed::get() { return (_controller == NULL); } ControllerCollisionFlag Controller::Move(Vector3 displacement, TimeSpan elapsedTime) { auto filter = gcnew ControllerFilters(); filter->ActiveGroups = 0xFFFFFFFF; filter->FilterFlags = QueryFlag::Static | QueryFlag::Dynamic; return Move(displacement, elapsedTime, 0.001f, filter, nullptr); } ControllerCollisionFlag Controller::Move(Vector3 displacement, TimeSpan elapsedTime, float minimumDistance, ControllerFilters^ filters, [Optional] ObstacleContext^ obstacles) { auto disp = MathUtil::Vector3ToPxVec3(displacement); auto et = (float)elapsedTime.TotalSeconds; auto f = ControllerFilters::ToUnmanaged(filters); auto oc = (obstacles == nullptr ? NULL : obstacles->UnmanagedPointer); PxU32 returnFlags = _controller->move(disp, minimumDistance, et, f, oc); // TODO: Not the cleanest way of cleaning up the memory that ControllerFilter allocates if (f.mFilterData != NULL) { delete f.mFilterData; } return (ControllerCollisionFlag)returnFlags; } ControllerState^ Controller::GetState() { PxControllerState state; _controller->getState(state); return ControllerState::ToManaged(state); } void Controller::InvalidateCache() { _controller->invalidateCache(); } ControllerStats Controller::GetStats() { PxControllerStats s; _controller->getStats(s); return ControllerStats::ToManaged(s); } void Controller::Resize(float height) { _controller->resize(height); } PhysX::ControllerManager^ Controller::ControllerManager::get() { return _controllerManager; } PhysX::RigidDynamic^ Controller::Actor::get() { return _actor; } PhysX::Shape^ Controller::Shape::get() { return _shape; } Vector3 Controller::Position::get() { PxExtendedVec3 p = _controller->getPosition(); return MathUtil::PxExtendedVec3ToVector3(p); } void Controller::Position::set(Vector3 value) { PxExtendedVec3 p = MathUtil::Vector3ToPxExtendedVec3(value); _controller->setPosition(p); } Vector3 Controller::FootPosition::get() { PxExtendedVec3 p = _controller->getFootPosition(); return MathUtil::PxExtendedVec3ToVector3(p); } void Controller::FootPosition::set(Vector3 value) { PxExtendedVec3 p = MathUtil::Vector3ToPxExtendedVec3(value); _controller->setFootPosition(p); } float Controller::StepOffset::get() { return _controller->getStepOffset(); } void Controller::StepOffset::set(float value) { _controller->setStepOffset(value); } ControllerNonWalkableMode Controller::NonWalkableMode::get() { return ToManagedEnum(ControllerNonWalkableMode, _controller->getNonWalkableMode()); } void Controller::NonWalkableMode::set(ControllerNonWalkableMode value) { _controller->setNonWalkableMode(ToUnmanagedEnum(PxControllerNonWalkableMode, value)); } //CCTInteractionMode Controller::Interaction::get() //{ // return ToManagedEnum(CCTInteractionMode, _controller->getInteraction()); //} //void Controller::Interaction::set(CCTInteractionMode value) //{ // _controller->setInteraction(ToUnmanagedEnum(PxCCTInteractionMode, value)); //} float Controller::ContactOffset::get() { return _controller->getContactOffset(); } Vector3 Controller::UpDirection::get() { return MathUtil::PxVec3ToVector3(_controller->getUpDirection()); } void Controller::UpDirection::set(Vector3 value) { _controller->setUpDirection(MathUtil::Vector3ToPxVec3(value)); } float Controller::SlopeLimit::get() { return _controller->getSlopeLimit(); } void Controller::SlopeLimit::set(float value) { _controller->setSlopeLimit(value); } ControllerShapeType Controller::Type::get() { return ToManagedEnum(ControllerShapeType, _controller->getType()); } PxController* Controller::UnmanagedPointer::get() { return _controller; }<commit_msg>Clean<commit_after>#include "StdAfx.h" #include "Controller.h" #include "ControllerManager.h" #include "ControllerFilters.h" #include "ObstacleContext.h" #include "RigidDynamic.h" #include "Shape.h" #include "ControllerState.h" #include "ControllerStats.h" using namespace System::Linq; Controller::Controller(PxController* controller, PhysX::ControllerManager^ owner) { ThrowIfNull(controller, "controller"); ThrowIfNullOrDisposed(owner, "owner"); _controller = controller; _controllerManager = owner; ObjectTable::Add((intptr_t)controller, this, owner); // The Actor class holds the PxActor, but should not dispose of it, as it is owned entirely // by the PxController instance PxRigidDynamic* actor = controller->getActor(); _actor = gcnew PhysX::RigidDynamic(actor, nullptr); _actor->UnmanagedOwner = false; // The Shape class holds the PxShape, but should not dispose of it, as it is owned entirely // by the PxActor of the PxController instance _shape = _actor->GetShape(0); _shape->UnmanagedOwner = false; } Controller::~Controller() { this->!Controller(); } Controller::!Controller() { OnDisposing(this, nullptr); if (this->Disposed) return; _controller->release(); _controller = NULL; UserData = nullptr; OnDisposed(this, nullptr); } bool Controller::Disposed::get() { return (_controller == NULL); } ControllerCollisionFlag Controller::Move(Vector3 displacement, TimeSpan elapsedTime) { auto filter = gcnew ControllerFilters(); filter->ActiveGroups = 0xFFFFFFFF; filter->FilterFlags = QueryFlag::Static | QueryFlag::Dynamic; return Move(displacement, elapsedTime, 0.001f, filter, nullptr); } ControllerCollisionFlag Controller::Move(Vector3 displacement, TimeSpan elapsedTime, float minimumDistance, ControllerFilters^ filters, [Optional] ObstacleContext^ obstacles) { auto disp = MathUtil::Vector3ToPxVec3(displacement); auto et = (float)elapsedTime.TotalSeconds; auto f = ControllerFilters::ToUnmanaged(filters); auto oc = (obstacles == nullptr ? NULL : obstacles->UnmanagedPointer); PxU32 returnFlags = _controller->move(disp, minimumDistance, et, f, oc); // TODO: Not the cleanest way of cleaning up the memory that ControllerFilter allocates if (f.mFilterData != NULL) { delete f.mFilterData; } return (ControllerCollisionFlag)returnFlags; } ControllerState^ Controller::GetState() { PxControllerState state; _controller->getState(state); return ControllerState::ToManaged(state); } void Controller::InvalidateCache() { _controller->invalidateCache(); } ControllerStats Controller::GetStats() { PxControllerStats s; _controller->getStats(s); return ControllerStats::ToManaged(s); } void Controller::Resize(float height) { _controller->resize(height); } PhysX::ControllerManager^ Controller::ControllerManager::get() { return _controllerManager; } PhysX::RigidDynamic^ Controller::Actor::get() { return _actor; } PhysX::Shape^ Controller::Shape::get() { return _shape; } Vector3 Controller::Position::get() { return MathUtil::PxExtendedVec3ToVector3(_controller->getPosition()); } void Controller::Position::set(Vector3 value) { _controller->setPosition(MathUtil::Vector3ToPxExtendedVec3(value)); } Vector3 Controller::FootPosition::get() { PxExtendedVec3 p = _controller->getFootPosition(); return MathUtil::PxExtendedVec3ToVector3(p); } void Controller::FootPosition::set(Vector3 value) { PxExtendedVec3 p = MathUtil::Vector3ToPxExtendedVec3(value); _controller->setFootPosition(p); } float Controller::StepOffset::get() { return _controller->getStepOffset(); } void Controller::StepOffset::set(float value) { _controller->setStepOffset(value); } ControllerNonWalkableMode Controller::NonWalkableMode::get() { return ToManagedEnum(ControllerNonWalkableMode, _controller->getNonWalkableMode()); } void Controller::NonWalkableMode::set(ControllerNonWalkableMode value) { _controller->setNonWalkableMode(ToUnmanagedEnum(PxControllerNonWalkableMode, value)); } //CCTInteractionMode Controller::Interaction::get() //{ // return ToManagedEnum(CCTInteractionMode, _controller->getInteraction()); //} //void Controller::Interaction::set(CCTInteractionMode value) //{ // _controller->setInteraction(ToUnmanagedEnum(PxCCTInteractionMode, value)); //} float Controller::ContactOffset::get() { return _controller->getContactOffset(); } Vector3 Controller::UpDirection::get() { return MathUtil::PxVec3ToVector3(_controller->getUpDirection()); } void Controller::UpDirection::set(Vector3 value) { _controller->setUpDirection(MathUtil::Vector3ToPxVec3(value)); } float Controller::SlopeLimit::get() { return _controller->getSlopeLimit(); } void Controller::SlopeLimit::set(float value) { _controller->setSlopeLimit(value); } ControllerShapeType Controller::Type::get() { return ToManagedEnum(ControllerShapeType, _controller->getType()); } PxController* Controller::UnmanagedPointer::get() { return _controller; }<|endoftext|>
<commit_before>// run in subdir as // root -b -q -l ../../../../lydia/workspace-run2-ggf.root '../time_higgs_lydia.C(1,1)' using namespace RooFit; // only used for dataset Lydia 2: using namespace RooStats; using namespace HistFactory; const char* project_dir = "/Users/pbos/projects/apcocsm"; const char* run_subdir = "code/profiling/numIntSet_timing/run_time_higgs_lydia1"; void time_higgs_lydia(int dataset, int num_cpu, int debug=0, int parallel_interleave=0, int seed=1, int print_level=0) { gSystem->ChangeDirectory(project_dir); TFile *_file0; const char* workspace_name; const char* obsdata_name; bool set_muGGF; bool perturb_parameters_randomly; // load dataset file and settings switch (dataset) { case 1: { _file0 = TFile::Open("lydia/workspace-run2-ggf.root"); workspace_name = "Run2GGF"; obsdata_name = "asimovData"; set_muGGF = true; perturb_parameters_randomly = true; break; } case 2: { std::cout << "WARNING: this dataset only works with HiggsComb ROOT (on stoomboot: lsetup \"root 5.34.32-HiggsComb-x86_64-slc6-gcc48-opt\")" << std::endl; _file0 = TFile::Open("lydia/9channel_20150304_incl_tH_couplings_7TeV_8TeV_test_full_fixed_theory_asimov_7TeV_8TeV_THDMII.root"); workspace_name = "combined"; obsdata_name = "combData"; set_muGGF = false; perturb_parameters_randomly = false; break; } } gSystem->ChangeDirectory(run_subdir); gRandom->SetSeed(seed); // activate debugging output if (debug == 1) { RooMsgService::instance().addStream(DEBUG); // all DEBUG messages // RooMsgService::instance().addStream(DEBUG, Topic(RooFit::Eval), ClassName("RooAbsTestStatistic")); } // TStopwatch t; // t.Start(); RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get(workspace_name)); RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj("ModelConfig")); // Activate binned likelihood calculation for binned models if (1) { RooFIter iter = w->components().fwdIterator(); RooAbsArg* arg; while((arg=iter.next())) { if (arg->IsA()==RooRealSumPdf::Class()) { arg->setAttribute("BinnedLikelihood"); cout << "component " << arg->GetName() << " is a binned likelihood" << endl; } if (arg->IsA()==RooAddPdf::Class() && TString(arg->GetName()).BeginsWith("pdf_")) { arg->setAttribute("MAIN_MEASUREMENT"); cout << "component " << arg->GetName() << " is a cms main measurement" << endl; } } } if (set_muGGF) { w->var("muGGF")->setVal(3); } //w->loadSnapshot("NominalParamValues"); RooAbsData* obsData = w->data(obsdata_name); RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()); if (perturb_parameters_randomly) { // NOT REALLY NECESSARY FOR TESTING, IT MAKES THE FIT A BIT HARDER RooArgSet* params = static_cast<RooArgSet*>(pdf->getParameters(obsData)->selectByAttrib("Constant",kFALSE)); RooFIter iter = params->fwdIterator(); RooAbsRealLValue* arg; while ((arg=(RooAbsRealLValue*)iter.next())) { arg->setVal(arg->getVal()+gRandom->Gaus(0,0.3)); } } // activate debugging output if (debug == 2) { RooMsgService::instance().addStream(DEBUG); // all DEBUG messages // RooMsgService::instance().addStream(DEBUG, Topic(RooFit::Eval), ClassName("RooAbsTestStatistic")); } RooMsgService::instance().addStream(DEBUG, Topic(RooFit::Generation), ClassName("RooRealMPFE")); RooAbsReal* nll = pdf->createNLL(*obsData, Constrain(*w->set("ModelConfig_NuisParams")), GlobalObservables(*w->set("ModelConfig_GlobalObservables")), Offset(kTRUE), NumCPU(num_cpu, parallel_interleave) ); RooMinimizer m(*nll); m.setVerbose(print_level); m.setStrategy(0); // this sets the minuit strategy to optimal for "fast functions" (2 is for slow, 1 for intermediate) // m.setProfile(1); // this is for activating profiling of the minimizer m.optimizeConst(2); std::cout << "\n\n\n\nSTART MINIMIZE\n\n\n\n" << std::endl; m.minimize("Minuit2","migrad"); } <commit_msg>Made project_dir var dependent on host<commit_after>// run in subdir as // root -b -q -l ../../../../lydia/workspace-run2-ggf.root '../time_higgs_lydia.C(1,1)' using namespace RooFit; // only used for dataset Lydia 2: using namespace RooStats; using namespace HistFactory; const char* run_subdir = "code/profiling/numIntSet_timing/run_time_higgs_lydia1"; void time_higgs_lydia(int dataset, int num_cpu, std::string host="eslt0072", int debug=0, int parallel_interleave=0, int seed=1, int print_level=0) { const char* project_dir; if (host == "eslt0072") { project_dir="/Users/pbos/projects/apcocsm"; } else if (host == "stbc") { project_dir="/user/pbos/project_atlas"; } gSystem->ChangeDirectory(project_dir); TFile *_file0; const char* workspace_name; const char* obsdata_name; bool set_muGGF; bool perturb_parameters_randomly; // load dataset file and settings switch (dataset) { case 1: { _file0 = TFile::Open("lydia/workspace-run2-ggf.root"); workspace_name = "Run2GGF"; obsdata_name = "asimovData"; set_muGGF = true; perturb_parameters_randomly = true; break; } case 2: { std::cout << "WARNING: this dataset only works with HiggsComb ROOT (on stoomboot: lsetup \"root 5.34.32-HiggsComb-x86_64-slc6-gcc48-opt\")" << std::endl; _file0 = TFile::Open("lydia/9channel_20150304_incl_tH_couplings_7TeV_8TeV_test_full_fixed_theory_asimov_7TeV_8TeV_THDMII.root"); workspace_name = "combined"; obsdata_name = "combData"; set_muGGF = false; perturb_parameters_randomly = false; break; } } gSystem->ChangeDirectory(run_subdir); gRandom->SetSeed(seed); // activate debugging output if (debug == 1) { RooMsgService::instance().addStream(DEBUG); // all DEBUG messages // RooMsgService::instance().addStream(DEBUG, Topic(RooFit::Eval), ClassName("RooAbsTestStatistic")); } // TStopwatch t; // t.Start(); RooWorkspace* w = static_cast<RooWorkspace*>(gDirectory->Get(workspace_name)); RooStats::ModelConfig* mc = static_cast<RooStats::ModelConfig*>(w->genobj("ModelConfig")); // Activate binned likelihood calculation for binned models if (1) { RooFIter iter = w->components().fwdIterator(); RooAbsArg* arg; while((arg=iter.next())) { if (arg->IsA()==RooRealSumPdf::Class()) { arg->setAttribute("BinnedLikelihood"); cout << "component " << arg->GetName() << " is a binned likelihood" << endl; } if (arg->IsA()==RooAddPdf::Class() && TString(arg->GetName()).BeginsWith("pdf_")) { arg->setAttribute("MAIN_MEASUREMENT"); cout << "component " << arg->GetName() << " is a cms main measurement" << endl; } } } if (set_muGGF) { w->var("muGGF")->setVal(3); } //w->loadSnapshot("NominalParamValues"); RooAbsData* obsData = w->data(obsdata_name); RooAbsPdf* pdf = w->pdf(mc->GetPdf()->GetName()); if (perturb_parameters_randomly) { // NOT REALLY NECESSARY FOR TESTING, IT MAKES THE FIT A BIT HARDER RooArgSet* params = static_cast<RooArgSet*>(pdf->getParameters(obsData)->selectByAttrib("Constant",kFALSE)); RooFIter iter = params->fwdIterator(); RooAbsRealLValue* arg; while ((arg=(RooAbsRealLValue*)iter.next())) { arg->setVal(arg->getVal()+gRandom->Gaus(0,0.3)); } } // activate debugging output if (debug == 2) { RooMsgService::instance().addStream(DEBUG); // all DEBUG messages // RooMsgService::instance().addStream(DEBUG, Topic(RooFit::Eval), ClassName("RooAbsTestStatistic")); } RooMsgService::instance().addStream(DEBUG, Topic(RooFit::Generation), ClassName("RooRealMPFE")); RooAbsReal* nll = pdf->createNLL(*obsData, Constrain(*w->set("ModelConfig_NuisParams")), GlobalObservables(*w->set("ModelConfig_GlobalObservables")), Offset(kTRUE), NumCPU(num_cpu, parallel_interleave) ); RooMinimizer m(*nll); m.setVerbose(print_level); m.setStrategy(0); // this sets the minuit strategy to optimal for "fast functions" (2 is for slow, 1 for intermediate) // m.setProfile(1); // this is for activating profiling of the minimizer m.optimizeConst(2); std::cout << "\n\n\n\nSTART MINIMIZE\n\n\n\n" << std::endl; m.minimize("Minuit2","migrad"); } <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief R8C/M110AN, R8C/M120AN グループ・コンパレーターレジスタ定義 @n Copyright 2015 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "common/io_utils.hpp" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンパレーター制御レジスタ WCMPR */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// typedef io8<0x0180> wcmpr_io; struct wcmpr_t : public wcmpr_io { using wcmpr_io::operator =; using wcmpr_io::operator (); using wcmpr_io::operator |=; using wcmpr_io::operator &=; bit_t<wcmpr_io, 0> WCB1M0; bit_t<wcmpr_io, 3> WCB1OUT; bit_t<wcmpr_io, 4> WCB3M0; bit_t<wcmpr_io, 0> WCB3OUT; }; static wcmpr_t WCMPR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンパレーター B1 割り込み制御レジスタ WCB1INTR */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// typedef io8<0x0181> wcb1intr_io; struct wcb1intr_t : public wcb1intr_io { using wcb1intr_io::operator =; using wcb1intr_io::operator (); using wcb1intr_io::operator |=; using wcb1intr_io::operator &=; bits_t<wcb1intr_io, 0, 2> WCB1FL; bits_t<wcb1intr_io, 4, 2> WCB1S; bit_t<wcb1intr_io, 6> WCB1INTEN; bit_t<wcb1intr_io, 7> WCB1F; }; static wcb1intr_t WCB1INTR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンパレーター B3 割り込み制御レジスタ WCB3INTR */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// typedef io8<0x0182> wcb3intr_io; struct wcb3intr_t : public wcb3intr_io { using wcb3intr_io::operator =; using wcb3intr_io::operator (); using wcb3intr_io::operator |=; using wcb3intr_io::operator &=; bits_t<wcb3intr_io, 0, 2> WCB3FL; bits_t<wcb3intr_io, 4, 2> WCB3S; bit_t<wcb3intr_io, 6> WCB3INTEN; bit_t<wcb3intr_io, 7> WCB3F; }; static wcb3intr_t WCB3INTR; } <commit_msg>ビット位置間違い修正<commit_after>#pragma once //=====================================================================// /*! @file @brief R8C/M110AN, R8C/M120AN グループ・コンパレーターレジスタ定義 @n Copyright 2015 Kunihito Hiramatsu @author 平松邦仁 (hira@rvf-rc45.net) */ //=====================================================================// #include "common/io_utils.hpp" namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンパレーター制御レジスタ WCMPR */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// typedef io8<0x0180> wcmpr_io; struct wcmpr_t : public wcmpr_io { using wcmpr_io::operator =; using wcmpr_io::operator (); using wcmpr_io::operator |=; using wcmpr_io::operator &=; bit_t<wcmpr_io, 0> WCB1M0; bit_t<wcmpr_io, 3> WCB1OUT; bit_t<wcmpr_io, 4> WCB3M0; bit_t<wcmpr_io, 7> WCB3OUT; }; static wcmpr_t WCMPR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンパレーター B1 割り込み制御レジスタ WCB1INTR */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// typedef io8<0x0181> wcb1intr_io; struct wcb1intr_t : public wcb1intr_io { using wcb1intr_io::operator =; using wcb1intr_io::operator (); using wcb1intr_io::operator |=; using wcb1intr_io::operator &=; bits_t<wcb1intr_io, 0, 2> WCB1FL; bits_t<wcb1intr_io, 4, 2> WCB1S; bit_t<wcb1intr_io, 6> WCB1INTEN; bit_t<wcb1intr_io, 7> WCB1F; }; static wcb1intr_t WCB1INTR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンパレーター B3 割り込み制御レジスタ WCB3INTR */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// typedef io8<0x0182> wcb3intr_io; struct wcb3intr_t : public wcb3intr_io { using wcb3intr_io::operator =; using wcb3intr_io::operator (); using wcb3intr_io::operator |=; using wcb3intr_io::operator &=; bits_t<wcb3intr_io, 0, 2> WCB3FL; bits_t<wcb3intr_io, 4, 2> WCB3S; bit_t<wcb3intr_io, 6> WCB3INTEN; bit_t<wcb3intr_io, 7> WCB3F; }; static wcb3intr_t WCB3INTR; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: svgwriter.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2004-05-03 13:53:17 $ * * 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): _______________________________________ * * ************************************************************************/ #include "svgwriter.hxx" #include "svgaction.hxx" #include <uno/mapping.hxx> // ---------------- // - SVGMtfExport - // ---------------- class SVGMtfExport : public SvXMLExport { private: SVGMtfExport(); protected: virtual void _ExportMeta() {} virtual void _ExportStyles( BOOL bUsed ) {} virtual void _ExportAutoStyles() {} virtual void _ExportContent() {} virtual void _ExportMasterStyles() {} virtual ULONG exportDoc( enum ::xmloff::token::XMLTokenEnum eClass ) { return 0; } public: // #110680# SVGMtfExport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, const REF( NMSP_SAX::XDocumentHandler )& rxHandler ); virtual ~SVGMtfExport(); virtual void writeMtf( const GDIMetaFile& rMtf ); }; // ----------------------------------------------------------------------------- // #110680# SVGMtfExport::SVGMtfExport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, const REF( NMSP_SAX::XDocumentHandler )& rxHandler ) : SvXMLExport( xServiceFactory, NMSP_RTL::OUString(), rxHandler ) { GetDocHandler()->startDocument(); } // ----------------------------------------------------------------------------- SVGMtfExport::~SVGMtfExport() { GetDocHandler()->endDocument(); } // ----------------------------------------------------------------------------- void SVGMtfExport::writeMtf( const GDIMetaFile& rMtf ) { const Size aSize( OutputDevice::LogicToLogic( rMtf.GetPrefSize(), rMtf.GetPrefMapMode(), MAP_MM ) ); NMSP_RTL::OUString aAttr; REF( NMSP_SAX::XExtendedDocumentHandler ) xExtDocHandler( GetDocHandler(), NMSP_UNO::UNO_QUERY ); if( xExtDocHandler.is() ) xExtDocHandler->unknown( SVG_DTD_STRING ); aAttr = NMSP_RTL::OUString::valueOf( aSize.Width() ); aAttr += B2UCONST( "mm" ); AddAttribute( XML_NAMESPACE_NONE, "width", aAttr ); aAttr = NMSP_RTL::OUString::valueOf( aSize.Height() ); aAttr += B2UCONST( "mm" ); AddAttribute( XML_NAMESPACE_NONE, "height", aAttr ); aAttr = B2UCONST( "0 0 " ); aAttr += NMSP_RTL::OUString::valueOf( aSize.Width() * 100L ); aAttr += B2UCONST( " " ); aAttr += NMSP_RTL::OUString::valueOf( aSize.Height() * 100L ); AddAttribute( XML_NAMESPACE_NONE, "viewBox", aAttr ); { SvXMLElementExport aSVG( *this, XML_NAMESPACE_NONE, "svg", TRUE, TRUE ); SVGActionWriter* pWriter = new SVGActionWriter( *this, rMtf ); delete pWriter; } } // ------------- // - SVGWriter - // ------------- SVGWriter::SVGWriter( const REF( NMSP_LANG::XMultiServiceFactory )& rxMgr ) : mxFact( rxMgr ) { } // ----------------------------------------------------------------------------- SVGWriter::~SVGWriter() { } // ----------------------------------------------------------------------------- ANY SAL_CALL SVGWriter::queryInterface( const NMSP_UNO::Type & rType ) throw( NMSP_UNO::RuntimeException ) { const ANY aRet( NMSP_CPPU::queryInterface( rType, static_cast< NMSP_SVG::XSVGWriter* >( this ) ) ); return( aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType ) ); } // ----------------------------------------------------------------------------- void SAL_CALL SVGWriter::acquire() throw() { OWeakObject::acquire(); } // ----------------------------------------------------------------------------- void SAL_CALL SVGWriter::release() throw() { OWeakObject::release(); } // ----------------------------------------------------------------------------- void SAL_CALL SVGWriter::write( const REF( NMSP_SAX::XDocumentHandler )& rxDocHandler, const SEQ( sal_Int8 )& rMtfSeq ) throw( NMSP_UNO::RuntimeException ) { SvMemoryStream aMemStm( (char*) rMtfSeq.getConstArray(), rMtfSeq.getLength(), STREAM_READ ); GDIMetaFile aMtf; aMemStm.SetCompressMode( COMPRESSMODE_FULL ); aMemStm >> aMtf; const REF( NMSP_SAX::XDocumentHandler ) xDocumentHandler( rxDocHandler ); // #110680# // SVGMtfExport* pWriter = new SVGMtfExport( xDocumentHandler ); SVGMtfExport* pWriter = new SVGMtfExport( mxFact, xDocumentHandler ); pWriter->writeMtf( aMtf ); delete pWriter; } <commit_msg>INTEGRATION: CWS ooo19126 (1.5.284); FILE MERGED 2005/09/05 13:01:14 rt 1.5.284.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: svgwriter.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 20:42:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "svgwriter.hxx" #include "svgaction.hxx" #include <uno/mapping.hxx> // ---------------- // - SVGMtfExport - // ---------------- class SVGMtfExport : public SvXMLExport { private: SVGMtfExport(); protected: virtual void _ExportMeta() {} virtual void _ExportStyles( BOOL bUsed ) {} virtual void _ExportAutoStyles() {} virtual void _ExportContent() {} virtual void _ExportMasterStyles() {} virtual ULONG exportDoc( enum ::xmloff::token::XMLTokenEnum eClass ) { return 0; } public: // #110680# SVGMtfExport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, const REF( NMSP_SAX::XDocumentHandler )& rxHandler ); virtual ~SVGMtfExport(); virtual void writeMtf( const GDIMetaFile& rMtf ); }; // ----------------------------------------------------------------------------- // #110680# SVGMtfExport::SVGMtfExport( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory, const REF( NMSP_SAX::XDocumentHandler )& rxHandler ) : SvXMLExport( xServiceFactory, NMSP_RTL::OUString(), rxHandler ) { GetDocHandler()->startDocument(); } // ----------------------------------------------------------------------------- SVGMtfExport::~SVGMtfExport() { GetDocHandler()->endDocument(); } // ----------------------------------------------------------------------------- void SVGMtfExport::writeMtf( const GDIMetaFile& rMtf ) { const Size aSize( OutputDevice::LogicToLogic( rMtf.GetPrefSize(), rMtf.GetPrefMapMode(), MAP_MM ) ); NMSP_RTL::OUString aAttr; REF( NMSP_SAX::XExtendedDocumentHandler ) xExtDocHandler( GetDocHandler(), NMSP_UNO::UNO_QUERY ); if( xExtDocHandler.is() ) xExtDocHandler->unknown( SVG_DTD_STRING ); aAttr = NMSP_RTL::OUString::valueOf( aSize.Width() ); aAttr += B2UCONST( "mm" ); AddAttribute( XML_NAMESPACE_NONE, "width", aAttr ); aAttr = NMSP_RTL::OUString::valueOf( aSize.Height() ); aAttr += B2UCONST( "mm" ); AddAttribute( XML_NAMESPACE_NONE, "height", aAttr ); aAttr = B2UCONST( "0 0 " ); aAttr += NMSP_RTL::OUString::valueOf( aSize.Width() * 100L ); aAttr += B2UCONST( " " ); aAttr += NMSP_RTL::OUString::valueOf( aSize.Height() * 100L ); AddAttribute( XML_NAMESPACE_NONE, "viewBox", aAttr ); { SvXMLElementExport aSVG( *this, XML_NAMESPACE_NONE, "svg", TRUE, TRUE ); SVGActionWriter* pWriter = new SVGActionWriter( *this, rMtf ); delete pWriter; } } // ------------- // - SVGWriter - // ------------- SVGWriter::SVGWriter( const REF( NMSP_LANG::XMultiServiceFactory )& rxMgr ) : mxFact( rxMgr ) { } // ----------------------------------------------------------------------------- SVGWriter::~SVGWriter() { } // ----------------------------------------------------------------------------- ANY SAL_CALL SVGWriter::queryInterface( const NMSP_UNO::Type & rType ) throw( NMSP_UNO::RuntimeException ) { const ANY aRet( NMSP_CPPU::queryInterface( rType, static_cast< NMSP_SVG::XSVGWriter* >( this ) ) ); return( aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType ) ); } // ----------------------------------------------------------------------------- void SAL_CALL SVGWriter::acquire() throw() { OWeakObject::acquire(); } // ----------------------------------------------------------------------------- void SAL_CALL SVGWriter::release() throw() { OWeakObject::release(); } // ----------------------------------------------------------------------------- void SAL_CALL SVGWriter::write( const REF( NMSP_SAX::XDocumentHandler )& rxDocHandler, const SEQ( sal_Int8 )& rMtfSeq ) throw( NMSP_UNO::RuntimeException ) { SvMemoryStream aMemStm( (char*) rMtfSeq.getConstArray(), rMtfSeq.getLength(), STREAM_READ ); GDIMetaFile aMtf; aMemStm.SetCompressMode( COMPRESSMODE_FULL ); aMemStm >> aMtf; const REF( NMSP_SAX::XDocumentHandler ) xDocumentHandler( rxDocHandler ); // #110680# // SVGMtfExport* pWriter = new SVGMtfExport( xDocumentHandler ); SVGMtfExport* pWriter = new SVGMtfExport( mxFact, xDocumentHandler ); pWriter->writeMtf( aMtf ); delete pWriter; } <|endoftext|>
<commit_before>#include "Nonlinear3D.h" #include "SolidModel.h" #include "Problem.h" #include "SymmIsotropicElasticityTensor.h" #include "VolumetricModel.h" namespace Elk { namespace SolidMechanics { Nonlinear3D::Nonlinear3D( const std::string & name, InputParameters parameters ) :Element( name, parameters ), _grad_disp_x(coupledGradient("disp_x")), _grad_disp_y(coupledGradient("disp_y")), _grad_disp_z(coupledGradient("disp_z")), _grad_disp_x_old(coupledGradientOld("disp_x")), _grad_disp_y_old(coupledGradientOld("disp_y")), _grad_disp_z_old(coupledGradientOld("disp_z")), _decomp_method( RashidApprox ), _incremental_rotation(3,3), _Uhat(3,3) { std::string increment_calculation = getParam<std::string>("increment_calculation"); std::transform( increment_calculation.begin(), increment_calculation.end(), increment_calculation.begin(), ::tolower ); if ( increment_calculation == "rashidapprox" ) { _decomp_method = RashidApprox; } else if ( increment_calculation == "eigen" ) { _decomp_method = Eigen; } else { mooseError( "The options for the increment calculation are RashidApprox and Eigen."); } } //////////////////////////////////////////////////////////////////////// Nonlinear3D::~Nonlinear3D() { } //////////////////////////////////////////////////////////////////////// void Nonlinear3D::computeIncrementalDeformationGradient( std::vector<ColumnMajorMatrix> & Fhat ) { // A = grad(u(k+1) - u(k)) // Fbar = 1 + grad(u(k)) // Fhat = 1 + A*(Fbar^-1) ColumnMajorMatrix A; ColumnMajorMatrix Fbar; ColumnMajorMatrix Fbar_inverse; ColumnMajorMatrix Fhat_average; Real volume(0); _Fbar.resize(_qrule->n_points()); for ( _qp= 0; _qp < _qrule->n_points(); ++_qp ) { fillMatrix( _grad_disp_x, _grad_disp_y, _grad_disp_z, A ); fillMatrix( _grad_disp_x_old, _grad_disp_y_old, _grad_disp_z_old, Fbar); A -= Fbar; Fbar.addDiag( 1 ); _Fbar[_qp] = Fbar; // Get Fbar^(-1) // Computing the inverse is generally a bad idea. // It's better to compute LU factors. For now at least, we'll take // a direct route. invertMatrix( Fbar, Fbar_inverse ); Fhat[_qp] = A * Fbar_inverse; Fhat[_qp].addDiag( 1 ); // Now include the contribution for the integration of Fhat over the element Fhat_average += Fhat[_qp] * _JxW[_qp]; volume += _JxW[_qp]; // Accumulate original configuration volume } Fhat_average /= volume; const Real det_Fhat_average( detMatrix( Fhat_average ) ); const Real third( 1./3. ); // Finalize volumetric locking correction for ( _qp=0; _qp < _qrule->n_points(); ++_qp ) { const Real det_Fhat( detMatrix( Fhat[_qp] ) ); const Real factor( std::pow( det_Fhat_average/det_Fhat, third ) ); Fhat[_qp] *= factor; } } //////////////////////////////////////////////////////////////////////// void Nonlinear3D::computeStrainAndRotationIncrement( const ColumnMajorMatrix & Fhat, SymmTensor & strain_increment ) { if ( _decomp_method == RashidApprox ) { computeStrainIncrement( Fhat, strain_increment ); computePolarDecomposition( Fhat ); } else if ( _decomp_method == Eigen ) { const int ND = 3; ColumnMajorMatrix eigen_value(ND,1), eigen_vector(ND,ND); ColumnMajorMatrix invUhat(ND,ND), logVhat(ND,ND); ColumnMajorMatrix n1(ND,1), n2(ND,1), n3(ND,1), N1(ND,1), N2(ND,1), N3(ND,1); ColumnMajorMatrix Chat = Fhat.transpose() * Fhat; Chat.eigen(eigen_value,eigen_vector); for(int i = 0; i < ND; i++) { N1(i) = eigen_vector(i,0); N2(i) = eigen_vector(i,1); N3(i) = eigen_vector(i,2); } const Real lamda1 = std::sqrt(eigen_value(0)); const Real lamda2 = std::sqrt(eigen_value(1)); const Real lamda3 = std::sqrt(eigen_value(2)); const Real log1 = std::log(lamda1); const Real log2 = std::log(lamda2); const Real log3 = std::log(lamda3); _Uhat = N1 * N1.transpose() * lamda1 + N2 * N2.transpose() * lamda2 + N3 * N3.transpose() * lamda3; invertMatrix(_Uhat,invUhat); _incremental_rotation = Fhat * invUhat; strain_increment = N1 * N1.transpose() * log1 + N2 * N2.transpose() * log2 + N3 * N3.transpose() * log3; } else { mooseError("Unknown polar decomposition type!"); } } //////////////////////////////////////////////////////////////////////// void Nonlinear3D::computeStrainIncrement( const ColumnMajorMatrix & Fhat, SymmTensor & strain_increment ) { // // A calculation of the strain at the mid-interval is probably more // accurate (second vs. first order). This would require the // incremental deformation gradient at the mid-step, which we // currently don't have. We would then have to calculate the // rotation for the whole step. // // // We are looking for: // log( Uhat ) // = log( sqrt( Fhat^T*Fhat ) ) // = log( sqrt( Chat ) ) // A Taylor series expansion gives: // ( Chat - 0.25 * Chat^T*Chat - 0.75 * I ) // = ( - 0.25 * Chat^T*Chat + Chat - 0.75 * I ) // = ( (0.25*Chat - 0.75*I) * (Chat - I) ) // = ( B * A ) // B // = 0.25*Chat - 0.75*I // = 0.25*(Chat - I) - 0.5*I // = 0.25*A - 0.5*I // const Real Uxx = Fhat(0,0); const Real Uxy = Fhat(0,1); const Real Uxz = Fhat(0,2); const Real Uyx = Fhat(1,0); const Real Uyy = Fhat(1,1); const Real Uyz = Fhat(1,2); const Real Uzx = Fhat(2,0); const Real Uzy = Fhat(2,1); const Real Uzz = Fhat(2,2); const Real Axx = Uxx*Uxx + Uyx*Uyx + Uzx*Uzx - 1.0; const Real Axy = Uxx*Uxy + Uyx*Uyy + Uzx*Uzy; const Real Axz = Uxx*Uxz + Uyx*Uyz + Uzx*Uzz; const Real Ayy = Uxy*Uxy + Uyy*Uyy + Uzy*Uzy - 1.0; const Real Ayz = Uxy*Uxz + Uyy*Uyz + Uzy*Uzz; const Real Azz = Uxz*Uxz + Uyz*Uyz + Uzz*Uzz - 1.0; const Real Bxx = 0.25 * Axx - 0.5; const Real Bxy = 0.25 * Axy; const Real Bxz = 0.25 * Axz; const Real Byy = 0.25 * Ayy - 0.5; const Real Byz = 0.25 * Ayz; const Real Bzz = 0.25 * Azz - 0.5; strain_increment.xx( -(Bxx*Axx + Bxy*Axy + Bxz*Axz) ); strain_increment.xy( -(Bxx*Axy + Bxy*Ayy + Bxz*Ayz) ); strain_increment.zx( -(Bxx*Axz + Bxy*Ayz + Bxz*Azz) ); strain_increment.yy( -(Bxy*Axy + Byy*Ayy + Byz*Ayz) ); strain_increment.yz( -(Bxy*Axz + Byy*Ayz + Byz*Azz) ); strain_increment.zz( -(Bxz*Axz + Byz*Ayz + Bzz*Azz) ); } //////////////////////////////////////////////////////////////////////// void Nonlinear3D::computePolarDecomposition( const ColumnMajorMatrix & Fhat ) { // From Rashid, 1993. ColumnMajorMatrix Fhat_inverse; invertMatrix( Fhat, Fhat_inverse ); Fhat_inverse = Fhat; /*std::cout << "Fhat = " << std::endl; ColumnMajorMatrix out(Fhat); out.print(); std::cout << "Fhat_inverse = " << std::endl; out = Fhat_inverse; out.print();*/ const Real Uxx = Fhat_inverse(0,0); const Real Uxy = Fhat_inverse(0,1); const Real Uxz = Fhat_inverse(0,2); const Real Uyx = Fhat_inverse(1,0); const Real Uyy = Fhat_inverse(1,1); const Real Uyz = Fhat_inverse(1,2); const Real Uzx = Fhat_inverse(2,0); const Real Uzy = Fhat_inverse(2,1); const Real Uzz = Fhat_inverse(2,2); const Real Ax = Uyz - Uzy; const Real Ay = Uzx - Uxz; const Real Az = Uxy - Uyx; const Real Q = 0.25 * (Ax*Ax + Ay*Ay + Az*Az); const Real traceF = Uxx + Uyy + Uzz; const Real P = 0.25 * (traceF - 1) * (traceF - 1); const Real Y = 1 / ((Q+P)*(Q+P)*(Q+P)); const Real C1 = std::sqrt(P * (1 + (P*(Q+Q+(Q+P))) * (1-(Q+P)) * Y)); const Real C2 = 0.125 + Q * 0.03125 * (P*P - 12*(P-1)) / (P*P); const Real C3 = 0.5 * std::sqrt( (P*Q*(3-Q) + P*P*P + Q*Q) / ((P+Q)*(P+Q)*(P+Q)) ); // Since the input to this routine is the incremental deformation gradient // and not the inverse incremental gradient, this result is the transpose // of the one in Rashid's paper. _incremental_rotation(0,0) = C1 + (C2*Ax)*Ax; _incremental_rotation(0,1) = (C2*Ay)*Ax + (C3*Az); _incremental_rotation(0,2) = (C2*Az)*Ax - (C3*Ay); _incremental_rotation(1,0) = (C2*Ax)*Ay - (C3*Az); _incremental_rotation(1,1) = C1 + (C2*Ay)*Ay; _incremental_rotation(1,2) = (C2*Az)*Ay + (C3*Ax); _incremental_rotation(2,0) = (C2*Ax)*Az + (C3*Ay); _incremental_rotation(2,1) = (C2*Ay)*Az - (C3*Ax); _incremental_rotation(2,2) = C1 + (C2*Az)*Az; } //////////////////////////////////////////////////////////////////////// void Nonlinear3D::finalizeStress( std::vector<SymmTensor*> & t) { // Using the incremental rotation, update the stress to the current configuration (R*T*R^T) for (unsigned i(0); i < t.size(); ++i) { Element::rotateSymmetricTensor( _incremental_rotation, *t[i], *t[i]); } } //////////////////////////////////////////////////////////////////////// void Nonlinear3D::computeStrain( const unsigned qp, const SymmTensor & total_strain_old, SymmTensor & total_strain_new, SymmTensor & strain_increment ) { computeStrainAndRotationIncrement(_Fhat[qp], strain_increment); total_strain_new = strain_increment; total_strain_new += total_strain_old; } //////////////////////////////////////////////////////////////////////// void Nonlinear3D::init() { _Fhat.resize(_qrule->n_points()); computeIncrementalDeformationGradient(_Fhat); } //////////////////////////////////////////////////////////////////////// } } <commit_msg>Discuss 3D example in workshop<commit_after>#include "Nonlinear3D.h" #include "SolidModel.h" #include "Problem.h" #include "SymmIsotropicElasticityTensor.h" #include "VolumetricModel.h" namespace Elk { namespace SolidMechanics { Nonlinear3D::Nonlinear3D( const std::string & name, InputParameters parameters ) :Element( name, parameters ), _grad_disp_x(coupledGradient("disp_x")), _grad_disp_y(coupledGradient("disp_y")), _grad_disp_z(coupledGradient("disp_z")), _grad_disp_x_old(coupledGradientOld("disp_x")), _grad_disp_y_old(coupledGradientOld("disp_y")), _grad_disp_z_old(coupledGradientOld("disp_z")), _decomp_method( RashidApprox ), _incremental_rotation(3,3), _Uhat(3,3) { std::string increment_calculation = getParam<std::string>("increment_calculation"); std::transform( increment_calculation.begin(), increment_calculation.end(), increment_calculation.begin(), ::tolower ); if ( increment_calculation == "rashidapprox" ) { _decomp_method = RashidApprox; } else if ( increment_calculation == "eigen" ) { _decomp_method = Eigen; } else { mooseError( "The options for the increment calculation are RashidApprox and Eigen."); } } //////////////////////////////////////////////////////////////////////// Nonlinear3D::~Nonlinear3D() { } //////////////////////////////////////////////////////////////////////// void Nonlinear3D::computeIncrementalDeformationGradient( std::vector<ColumnMajorMatrix> & Fhat ) { // A = grad(u(k+1) - u(k)) // Fbar = 1 + grad(u(k)) // Fhat = 1 + A*(Fbar^-1) ColumnMajorMatrix A; ColumnMajorMatrix Fbar; ColumnMajorMatrix Fbar_inverse; ColumnMajorMatrix Fhat_average; Real volume(0); _Fbar.resize(_qrule->n_points()); for ( _qp= 0; _qp < _qrule->n_points(); ++_qp ) { fillMatrix( _grad_disp_x, _grad_disp_y, _grad_disp_z, A ); fillMatrix( _grad_disp_x_old, _grad_disp_y_old, _grad_disp_z_old, Fbar); A -= Fbar; Fbar.addDiag( 1 ); _Fbar[_qp] = Fbar; // Get Fbar^(-1) // Computing the inverse is generally a bad idea. // It's better to compute LU factors. For now at least, we'll take // a direct route. invertMatrix( Fbar, Fbar_inverse ); Fhat[_qp] = A * Fbar_inverse; Fhat[_qp].addDiag( 1 ); // Now include the contribution for the integration of Fhat over the element Fhat_average += Fhat[_qp] * _JxW[_qp]; volume += _JxW[_qp]; // Accumulate original configuration volume } Fhat_average /= volume; const Real det_Fhat_average( detMatrix( Fhat_average ) ); const Real third( 1./3. ); // Finalize volumetric locking correction for ( _qp=0; _qp < _qrule->n_points(); ++_qp ) { const Real det_Fhat( detMatrix( Fhat[_qp] ) ); const Real factor( std::pow( det_Fhat_average/det_Fhat, third ) ); Fhat[_qp] *= factor; } } //////////////////////////////////////////////////////////////////////// void Nonlinear3D::computeStrainAndRotationIncrement( const ColumnMajorMatrix & Fhat, SymmTensor & strain_increment ) { if ( _decomp_method == RashidApprox ) { computeStrainIncrement( Fhat, strain_increment ); computePolarDecomposition( Fhat ); } else if ( _decomp_method == Eigen ) { const int ND = 3; ColumnMajorMatrix eigen_value(ND,1), eigen_vector(ND,ND); ColumnMajorMatrix invUhat(ND,ND), logVhat(ND,ND); ColumnMajorMatrix n1(ND,1), n2(ND,1), n3(ND,1), N1(ND,1), N2(ND,1), N3(ND,1); ColumnMajorMatrix Chat = Fhat.transpose() * Fhat; Chat.eigen(eigen_value,eigen_vector); for(int i = 0; i < ND; i++) { N1(i) = eigen_vector(i,0); N2(i) = eigen_vector(i,1); N3(i) = eigen_vector(i,2); } const Real lamda1 = std::sqrt(eigen_value(0)); const Real lamda2 = std::sqrt(eigen_value(1)); const Real lamda3 = std::sqrt(eigen_value(2)); const Real log1 = std::log(lamda1); const Real log2 = std::log(lamda2); const Real log3 = std::log(lamda3); _Uhat = N1 * N1.transpose() * lamda1 + N2 * N2.transpose() * lamda2 + N3 * N3.transpose() * lamda3; invertMatrix(_Uhat,invUhat); _incremental_rotation = Fhat * invUhat; strain_increment = N1 * N1.transpose() * log1 + N2 * N2.transpose() * log2 + N3 * N3.transpose() * log3; } else { mooseError("Unknown polar decomposition type!"); } } //////////////////////////////////////////////////////////////////////// void Nonlinear3D::computeStrainIncrement( const ColumnMajorMatrix & Fhat, SymmTensor & strain_increment ) { // // A calculation of the strain at the mid-interval is probably more // accurate (second vs. first order). This would require the // incremental deformation gradient at the mid-step, which we // currently don't have. We would then have to calculate the // rotation for the whole step. // // // We are looking for: // log( Uhat ) // = log( sqrt( Fhat^T*Fhat ) ) // = log( sqrt( Chat ) ) // A Taylor series expansion gives: // ( Chat - 0.25 * Chat^T*Chat - 0.75 * I ) // = ( - 0.25 * Chat^T*Chat + Chat - 0.75 * I ) // = ( (0.25*Chat - 0.75*I) * (Chat - I) ) // = ( B * A ) // B // = 0.25*Chat - 0.75*I // = 0.25*(Chat - I) - 0.5*I // = 0.25*A - 0.5*I // const Real Uxx = Fhat(0,0); const Real Uxy = Fhat(0,1); const Real Uxz = Fhat(0,2); const Real Uyx = Fhat(1,0); const Real Uyy = Fhat(1,1); const Real Uyz = Fhat(1,2); const Real Uzx = Fhat(2,0); const Real Uzy = Fhat(2,1); const Real Uzz = Fhat(2,2); const Real Axx = Uxx*Uxx + Uyx*Uyx + Uzx*Uzx - 1.0; const Real Axy = Uxx*Uxy + Uyx*Uyy + Uzx*Uzy; const Real Axz = Uxx*Uxz + Uyx*Uyz + Uzx*Uzz; const Real Ayy = Uxy*Uxy + Uyy*Uyy + Uzy*Uzy - 1.0; const Real Ayz = Uxy*Uxz + Uyy*Uyz + Uzy*Uzz; const Real Azz = Uxz*Uxz + Uyz*Uyz + Uzz*Uzz - 1.0; const Real Bxx = 0.25 * Axx - 0.5; const Real Bxy = 0.25 * Axy; const Real Bxz = 0.25 * Axz; const Real Byy = 0.25 * Ayy - 0.5; const Real Byz = 0.25 * Ayz; const Real Bzz = 0.25 * Azz - 0.5; strain_increment.xx( -(Bxx*Axx + Bxy*Axy + Bxz*Axz) ); strain_increment.xy( -(Bxx*Axy + Bxy*Ayy + Bxz*Ayz) ); strain_increment.zx( -(Bxx*Axz + Bxy*Ayz + Bxz*Azz) ); strain_increment.yy( -(Bxy*Axy + Byy*Ayy + Byz*Ayz) ); strain_increment.yz( -(Bxy*Axz + Byy*Ayz + Byz*Azz) ); strain_increment.zz( -(Bxz*Axz + Byz*Ayz + Bzz*Azz) ); } //////////////////////////////////////////////////////////////////////// void Nonlinear3D::computePolarDecomposition( const ColumnMajorMatrix & Fhat ) { // From Rashid, 1993. ColumnMajorMatrix Fhat_inverse; invertMatrix( Fhat, Fhat_inverse ); Fhat_inverse = Fhat; /*std::cout << "Fhat = " << std::endl; ColumnMajorMatrix out(Fhat); out.print(); std::cout << "Fhat_inverse = " << std::endl; out = Fhat_inverse; out.print();*/ const Real Uxx = Fhat_inverse(0,0); const Real Uxy = Fhat_inverse(0,1); const Real Uxz = Fhat_inverse(0,2); const Real Uyx = Fhat_inverse(1,0); const Real Uyy = Fhat_inverse(1,1); const Real Uyz = Fhat_inverse(1,2); const Real Uzx = Fhat_inverse(2,0); const Real Uzy = Fhat_inverse(2,1); const Real Uzz = Fhat_inverse(2,2); const Real Ax = Uyz - Uzy; const Real Ay = Uzx - Uxz; const Real Az = Uxy - Uyx; const Real Q = 0.25 * (Ax*Ax + Ay*Ay + Az*Az); const Real traceF = Uxx + Uyy + Uzz; const Real P = 0.25 * (traceF - 1) * (traceF - 1); const Real Y = 1 / ((Q+P)*(Q+P)*(Q+P)); const Real C1 = std::sqrt(P * (1 + (P*(Q+Q+(Q+P))) * (1-(Q+P)) * Y)); const Real C2 = 0.125 + Q * 0.03125 * (P*P - 12*(P-1)) / (P*P); const Real C3 = 0.5 * std::sqrt( (P*Q*(3-Q) + P*P*P + Q*Q) * Y ); // Since the input to this routine is the incremental deformation gradient // and not the inverse incremental gradient, this result is the transpose // of the one in Rashid's paper. _incremental_rotation(0,0) = C1 + (C2*Ax)*Ax; _incremental_rotation(0,1) = (C2*Ay)*Ax + (C3*Az); _incremental_rotation(0,2) = (C2*Az)*Ax - (C3*Ay); _incremental_rotation(1,0) = (C2*Ax)*Ay - (C3*Az); _incremental_rotation(1,1) = C1 + (C2*Ay)*Ay; _incremental_rotation(1,2) = (C2*Az)*Ay + (C3*Ax); _incremental_rotation(2,0) = (C2*Ax)*Az + (C3*Ay); _incremental_rotation(2,1) = (C2*Ay)*Az - (C3*Ax); _incremental_rotation(2,2) = C1 + (C2*Az)*Az; } //////////////////////////////////////////////////////////////////////// void Nonlinear3D::finalizeStress( std::vector<SymmTensor*> & t) { // Using the incremental rotation, update the stress to the current configuration (R*T*R^T) for (unsigned i(0); i < t.size(); ++i) { Element::rotateSymmetricTensor( _incremental_rotation, *t[i], *t[i]); } } //////////////////////////////////////////////////////////////////////// void Nonlinear3D::computeStrain( const unsigned qp, const SymmTensor & total_strain_old, SymmTensor & total_strain_new, SymmTensor & strain_increment ) { computeStrainAndRotationIncrement(_Fhat[qp], strain_increment); total_strain_new = strain_increment; total_strain_new += total_strain_old; } //////////////////////////////////////////////////////////////////////// void Nonlinear3D::init() { _Fhat.resize(_qrule->n_points()); computeIncrementalDeformationGradient(_Fhat); } //////////////////////////////////////////////////////////////////////// } } <|endoftext|>
<commit_before>/* Kopete Yahoo Protocol Receive a file Copyright (c) 2006 André Duffeck <duffeck@kde.org> ************************************************************************* * * * 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 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "receivefiletask.h" #include "transfer.h" #include "ymsgtransfer.h" #include "yahootypes.h" #include "client.h" #include <QTimer> #include <QFile> #include <kdebug.h> #include <klocale.h> #include <kio/global.h> #include <kio/job.h> #include <kio/jobclasses.h> ReceiveFileTask::ReceiveFileTask(Task* parent) : Task(parent) { kDebug(YAHOO_RAW_DEBUG) ; m_transmitted = 0; m_file = 0; m_transferJob = 0; } ReceiveFileTask::~ReceiveFileTask() { delete m_file; m_file = 0; } void ReceiveFileTask::onGo() { kDebug(YAHOO_RAW_DEBUG) ; YMSGTransfer *t = new YMSGTransfer(Yahoo::ServiceFileTransfer7); switch( m_type ) { case FileTransferAccept: m_file = new QFile( m_localUrl.path() ); if( !m_file->open( QIODevice::WriteOnly ) ) { emit error( m_transferId, KIO::ERR_CANNOT_OPEN_FOR_WRITING, i18n("Could not open file for writing.") ); setError(); return; } m_transferJob = KIO::get( m_remoteUrl, KIO::NoReload, KIO::HideProgressInfo ); QObject::connect( m_transferJob, SIGNAL( result( KJob* ) ), this, SLOT( slotComplete( KJob* ) ) ); QObject::connect( m_transferJob, SIGNAL( data( KIO::Job*, const QByteArray & ) ), this, SLOT( slotData( KIO::Job*, const QByteArray & ) ) ); delete t; break; case FileTransfer7Accept: t->setId( client()->sessionID() ); t->setParam( 1, client()->userId().toLocal8Bit() ); t->setParam( 5, m_userId.toLocal8Bit() ); t->setParam( 265, m_remoteUrl.url().toLocal8Bit() ); t->setParam( 222, 3 ); send( t ); break; case FileTransfer7Reject: t->setId( client()->sessionID() ); t->setParam( 1, client()->userId().toLocal8Bit() ); t->setParam( 5, m_userId.toLocal8Bit() ); t->setParam( 265, m_remoteUrl.url().toLocal8Bit() ); t->setParam( 222, 4 ); send( t ); break; default: delete t; } } bool ReceiveFileTask::take( Transfer* transfer ) { kDebug(YAHOO_RAW_DEBUG) ; if ( !forMe( transfer ) ) return false; YMSGTransfer *t = static_cast<YMSGTransfer*>(transfer); parseFileTransfer7Info( t ); return true; } bool ReceiveFileTask::forMe( const Transfer *transfer ) const { kDebug(YAHOO_RAW_DEBUG) ; const YMSGTransfer *t = 0L; t = dynamic_cast<const YMSGTransfer*>(transfer); if (!t) return false; if( t->service() == Yahoo::ServiceFileTransfer7Info ) { // Only take this transfer if we are the corresponding task (in case of simultaneous file transfers) if( t->firstParam( 265 ) == m_remoteUrl.url().toLocal8Bit() ) return true; else return false; } else return false; } void ReceiveFileTask::slotData( KIO::Job *job, const QByteArray& data ) { Q_UNUSED( job ); kDebug(YAHOO_RAW_DEBUG) ; m_transmitted += data.size(); emit bytesProcessed( m_transferId, m_transmitted ); m_file->write( data ); } void ReceiveFileTask::slotComplete( KJob *job ) { kDebug(YAHOO_RAW_DEBUG) ; KIO::TransferJob *transfer = static_cast< KIO::TransferJob * >(job); if( m_file ) m_file->close(); if ( job->error () || transfer->isErrorPage () ) { emit error( m_transferId, KIO::ERR_ABORTED, i18n("An error occurred while downloading the file.") ); setError(); } else { emit complete( m_transferId ); setSuccess(); } } void ReceiveFileTask::parseFileTransfer7Info( YMSGTransfer *transfer ) { kDebug(YAHOO_RAW_DEBUG) ; if( transfer->firstParam( 249 ).toInt() == 1 ) { // Reject P2P Transfer offer YMSGTransfer *t = new YMSGTransfer(Yahoo::ServiceFileTransfer7Accept); t->setId( client()->sessionID() ); t->setParam( 1, client()->userId().toLocal8Bit() ); t->setParam( 5, transfer->firstParam( 4 ) ); t->setParam( 265, transfer->firstParam( 265 ) ); t->setParam( 66, -3 ); send( t ); } else if( transfer->firstParam( 249 ).toInt() == 3 ) { m_file = new QFile( m_localUrl.path() ); if( !m_file->open( QIODevice::WriteOnly ) ) { emit error( m_transferId, KIO::ERR_CANNOT_OPEN_FOR_WRITING, i18n("Could not open file for writing.") ); setError(); return; } YMSGTransfer *t = new YMSGTransfer(Yahoo::ServiceFileTransfer7Accept); t->setId( client()->sessionID() ); t->setParam( 1, client()->userId().toLocal8Bit() ); t->setParam( 5, transfer->firstParam( 4 ) ); t->setParam( 265, transfer->firstParam( 265 ) ); t->setParam( 27, transfer->firstParam( 27 ) ); t->setParam( 249, 3 ); // Use Reflection server t->setParam( 251, transfer->firstParam( 251 ) ); send( t ); // The server expects a HTTP HEAD command prior to the GET m_mimetypeJob = KIO::mimetype(QString::fromLatin1("http://%1/relay?token=%2&sender=%3&recver=%4") .arg( QString(transfer->firstParam( 250 )) ).arg( QString(transfer->firstParam( 251 )) ).arg(m_userId).arg(client()->userId()), false); m_mimetypeJob->addMetaData("cookies", "manual"); m_mimetypeJob->addMetaData("setcookies", QString::fromLatin1("Cookie: T=%1; path=/; domain=.yahoo.com; Y=%2; C=%3;") .arg(client()->tCookie()).arg(client()->yCookie()).arg(client()->cCookie()) ); m_transferJob = KIO::get( QString::fromLatin1("http://%1/relay?token=%2&sender=%3&recver=%4") .arg( QString(transfer->firstParam( 250 )) ).arg( QString(transfer->firstParam( 251 )) ).arg(m_userId).arg(client()->userId()), KIO::NoReload, KIO::HideProgressInfo ); QObject::connect( m_transferJob, SIGNAL( result( KJob* ) ), this, SLOT( slotComplete( KJob* ) ) ); QObject::connect( m_transferJob, SIGNAL( data( KIO::Job*, const QByteArray & ) ), this, SLOT( slotData( KIO::Job*, const QByteArray & ) ) ); m_transferJob->addMetaData("cookies", "manual"); m_transferJob->addMetaData("setcookies", QString::fromLatin1("Cookie: T=%1; path=/; domain=.yahoo.com; Y=%2; C=%3;") .arg(client()->tCookie()).arg(client()->yCookie()).arg(client()->cCookie()) ); } } void ReceiveFileTask::setRemoteUrl( KUrl url ) { m_remoteUrl = url; } void ReceiveFileTask::setLocalUrl( KUrl url ) { m_localUrl = url; } void ReceiveFileTask::setTransferId( unsigned int transferId ) { m_transferId = transferId; } void ReceiveFileTask::setType( Type type ) { m_type = type; } void ReceiveFileTask::setUserId( const QString &userId ) { m_userId = userId; } void ReceiveFileTask::canceled( unsigned int id ) { if( m_transferId != id ) return; if( m_transferJob ) m_transferJob->kill(); setError(); } #include "receivefiletask.moc" <commit_msg>Delete also when an error has occurred. CID: 4960<commit_after>/* Kopete Yahoo Protocol Receive a file Copyright (c) 2006 André Duffeck <duffeck@kde.org> ************************************************************************* * * * 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 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "receivefiletask.h" #include "transfer.h" #include "ymsgtransfer.h" #include "yahootypes.h" #include "client.h" #include <QTimer> #include <QFile> #include <kdebug.h> #include <klocale.h> #include <kio/global.h> #include <kio/job.h> #include <kio/jobclasses.h> ReceiveFileTask::ReceiveFileTask(Task* parent) : Task(parent) { kDebug(YAHOO_RAW_DEBUG) ; m_transmitted = 0; m_file = 0; m_transferJob = 0; } ReceiveFileTask::~ReceiveFileTask() { delete m_file; m_file = 0; } void ReceiveFileTask::onGo() { kDebug(YAHOO_RAW_DEBUG) ; YMSGTransfer *t = new YMSGTransfer(Yahoo::ServiceFileTransfer7); switch( m_type ) { case FileTransferAccept: m_file = new QFile( m_localUrl.path() ); if( !m_file->open( QIODevice::WriteOnly ) ) { emit error( m_transferId, KIO::ERR_CANNOT_OPEN_FOR_WRITING, i18n("Could not open file for writing.") ); setError(); delete t; return; } m_transferJob = KIO::get( m_remoteUrl, KIO::NoReload, KIO::HideProgressInfo ); QObject::connect( m_transferJob, SIGNAL( result( KJob* ) ), this, SLOT( slotComplete( KJob* ) ) ); QObject::connect( m_transferJob, SIGNAL( data( KIO::Job*, const QByteArray & ) ), this, SLOT( slotData( KIO::Job*, const QByteArray & ) ) ); delete t; break; case FileTransfer7Accept: t->setId( client()->sessionID() ); t->setParam( 1, client()->userId().toLocal8Bit() ); t->setParam( 5, m_userId.toLocal8Bit() ); t->setParam( 265, m_remoteUrl.url().toLocal8Bit() ); t->setParam( 222, 3 ); send( t ); break; case FileTransfer7Reject: t->setId( client()->sessionID() ); t->setParam( 1, client()->userId().toLocal8Bit() ); t->setParam( 5, m_userId.toLocal8Bit() ); t->setParam( 265, m_remoteUrl.url().toLocal8Bit() ); t->setParam( 222, 4 ); send( t ); break; default: delete t; } } bool ReceiveFileTask::take( Transfer* transfer ) { kDebug(YAHOO_RAW_DEBUG) ; if ( !forMe( transfer ) ) return false; YMSGTransfer *t = static_cast<YMSGTransfer*>(transfer); parseFileTransfer7Info( t ); return true; } bool ReceiveFileTask::forMe( const Transfer *transfer ) const { kDebug(YAHOO_RAW_DEBUG) ; const YMSGTransfer *t = 0L; t = dynamic_cast<const YMSGTransfer*>(transfer); if (!t) return false; if( t->service() == Yahoo::ServiceFileTransfer7Info ) { // Only take this transfer if we are the corresponding task (in case of simultaneous file transfers) if( t->firstParam( 265 ) == m_remoteUrl.url().toLocal8Bit() ) return true; else return false; } else return false; } void ReceiveFileTask::slotData( KIO::Job *job, const QByteArray& data ) { Q_UNUSED( job ); kDebug(YAHOO_RAW_DEBUG) ; m_transmitted += data.size(); emit bytesProcessed( m_transferId, m_transmitted ); m_file->write( data ); } void ReceiveFileTask::slotComplete( KJob *job ) { kDebug(YAHOO_RAW_DEBUG) ; KIO::TransferJob *transfer = static_cast< KIO::TransferJob * >(job); if( m_file ) m_file->close(); if ( job->error () || transfer->isErrorPage () ) { emit error( m_transferId, KIO::ERR_ABORTED, i18n("An error occurred while downloading the file.") ); setError(); } else { emit complete( m_transferId ); setSuccess(); } } void ReceiveFileTask::parseFileTransfer7Info( YMSGTransfer *transfer ) { kDebug(YAHOO_RAW_DEBUG) ; if( transfer->firstParam( 249 ).toInt() == 1 ) { // Reject P2P Transfer offer YMSGTransfer *t = new YMSGTransfer(Yahoo::ServiceFileTransfer7Accept); t->setId( client()->sessionID() ); t->setParam( 1, client()->userId().toLocal8Bit() ); t->setParam( 5, transfer->firstParam( 4 ) ); t->setParam( 265, transfer->firstParam( 265 ) ); t->setParam( 66, -3 ); send( t ); } else if( transfer->firstParam( 249 ).toInt() == 3 ) { m_file = new QFile( m_localUrl.path() ); if( !m_file->open( QIODevice::WriteOnly ) ) { emit error( m_transferId, KIO::ERR_CANNOT_OPEN_FOR_WRITING, i18n("Could not open file for writing.") ); setError(); return; } YMSGTransfer *t = new YMSGTransfer(Yahoo::ServiceFileTransfer7Accept); t->setId( client()->sessionID() ); t->setParam( 1, client()->userId().toLocal8Bit() ); t->setParam( 5, transfer->firstParam( 4 ) ); t->setParam( 265, transfer->firstParam( 265 ) ); t->setParam( 27, transfer->firstParam( 27 ) ); t->setParam( 249, 3 ); // Use Reflection server t->setParam( 251, transfer->firstParam( 251 ) ); send( t ); // The server expects a HTTP HEAD command prior to the GET m_mimetypeJob = KIO::mimetype(QString::fromLatin1("http://%1/relay?token=%2&sender=%3&recver=%4") .arg( QString(transfer->firstParam( 250 )) ).arg( QString(transfer->firstParam( 251 )) ).arg(m_userId).arg(client()->userId()), false); m_mimetypeJob->addMetaData("cookies", "manual"); m_mimetypeJob->addMetaData("setcookies", QString::fromLatin1("Cookie: T=%1; path=/; domain=.yahoo.com; Y=%2; C=%3;") .arg(client()->tCookie()).arg(client()->yCookie()).arg(client()->cCookie()) ); m_transferJob = KIO::get( QString::fromLatin1("http://%1/relay?token=%2&sender=%3&recver=%4") .arg( QString(transfer->firstParam( 250 )) ).arg( QString(transfer->firstParam( 251 )) ).arg(m_userId).arg(client()->userId()), KIO::NoReload, KIO::HideProgressInfo ); QObject::connect( m_transferJob, SIGNAL( result( KJob* ) ), this, SLOT( slotComplete( KJob* ) ) ); QObject::connect( m_transferJob, SIGNAL( data( KIO::Job*, const QByteArray & ) ), this, SLOT( slotData( KIO::Job*, const QByteArray & ) ) ); m_transferJob->addMetaData("cookies", "manual"); m_transferJob->addMetaData("setcookies", QString::fromLatin1("Cookie: T=%1; path=/; domain=.yahoo.com; Y=%2; C=%3;") .arg(client()->tCookie()).arg(client()->yCookie()).arg(client()->cCookie()) ); } } void ReceiveFileTask::setRemoteUrl( KUrl url ) { m_remoteUrl = url; } void ReceiveFileTask::setLocalUrl( KUrl url ) { m_localUrl = url; } void ReceiveFileTask::setTransferId( unsigned int transferId ) { m_transferId = transferId; } void ReceiveFileTask::setType( Type type ) { m_type = type; } void ReceiveFileTask::setUserId( const QString &userId ) { m_userId = userId; } void ReceiveFileTask::canceled( unsigned int id ) { if( m_transferId != id ) return; if( m_transferJob ) m_transferJob->kill(); setError(); } #include "receivefiletask.moc" <|endoftext|>
<commit_before>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QIMESSAGING_DETAILS_GENERICOBJECT_HXX_ #define _QIMESSAGING_DETAILS_GENERICOBJECT_HXX_ #include <qimessaging/buffer.hpp> #include <qimessaging/future.hpp> namespace qi { template<typename T> GenericValue makeObjectValue(T* ptr) { GenericValue res = toValue(*ptr); qiLogDebug("meta") <<"metaobject on " << ptr <<" " << res.value; return res; } // We need to specialize Manager on genericobject to make a copy namespace detail { template<> struct TypeManager<GenericObject>: public TypeManagerDefault<GenericObject> { static void* create() { return new GenericObject(0, 0); } static void copy(void* dst, const void* src) { TypeManagerDefault<GenericObject>::copy(dst, src); GenericObject* o = (GenericObject*)dst; o->value = o->type->clone(o->value); } static void destroy(void* ptr) { GenericObject* go = (GenericObject*)ptr; go->type->destroy(go->value); delete go; } }; } namespace detail { template <typename T> inline void futureAdapter(qi::Future<qi::GenericValue> metaFut, qi::Promise<T> promise) { //error handling if (metaFut.hasError()) { promise.setError(metaFut.error()); return; } GenericValue val = metaFut.value(); Type* targetType = typeOf<T>(); std::pair<GenericValue, bool> conv = val.convert(targetType); if (!conv.first.type) promise.setError("Unable to convert call result to target type"); else { T* res = (T*)conv.first.type->ptrFromStorage(&conv.first.value); promise.setValue(*res); } if (conv.second) conv.first.destroy(); } template <> inline void futureAdapter<void>(qi::Future<qi::GenericValue> metaFut, qi::Promise<void> promise) { //error handling if (metaFut.hasError()) { promise.setError(metaFut.error()); return; } promise.setValue(0); } } template<typename R> qi::FutureSync<R> GenericObject::call(const std::string& methodName, qi::AutoGenericValue p1, qi::AutoGenericValue p2, qi::AutoGenericValue p3, qi::AutoGenericValue p4, qi::AutoGenericValue p5, qi::AutoGenericValue p6, qi::AutoGenericValue p7, qi::AutoGenericValue p8) { qi::Promise<R> res; if (!value || !type) { res.setError("Invalid GenericObject"); return res.future(); } qi::AutoGenericValue* vals[8]= {&p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8}; std::vector<qi::GenericValue> params; for (unsigned i=0; i<8; ++i) if (vals[i]->type) // 0 is a perfectly legal value params.push_back(*vals[i]); // Signature construction std::string signature = methodName + "::("; for (unsigned i=0; i< params.size(); ++i) signature += params[i].signature(); signature += ")"; std::string sigret; // Go through MetaType::signature which can return unknown, since // signatureFroType will produce a static assert sigret = typeOf<R>()->signature(); // Future adaptation qi::Future<qi::GenericValue> fmeta = xMetaCall(sigret, signature, params); fmeta.connect(boost::bind<void>(&detail::futureAdapter<R>, _1, res)); return res.future(); } } #endif // _QIMESSAGING_DETAILS_GENERICOBJECT_HXX_ <commit_msg>Fix leaked call result in futureAdapter.<commit_after>#pragma once /* ** Copyright (C) 2012 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QIMESSAGING_DETAILS_GENERICOBJECT_HXX_ #define _QIMESSAGING_DETAILS_GENERICOBJECT_HXX_ #include <qimessaging/buffer.hpp> #include <qimessaging/future.hpp> namespace qi { template<typename T> GenericValue makeObjectValue(T* ptr) { GenericValue res = toValue(*ptr); qiLogDebug("meta") <<"metaobject on " << ptr <<" " << res.value; return res; } // We need to specialize Manager on genericobject to make a copy namespace detail { template<> struct TypeManager<GenericObject>: public TypeManagerDefault<GenericObject> { static void* create() { return new GenericObject(0, 0); } static void copy(void* dst, const void* src) { TypeManagerDefault<GenericObject>::copy(dst, src); GenericObject* o = (GenericObject*)dst; o->value = o->type->clone(o->value); } static void destroy(void* ptr) { GenericObject* go = (GenericObject*)ptr; go->type->destroy(go->value); delete go; } }; } namespace detail { template <typename T> inline void futureAdapter(qi::Future<qi::GenericValue> metaFut, qi::Promise<T> promise) { //error handling if (metaFut.hasError()) { promise.setError(metaFut.error()); return; } GenericValue val = metaFut.value(); Type* targetType = typeOf<T>(); std::pair<GenericValue, bool> conv = val.convert(targetType); if (!conv.first.type) promise.setError("Unable to convert call result to target type"); else { T* res = (T*)conv.first.type->ptrFromStorage(&conv.first.value); promise.setValue(*res); } if (conv.second) conv.first.destroy(); val.destroy(); } template <> inline void futureAdapter<void>(qi::Future<qi::GenericValue> metaFut, qi::Promise<void> promise) { //error handling if (metaFut.hasError()) { promise.setError(metaFut.error()); return; } promise.setValue(0); } } template<typename R> qi::FutureSync<R> GenericObject::call(const std::string& methodName, qi::AutoGenericValue p1, qi::AutoGenericValue p2, qi::AutoGenericValue p3, qi::AutoGenericValue p4, qi::AutoGenericValue p5, qi::AutoGenericValue p6, qi::AutoGenericValue p7, qi::AutoGenericValue p8) { qi::Promise<R> res; if (!value || !type) { res.setError("Invalid GenericObject"); return res.future(); } qi::AutoGenericValue* vals[8]= {&p1, &p2, &p3, &p4, &p5, &p6, &p7, &p8}; std::vector<qi::GenericValue> params; for (unsigned i=0; i<8; ++i) if (vals[i]->type) // 0 is a perfectly legal value params.push_back(*vals[i]); // Signature construction std::string signature = methodName + "::("; for (unsigned i=0; i< params.size(); ++i) signature += params[i].signature(); signature += ")"; std::string sigret; // Go through MetaType::signature which can return unknown, since // signatureFroType will produce a static assert sigret = typeOf<R>()->signature(); // Future adaptation qi::Future<qi::GenericValue> fmeta = xMetaCall(sigret, signature, params); fmeta.connect(boost::bind<void>(&detail::futureAdapter<R>, _1, res)); return res.future(); } } #endif // _QIMESSAGING_DETAILS_GENERICOBJECT_HXX_ <|endoftext|>
<commit_before>#pragma once #include "common/SignalVector.hpp" #include <QAbstractTableModel> #include <QStandardItem> #include <boost/optional.hpp> #include <pajlada/signals/signalholder.hpp> namespace chatterino { template <typename TVectorItem> class SignalVectorModel : public QAbstractTableModel, pajlada::Signals::SignalHolder { public: SignalVectorModel(int columnCount, QObject *parent = nullptr) : QAbstractTableModel(parent) , columnCount_(columnCount) { for (int i = 0; i < columnCount; i++) { this->headerData_.emplace_back(); } } void init(BaseSignalVector<TVectorItem> *vec) { this->vector_ = vec; auto insert = [this](const SignalVectorItemArgs<TVectorItem> &args) { if (args.caller == this) { return; } // get row index int index = this->getModelIndexFromVectorIndex(args.index); assert(index >= 0 && index <= this->rows_.size()); // get row items std::vector<QStandardItem *> row = this->createRow(); this->getRowFromItem(args.item, row); // insert row index = this->beforeInsert(args.item, row, index); this->beginInsertRows(QModelIndex(), index, index); this->rows_.insert(this->rows_.begin() + index, Row(row, args.item)); this->endInsertRows(); }; int i = 0; for (const TVectorItem &item : vec->getVector()) { SignalVectorItemArgs<TVectorItem> args{item, i++, 0}; insert(args); } this->managedConnect(vec->itemInserted, insert); this->managedConnect(vec->itemRemoved, [this](auto args) { if (args.caller == this) { return; } int row = this->getModelIndexFromVectorIndex(args.index); assert(row >= 0 && row <= this->rows_.size()); // remove row std::vector<QStandardItem *> items = std::move(this->rows_[row].items); this->beginRemoveRows(QModelIndex(), row, row); this->rows_.erase(this->rows_.begin() + row); this->endRemoveRows(); this->afterRemoved(args.item, items, row); for (QStandardItem *item : items) { delete item; } }); this->afterInit(); } virtual ~SignalVectorModel() { for (Row &row : this->rows_) { for (QStandardItem *item : row.items) { delete item; } } } int rowCount(const QModelIndex &parent) const override { return this->rows_.size(); } int columnCount(const QModelIndex &parent) const override { return this->columnCount_; } QVariant data(const QModelIndex &index, int role) const override { int row = index.row(), column = index.column(); assert(row >= 0 && row < this->rows_.size() && column >= 0 && column < this->columnCount_); return rows_[row].items[column]->data(role); } bool setData(const QModelIndex &index, const QVariant &value, int role) override { int row = index.row(), column = index.column(); assert(row >= 0 && row < this->rows_.size() && column >= 0 && column < this->columnCount_); Row &rowItem = this->rows_[row]; rowItem.items[column]->setData(value, role); if (rowItem.isCustomRow) { this->customRowSetData(rowItem.items, column, value, role, row); } else { int vecRow = this->getVectorIndexFromModelIndex(row); this->vector_->removeItem(vecRow, this); assert(this->rows_[row].original); TVectorItem item = this->getItemFromRow( this->rows_[row].items, this->rows_[row].original.get()); this->vector_->insertItem(item, vecRow, this); } return true; } QVariant headerData(int section, Qt::Orientation orientation, int role) const override { if (orientation != Qt::Horizontal) { return QVariant(); } auto it = this->headerData_[section].find(role); if (it == this->headerData_[section].end()) { return QVariant(); } else { return it.value(); } } bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role = Qt::DisplayRole) override { if (orientation != Qt::Horizontal) { return false; } this->headerData_[section][role] = value; emit this->headerDataChanged(Qt::Horizontal, section, section); return true; } Qt::ItemFlags flags(const QModelIndex &index) const override { int row = index.row(), column = index.column(); if (row < 0 || column < 0) { return Qt::NoItemFlags; } assert(row >= 0 && row < this->rows_.size() && column >= 0 && column < this->columnCount_); return this->rows_[row].items[column]->flags(); } QStandardItem *getItem(int row, int column) { assert(row >= 0 && row < this->rows_.size() && column >= 0 && column < this->columnCount_); return rows_[row].items[column]; } void deleteRow(int row) { int signalVectorRow = this->getVectorIndexFromModelIndex(row); this->vector_->removeItem(signalVectorRow); } bool removeRows(int row, int count, const QModelIndex &parent) override { if (count != 1) { return false; } assert(row >= 0 && row < this->rows_.size()); int signalVectorRow = this->getVectorIndexFromModelIndex(row); this->vector_->removeItem(signalVectorRow); return true; } protected: virtual void afterInit() { } // turn a vector item into a model row virtual TVectorItem getItemFromRow(std::vector<QStandardItem *> &row, const TVectorItem &original) = 0; // turns a row in the model into a vector item virtual void getRowFromItem(const TVectorItem &item, std::vector<QStandardItem *> &row) = 0; virtual int beforeInsert(const TVectorItem &item, std::vector<QStandardItem *> &row, int proposedIndex) { return proposedIndex; } virtual void afterRemoved(const TVectorItem &item, std::vector<QStandardItem *> &row, int index) { } virtual void customRowSetData(const std::vector<QStandardItem *> &row, int column, const QVariant &value, int role, int rowIndex) { } void insertCustomRow(std::vector<QStandardItem *> row, int index) { assert(index >= 0 && index <= this->rows_.size()); this->beginInsertRows(QModelIndex(), index, index); this->rows_.insert(this->rows_.begin() + index, Row(std::move(row), true)); this->endInsertRows(); } void removeCustomRow(int index) { assert(index >= 0 && index <= this->rows_.size()); assert(this->rows_[index].isCustomRow); this->beginRemoveRows(QModelIndex(), index, index); this->rows_.erase(this->rows_.begin() + index); this->endRemoveRows(); } std::vector<QStandardItem *> createRow() { std::vector<QStandardItem *> row; for (int i = 0; i < this->columnCount_; i++) { row.push_back(new QStandardItem()); } return row; } struct Row { std::vector<QStandardItem *> items; boost::optional<TVectorItem> original; bool isCustomRow; Row(std::vector<QStandardItem *> _items, bool _isCustomRow = false) : items(std::move(_items)) , isCustomRow(_isCustomRow) { } Row(std::vector<QStandardItem *> _items, const TVectorItem &_original, bool _isCustomRow = false) : items(std::move(_items)) , original(_original) , isCustomRow(_isCustomRow) { } }; private: std::vector<QMap<int, QVariant>> headerData_; BaseSignalVector<TVectorItem> *vector_; std::vector<Row> rows_; int columnCount_; // returns the related index of the SignalVector int getVectorIndexFromModelIndex(int index) { int i = 0; for (auto &row : this->rows_) { if (row.isCustomRow) { index--; continue; } if (i == index) { return i; } i++; } return i; } // returns the related index of the model int getModelIndexFromVectorIndex(int index) { int i = 0; for (auto &row : this->rows_) { if (row.isCustomRow) { index++; } if (i == index) { return i; } i++; } return i; } }; } // namespace chatterino <commit_msg>fixed warning + added more checks to SignalVectorModel<commit_after>#pragma once #include "common/SignalVector.hpp" #include <QAbstractTableModel> #include <QStandardItem> #include <boost/optional.hpp> #include <pajlada/signals/signalholder.hpp> namespace chatterino { template <typename TVectorItem> class SignalVectorModel : public QAbstractTableModel, pajlada::Signals::SignalHolder { public: SignalVectorModel(int columnCount, QObject *parent = nullptr) : QAbstractTableModel(parent) , columnCount_(columnCount) { for (int i = 0; i < columnCount; i++) { this->headerData_.emplace_back(); } } void init(BaseSignalVector<TVectorItem> *vec) { this->vector_ = vec; auto insert = [this](const SignalVectorItemArgs<TVectorItem> &args) { if (args.caller == this) { return; } // get row index int index = this->getModelIndexFromVectorIndex(args.index); assert(index >= 0 && index <= this->rows_.size()); // get row items std::vector<QStandardItem *> row = this->createRow(); this->getRowFromItem(args.item, row); // insert row index = this->beforeInsert(args.item, row, index); this->beginInsertRows(QModelIndex(), index, index); this->rows_.insert(this->rows_.begin() + index, Row(row, args.item)); this->endInsertRows(); }; int i = 0; for (const TVectorItem &item : vec->getVector()) { SignalVectorItemArgs<TVectorItem> args{item, i++, 0}; insert(args); } this->managedConnect(vec->itemInserted, insert); this->managedConnect(vec->itemRemoved, [this](auto args) { if (args.caller == this) { return; } int row = this->getModelIndexFromVectorIndex(args.index); assert(row >= 0 && row <= this->rows_.size()); // remove row std::vector<QStandardItem *> items = std::move(this->rows_[row].items); this->beginRemoveRows(QModelIndex(), row, row); this->rows_.erase(this->rows_.begin() + row); this->endRemoveRows(); this->afterRemoved(args.item, items, row); for (QStandardItem *item : items) { delete item; } }); this->afterInit(); } virtual ~SignalVectorModel() { for (Row &row : this->rows_) { for (QStandardItem *item : row.items) { delete item; } } } int rowCount(const QModelIndex &parent) const override { (void)parent; return this->rows_.size(); } int columnCount(const QModelIndex &parent) const override { (void)parent; return this->columnCount_; } QVariant data(const QModelIndex &index, int role) const override { int row = index.row(), column = index.column(); if (row < 0 || column < 0 || row >= this->rows_.size() || column >= this->columnCount_) { return QVariant(); } return rows_[row].items[column]->data(role); } bool setData(const QModelIndex &index, const QVariant &value, int role) override { int row = index.row(), column = index.column(); if (row < 0 || column < 0 || row >= this->rows_.size() || column >= this->columnCount_) { return false; } Row &rowItem = this->rows_[row]; rowItem.items[column]->setData(value, role); if (rowItem.isCustomRow) { this->customRowSetData(rowItem.items, column, value, role, row); } else { int vecRow = this->getVectorIndexFromModelIndex(row); this->vector_->removeItem(vecRow, this); assert(this->rows_[row].original); TVectorItem item = this->getItemFromRow( this->rows_[row].items, this->rows_[row].original.get()); this->vector_->insertItem(item, vecRow, this); } return true; } QVariant headerData(int section, Qt::Orientation orientation, int role) const override { if (orientation != Qt::Horizontal) { return QVariant(); } auto it = this->headerData_[section].find(role); if (it == this->headerData_[section].end()) { return QVariant(); } else { return it.value(); } } bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role = Qt::DisplayRole) override { if (orientation != Qt::Horizontal) { return false; } this->headerData_[section][role] = value; emit this->headerDataChanged(Qt::Horizontal, section, section); return true; } Qt::ItemFlags flags(const QModelIndex &index) const override { int row = index.row(), column = index.column(); if (row < 0 || column < 0 || row >= this->rows_.size() || column >= this->columnCount_) { return Qt::NoItemFlags; } assert(row >= 0 && row < this->rows_.size() && column >= 0 && column < this->columnCount_); return this->rows_[row].items[column]->flags(); } QStandardItem *getItem(int row, int column) { assert(row >= 0 && row < this->rows_.size() && column >= 0 && column < this->columnCount_); return rows_[row].items[column]; } void deleteRow(int row) { int signalVectorRow = this->getVectorIndexFromModelIndex(row); this->vector_->removeItem(signalVectorRow); } bool removeRows(int row, int count, const QModelIndex &parent) override { (void)parent; if (count != 1) { return false; } assert(row >= 0 && row < this->rows_.size()); int signalVectorRow = this->getVectorIndexFromModelIndex(row); this->vector_->removeItem(signalVectorRow); return true; } protected: virtual void afterInit() { } // turn a vector item into a model row virtual TVectorItem getItemFromRow(std::vector<QStandardItem *> &row, const TVectorItem &original) = 0; // turns a row in the model into a vector item virtual void getRowFromItem(const TVectorItem &item, std::vector<QStandardItem *> &row) = 0; virtual int beforeInsert(const TVectorItem &item, std::vector<QStandardItem *> &row, int proposedIndex) { (void)item, (void)row; return proposedIndex; } virtual void afterRemoved(const TVectorItem &item, std::vector<QStandardItem *> &row, int index) { (void)item, (void)row, (void)index; } virtual void customRowSetData(const std::vector<QStandardItem *> &row, int column, const QVariant &value, int role, int rowIndex) { (void)row, (void)column, (void)value, (void)role, (void)rowIndex; } void insertCustomRow(std::vector<QStandardItem *> row, int index) { assert(index >= 0 && index <= this->rows_.size()); this->beginInsertRows(QModelIndex(), index, index); this->rows_.insert(this->rows_.begin() + index, Row(std::move(row), true)); this->endInsertRows(); } void removeCustomRow(int index) { assert(index >= 0 && index <= this->rows_.size()); assert(this->rows_[index].isCustomRow); this->beginRemoveRows(QModelIndex(), index, index); this->rows_.erase(this->rows_.begin() + index); this->endRemoveRows(); } std::vector<QStandardItem *> createRow() { std::vector<QStandardItem *> row; for (int i = 0; i < this->columnCount_; i++) { row.push_back(new QStandardItem()); } return row; } struct Row { std::vector<QStandardItem *> items; boost::optional<TVectorItem> original; bool isCustomRow; Row(std::vector<QStandardItem *> _items, bool _isCustomRow = false) : items(std::move(_items)) , isCustomRow(_isCustomRow) { } Row(std::vector<QStandardItem *> _items, const TVectorItem &_original, bool _isCustomRow = false) : items(std::move(_items)) , original(_original) , isCustomRow(_isCustomRow) { } }; private: std::vector<QMap<int, QVariant>> headerData_; BaseSignalVector<TVectorItem> *vector_; std::vector<Row> rows_; int columnCount_; // returns the related index of the SignalVector int getVectorIndexFromModelIndex(int index) { int i = 0; for (auto &row : this->rows_) { if (row.isCustomRow) { index--; continue; } if (i == index) { return i; } i++; } return i; } // returns the related index of the model int getModelIndexFromVectorIndex(int index) { int i = 0; for (auto &row : this->rows_) { if (row.isCustomRow) { index++; } if (i == index) { return i; } i++; } return i; } }; } // namespace chatterino <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH * * * * 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. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "config.h" #include <SofaLoader/BaseVTKReader.h> #include <SofaLoader/BaseVTKReader.inl> namespace sofa { namespace component { namespace loader { namespace basevtkreader { BaseVTKReader::BaseVTKReader():inputPoints (NULL), inputPolygons(NULL), inputCells(NULL), inputCellOffsets(NULL), inputCellTypes(NULL), numberOfPoints(0),numberOfCells(0) {} BaseVTKReader::BaseVTKDataIO* BaseVTKReader::newVTKDataIO(const string& typestr) { if (!strcasecmp(typestr.c_str(), "char") || !strcasecmp(typestr.c_str(), "Int8")) return new VTKDataIO<char>; else if (!strcasecmp(typestr.c_str(), "unsigned_char") || !strcasecmp(typestr.c_str(), "UInt8")) return new VTKDataIO<unsigned char>; else if (!strcasecmp(typestr.c_str(), "short") || !strcasecmp(typestr.c_str(), "Int16")) return new VTKDataIO<short>; else if (!strcasecmp(typestr.c_str(), "unsigned_short") || !strcasecmp(typestr.c_str(), "UInt16")) return new VTKDataIO<unsigned short>; else if (!strcasecmp(typestr.c_str(), "int") || !strcasecmp(typestr.c_str(), "Int32")) return new VTKDataIO<int>; else if (!strcasecmp(typestr.c_str(), "unsigned_int") || !strcasecmp(typestr.c_str(), "UInt32")) return new VTKDataIO<unsigned int>; //else if (!strcasecmp(typestr.c_str(), "long") || !strcasecmp(typestr.c_str(), "Int64")) // return new VTKDataIO<long long>; //else if (!strcasecmp(typestr.c_str(), "unsigned_long") || !strcasecmp(typestr.c_str(), "UInt64")) // return new VTKDataIO<unsigned long long>; else if (!strcasecmp(typestr.c_str(), "float") || !strcasecmp(typestr.c_str(), "Float32")) return new VTKDataIO<float>; else if (!strcasecmp(typestr.c_str(), "double") || !strcasecmp(typestr.c_str(), "Float64")) return new VTKDataIO<double>; else return NULL; } BaseVTKReader::BaseVTKDataIO* BaseVTKReader::newVTKDataIO(const string& typestr, int num) { BaseVTKDataIO* result = NULL; if (num == 1) result = newVTKDataIO(typestr); else { if (!strcasecmp(typestr.c_str(), "char") || !strcasecmp(typestr.c_str(), "Int8") || !strcasecmp(typestr.c_str(), "short") || !strcasecmp(typestr.c_str(), "Int32") || !strcasecmp(typestr.c_str(), "int") || !strcasecmp(typestr.c_str(), "Int32")) { switch (num) { case 2: result = new VTKDataIO<Vec<2, int> >; break; case 3: result = new VTKDataIO<Vec<3, int> >; break; default: return NULL; } } if (!strcasecmp(typestr.c_str(), "unsigned char") || !strcasecmp(typestr.c_str(), "UInt8") || !strcasecmp(typestr.c_str(), "unsigned short") || !strcasecmp(typestr.c_str(), "UInt32") || !strcasecmp(typestr.c_str(), "unsigned int") || !strcasecmp(typestr.c_str(), "UInt32")) { switch (num) { case 2: result = new VTKDataIO<Vec<2, unsigned int> >; break; case 3: result = new VTKDataIO<Vec<3, unsigned int> >; break; default: return NULL; } } if (!strcasecmp(typestr.c_str(), "float") || !strcasecmp(typestr.c_str(), "Float32")) { switch (num) { case 2: result = new VTKDataIO<Vec<2, float> >; break; case 3: result = new VTKDataIO<Vec<3, float> >; break; default: return NULL; } } if (!strcasecmp(typestr.c_str(), "double") || !strcasecmp(typestr.c_str(), "Float64")) { switch (num) { case 2: result = new VTKDataIO<Vec<2, double> >; break; case 3: result = new VTKDataIO<Vec<3, double> >; break; default: return NULL; } } } result->nestedDataSize = num; return result; } bool BaseVTKReader::readVTK(const char* filename) { bool state = readFile(filename); return state; } } // basevtkreader } // namespace loader } // namespace component } // namespace sofa <commit_msg>[SofaKernel] FIX compilation on windows in BaseVTKReader<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH * * * * 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. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include "config.h" #include <SofaLoader/BaseVTKReader.h> #include <SofaLoader/BaseVTKReader.inl> #if defined(WIN32) || defined(_XBOX) #define strcasecmp stricmp #endif namespace sofa { namespace component { namespace loader { namespace basevtkreader { BaseVTKReader::BaseVTKReader():inputPoints (NULL), inputPolygons(NULL), inputCells(NULL), inputCellOffsets(NULL), inputCellTypes(NULL), numberOfPoints(0),numberOfCells(0) {} BaseVTKReader::BaseVTKDataIO* BaseVTKReader::newVTKDataIO(const string& typestr) { if (!strcasecmp(typestr.c_str(), "char") || !strcasecmp(typestr.c_str(), "Int8")) return new VTKDataIO<char>; else if (!strcasecmp(typestr.c_str(), "unsigned_char") || !strcasecmp(typestr.c_str(), "UInt8")) return new VTKDataIO<unsigned char>; else if (!strcasecmp(typestr.c_str(), "short") || !strcasecmp(typestr.c_str(), "Int16")) return new VTKDataIO<short>; else if (!strcasecmp(typestr.c_str(), "unsigned_short") || !strcasecmp(typestr.c_str(), "UInt16")) return new VTKDataIO<unsigned short>; else if (!strcasecmp(typestr.c_str(), "int") || !strcasecmp(typestr.c_str(), "Int32")) return new VTKDataIO<int>; else if (!strcasecmp(typestr.c_str(), "unsigned_int") || !strcasecmp(typestr.c_str(), "UInt32")) return new VTKDataIO<unsigned int>; //else if (!strcasecmp(typestr.c_str(), "long") || !strcasecmp(typestr.c_str(), "Int64")) // return new VTKDataIO<long long>; //else if (!strcasecmp(typestr.c_str(), "unsigned_long") || !strcasecmp(typestr.c_str(), "UInt64")) // return new VTKDataIO<unsigned long long>; else if (!strcasecmp(typestr.c_str(), "float") || !strcasecmp(typestr.c_str(), "Float32")) return new VTKDataIO<float>; else if (!strcasecmp(typestr.c_str(), "double") || !strcasecmp(typestr.c_str(), "Float64")) return new VTKDataIO<double>; else return NULL; } BaseVTKReader::BaseVTKDataIO* BaseVTKReader::newVTKDataIO(const string& typestr, int num) { BaseVTKDataIO* result = NULL; if (num == 1) result = newVTKDataIO(typestr); else { if (!strcasecmp(typestr.c_str(), "char") || !strcasecmp(typestr.c_str(), "Int8") || !strcasecmp(typestr.c_str(), "short") || !strcasecmp(typestr.c_str(), "Int32") || !strcasecmp(typestr.c_str(), "int") || !strcasecmp(typestr.c_str(), "Int32")) { switch (num) { case 2: result = new VTKDataIO<Vec<2, int> >; break; case 3: result = new VTKDataIO<Vec<3, int> >; break; default: return NULL; } } if (!strcasecmp(typestr.c_str(), "unsigned char") || !strcasecmp(typestr.c_str(), "UInt8") || !strcasecmp(typestr.c_str(), "unsigned short") || !strcasecmp(typestr.c_str(), "UInt32") || !strcasecmp(typestr.c_str(), "unsigned int") || !strcasecmp(typestr.c_str(), "UInt32")) { switch (num) { case 2: result = new VTKDataIO<Vec<2, unsigned int> >; break; case 3: result = new VTKDataIO<Vec<3, unsigned int> >; break; default: return NULL; } } if (!strcasecmp(typestr.c_str(), "float") || !strcasecmp(typestr.c_str(), "Float32")) { switch (num) { case 2: result = new VTKDataIO<Vec<2, float> >; break; case 3: result = new VTKDataIO<Vec<3, float> >; break; default: return NULL; } } if (!strcasecmp(typestr.c_str(), "double") || !strcasecmp(typestr.c_str(), "Float64")) { switch (num) { case 2: result = new VTKDataIO<Vec<2, double> >; break; case 3: result = new VTKDataIO<Vec<3, double> >; break; default: return NULL; } } } result->nestedDataSize = num; return result; } bool BaseVTKReader::readVTK(const char* filename) { bool state = readFile(filename); return state; } } // basevtkreader } // namespace loader } // namespace component } // namespace sofa <|endoftext|>
<commit_before><commit_msg>fix a whole screen flicker when enabling TAA<commit_after><|endoftext|>
<commit_before> /* * random_gen_test.cpp - Tests for random number generator * * This file is not performance critical and thus could be compield with lower * level optimization in order to enable assert() */ #include "test_suite.h" /* * TestRandCorrectness() - Tests whether the generator gives correct result * lying in the specified range */ void TestRandCorrectness(int iter) { PrintTestName("TestRandCorrectness"); SimpleInt64Random<10, 1000> r{}; for(int i = 0;i < iter;i++) { uint64_t num = r(i, 0); assert(num >= 10 && num < 1000); } dbg_printf("Iteration = %d; Done\n", iter); return; } /* * StandardDev() - Compute standard deviation * * The first component is std dev, and the second component is average */ static std::pair<double, double> StandardDev(const std::map<uint64_t, uint64_t> &m) { double avg = 0.0; double squared_dev = 0.0; // Aggregate for(auto it = m.begin();it != m.end();it++) { avg += it->second; } // Average avg /= m.size(); // Aggregate diff for(auto it = m.begin();it != m.end();it++) { double diff = static_cast<double>(it->second) - avg; squared_dev += (diff * diff); } // Average squared diff squared_dev /= m.size(); return std::make_pair(sqrt(squared_dev), avg); } /* * TestRandRandomness() - Test the randomness of numbers we generate */ void TestRandRandomness(int iter, uint64_t num_salt, bool print_to_file) { PrintTestName("TestRandRandomness"); static const uint64_t lower = 10; static const uint64_t higher = 1000; SimpleInt64Random<lower, higher> r{}; // We run with different salt to see how it distributes for(uint64_t salt = 0;salt < num_salt;salt++) { std::map<uint64_t, uint64_t> m{}; FILE *fp = nullptr; if(print_to_file == true) { char filename[256]; sprintf(filename, "random_%lu.txt", salt); fp = fopen(filename, "w"); assert(fp != nullptr); } for(int i = 0;i < iter;i++) { uint64_t num = r(i, salt); if(print_to_file == true) { fprintf(fp, "%lu\n", num); } // This will return false to if key already exists // to indicate that we should just increment auto ret = m.insert({num, 1}); if(ret.second == false) { ret.first->second++; } } if(print_to_file == true) { fclose(fp); } auto ret = StandardDev(m); dbg_printf("Salt = %lu; std dev = %f; avg = %f\n", salt, ret.first, ret.second); } return; } int main() { TestRandCorrectness(100000000); TestRandRandomness(1000000, 10, false); return 0; } <commit_msg>Small change<commit_after> /* * random_gen_test.cpp - Tests for random number generator * * This file is not performance critical and thus could be compield with lower * level optimization in order to enable assert() */ #include "test_suite.h" /* * TestRandCorrectness() - Tests whether the generator gives correct result * lying in the specified range */ void TestRandCorrectness(int iter) { PrintTestName("TestRandCorrectness"); SimpleInt64Random<10, 1000> r{}; for(int i = 0;i < iter;i++) { uint64_t num = r(i, 0); assert(num >= 10 && num < 1000); } dbg_printf("Iteration = %d; Done\n", iter); return; } /* * StandardDev() - Compute standard deviation * * The first component is std dev, and the second component is average */ static std::pair<double, double> StandardDev(const std::map<uint64_t, uint64_t> &m) { double avg = 0.0; double squared_dev = 0.0; // Aggregate for(auto it = m.begin();it != m.end();it++) { avg += it->second; } // Average avg /= m.size(); // Aggregate diff for(auto it = m.begin();it != m.end();it++) { double diff = static_cast<double>(it->second) - avg; squared_dev += (diff * diff); } // Average squared diff squared_dev /= m.size(); return std::make_pair(sqrt(squared_dev), avg); } /* * TestRandRandomness() - Test the randomness of numbers we generate */ void TestRandRandomness(int iter, uint64_t num_salt, bool print_to_file) { PrintTestName("TestRandRandomness"); static const uint64_t lower = 10; static const uint64_t higher = 1000; SimpleInt64Random<lower, higher> r{}; // We run with different salt to see how it distributes for(uint64_t salt = 0;salt < num_salt;salt++) { std::map<uint64_t, uint64_t> m{}; FILE *fp = nullptr; if(print_to_file == true) { char filename[256]; sprintf(filename, "random_%lu.txt", salt); fp = fopen(filename, "w"); assert(fp != nullptr); } for(int i = 0;i < iter;i++) { uint64_t num = r(i, salt); if(print_to_file == true) { fprintf(fp, "%lu\n", num); } // This will return false to if key already exists // to indicate that we should just increment auto ret = m.insert({num, 1}); if(ret.second == false) { ret.first->second++; } } if(print_to_file == true) { fclose(fp); } auto ret = StandardDev(m); // Note that average is a constant given iter since it's the total // number of numbers we have allocated dbg_printf("Salt = %lu; std dev = %f; avg = %f\n", salt, ret.first, ret.second); } return; } int main() { TestRandCorrectness(100000000); TestRandRandomness(1000000, 10, false); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple 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/StyleResolverState.h" #include "core/dom/Element.h" #include "core/dom/Node.h" #include "core/dom/NodeRenderStyle.h" #include "core/dom/NodeRenderingContext.h" #include "core/dom/VisitedLinkState.h" #include "core/page/Page.h" namespace WebCore { ElementResolveContext::ElementResolveContext(Element* element) : m_element(element) , m_elementLinkState(element ? element->document()->visitedLinkState()->determineLinkState(element) : NotInsideLink) , m_distributedToInsertionPoint(false) , m_resetStyleInheritance(false) { NodeRenderingContext context(element); m_parentNode = context.parentNodeForRenderingAndStyle(); m_distributedToInsertionPoint = context.insertionPoint(); m_resetStyleInheritance = context.resetStyleInheritance(); Node* documentElement = document()->documentElement(); RenderStyle* documentStyle = document()->renderStyle(); m_rootElementStyle = documentElement && element != documentElement ? documentElement->renderStyle() : documentStyle; } StyleResolveScope::StyleResolveScope(StyleResolverState* state, const Document* document, Element* e, RenderStyle* parentStyle, RenderRegion* regionForStyling) : m_state(state) { m_state->initForStyleResolve(document, e, parentStyle, regionForStyling); } StyleResolveScope::~StyleResolveScope() { m_state->clear(); } void StyleResolverState::clear() { m_elementContext = ElementResolveContext(); m_style = 0; m_parentStyle = 0; m_regionForStyling = 0; m_elementStyleResources.clear(); } void StyleResolverState::initForStyleResolve(const Document* newDocument, Element* newElement, RenderStyle* parentStyle, RenderRegion* regionForStyling) { ASSERT(!element() || document() == newDocument); if (newElement != element()) { if (newElement) m_elementContext = ElementResolveContext(newElement); else m_elementContext = ElementResolveContext(); } m_regionForStyling = regionForStyling; if (m_elementContext.resetStyleInheritance()) m_parentStyle = 0; else if (parentStyle) m_parentStyle = parentStyle; else if (m_elementContext.parentNode()) m_parentStyle = m_elementContext.parentNode()->renderStyle(); else m_parentStyle = 0; m_style = 0; m_elementStyleResources.clear(); m_fontDirty = false; // FIXME: StyleResolverState is never passed between documents // so we should be able to do this initialization at StyleResolverState // createion time instead of now, correct? if (Page* page = newDocument->page()) m_elementStyleResources.setDeviceScaleFactor(page->deviceScaleFactor()); } } // namespace WebCore <commit_msg>Remove broken optimization causing crashes on canary<commit_after>/* * Copyright (C) 1999 Lars Knoll (knoll@kde.org) * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple 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/StyleResolverState.h" #include "core/dom/Element.h" #include "core/dom/Node.h" #include "core/dom/NodeRenderStyle.h" #include "core/dom/NodeRenderingContext.h" #include "core/dom/VisitedLinkState.h" #include "core/page/Page.h" namespace WebCore { ElementResolveContext::ElementResolveContext(Element* element) : m_element(element) , m_elementLinkState(element ? element->document()->visitedLinkState()->determineLinkState(element) : NotInsideLink) , m_distributedToInsertionPoint(false) , m_resetStyleInheritance(false) { NodeRenderingContext context(element); m_parentNode = context.parentNodeForRenderingAndStyle(); m_distributedToInsertionPoint = context.insertionPoint(); m_resetStyleInheritance = context.resetStyleInheritance(); Node* documentElement = document()->documentElement(); RenderStyle* documentStyle = document()->renderStyle(); m_rootElementStyle = documentElement && element != documentElement ? documentElement->renderStyle() : documentStyle; } StyleResolveScope::StyleResolveScope(StyleResolverState* state, const Document* document, Element* e, RenderStyle* parentStyle, RenderRegion* regionForStyling) : m_state(state) { m_state->initForStyleResolve(document, e, parentStyle, regionForStyling); } StyleResolveScope::~StyleResolveScope() { m_state->clear(); } void StyleResolverState::clear() { m_elementContext = ElementResolveContext(); m_style = 0; m_parentStyle = 0; m_regionForStyling = 0; m_elementStyleResources.clear(); } void StyleResolverState::initForStyleResolve(const Document* newDocument, Element* newElement, RenderStyle* parentStyle, RenderRegion* regionForStyling) { ASSERT(!element() || document() == newDocument); if (newElement) m_elementContext = ElementResolveContext(newElement); else m_elementContext = ElementResolveContext(); m_regionForStyling = regionForStyling; if (m_elementContext.resetStyleInheritance()) m_parentStyle = 0; else if (parentStyle) m_parentStyle = parentStyle; else if (m_elementContext.parentNode()) m_parentStyle = m_elementContext.parentNode()->renderStyle(); else m_parentStyle = 0; m_style = 0; m_elementStyleResources.clear(); m_fontDirty = false; // FIXME: StyleResolverState is never passed between documents // so we should be able to do this initialization at StyleResolverState // createion time instead of now, correct? if (Page* page = newDocument->page()) m_elementStyleResources.setDeviceScaleFactor(page->deviceScaleFactor()); } } // namespace WebCore <|endoftext|>
<commit_before>#ifdef _WIN32 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) #endif #include <iostream> #include <fstream> #include <cctype> #include <algorithm> #include <sys/stat.h> #include "file.hpp" #include "context.hpp" #include "sass2scss/sass2scss.h" namespace Sass { namespace File { using namespace std; size_t find_last_folder_separator(const string& path, size_t limit = string::npos) { size_t pos = string::npos; size_t pos_p = path.find_last_of('/', limit); size_t pos_w = string::npos; #ifdef _WIN32 pos_w = path.find_last_of('\\', limit); #endif if (pos_p != string::npos && pos_w != string::npos) { pos = max(pos_p, pos_w); } else if (pos_p != string::npos) { pos = pos_p; } else { pos = pos_w; } return pos; } string base_name(string path) { size_t pos = find_last_folder_separator(path); if (pos == string::npos) return path; else return path.substr(pos+1); } string dir_name(string path) { size_t pos = find_last_folder_separator(path); if (pos == string::npos) return ""; else return path.substr(0, pos+1); } string join_paths(string l, string r) { if (l.empty()) return r; if (r.empty()) return l; if (is_absolute_path(r)) return r; if (l[l.length()-1] != '/') l += '/'; while ((r.length() > 3) && ((r.substr(0, 3) == "../") || (r.substr(0, 3)) == "..\\")) { r = r.substr(3); size_t pos = find_last_folder_separator(l, l.length() - 2); l = l.substr(0, pos == string::npos ? pos : pos + 1); } return l + r; } bool is_absolute_path(const string& path) { if (path[0] == '/') return true; // TODO: UN-HACKIFY THIS #ifdef _WIN32 if (path.length() >= 2 && isalpha(path[0]) && path[1] == ':') return true; #endif return false; } string make_absolute_path(const string& path, const string& cwd) { return (is_absolute_path(path) ? path : join_paths(cwd, path)); } string resolve_relative_path(const string& uri, const string& base, const string& cwd) { string absolute_uri = make_absolute_path(uri, cwd); string absolute_base = make_absolute_path(base, cwd); string stripped_uri = ""; string stripped_base = ""; size_t index = 0; size_t minSize = min(absolute_uri.size(), absolute_base.size()); for (size_t i = 0; i < minSize; ++i) { if (absolute_uri[i] != absolute_base[i]) break; if (absolute_uri[i] == '/') index = i + 1; } for (size_t i = index; i < absolute_uri.size(); ++i) { stripped_uri += absolute_uri[i]; } for (size_t i = index; i < absolute_base.size(); ++i) { stripped_base += absolute_base[i]; } size_t directories = 0; for (size_t i = 0; i < stripped_base.size(); ++i) { if (stripped_base[i] == '/') ++directories; } string result = ""; for (size_t i = 0; i < directories; ++i) { result += "../"; } result += stripped_uri; return result; } char* resolve_and_load(string path, string& real_path) { // Resolution order for ambiguous imports: // (1) filename as given // (2) underscore + given // (3) underscore + given + extension // (4) given + extension char* contents = 0; real_path = path; // if the file isn't found with the given filename ... if (!(contents = read_file(real_path))) { string dir(dir_name(path)); string base(base_name(path)); string _base("_" + base); real_path = dir + _base; // if the file isn't found with '_' + filename ... if (!(contents = read_file(real_path))) { string _base_scss(_base + ".scss"); real_path = dir + _base_scss; // if the file isn't found with '_' + filename + ".scss" ... if (!(contents = read_file(real_path))) { string base_scss(base + ".scss"); // try filename + ".scss" as the last resort real_path = dir + base_scss; contents = read_file(real_path); } } } return contents; } char* read_file(string path) { struct stat st; if (stat(path.c_str(), &st) == -1 || S_ISDIR(st.st_mode)) return 0; ifstream file(path.c_str(), ios::in | ios::binary | ios::ate); string extension; if (path.length() > 5) { extension = path.substr(path.length() - 5, 5); } char* contents = 0; if (file.is_open()) { size_t size = file.tellg(); contents = new char[size + 1]; // extra byte for the null char file.seekg(0, ios::beg); file.read(contents, size); contents[size] = '\0'; file.close(); } if (extension == ".sass") { char * converted = ocbnet::sass2scss(contents, SASS2SCSS_PRETTIFY_1); delete[] contents; // free the sass content return converted; // should be freed by caller } else { return contents; } } } } <commit_msg>Implements indented syntax for resolve_and_load function<commit_after>#ifdef _WIN32 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) #endif #include <iostream> #include <fstream> #include <cctype> #include <algorithm> #include <sys/stat.h> #include "file.hpp" #include "context.hpp" #include "sass2scss/sass2scss.h" namespace Sass { namespace File { using namespace std; size_t find_last_folder_separator(const string& path, size_t limit = string::npos) { size_t pos = string::npos; size_t pos_p = path.find_last_of('/', limit); size_t pos_w = string::npos; #ifdef _WIN32 pos_w = path.find_last_of('\\', limit); #endif if (pos_p != string::npos && pos_w != string::npos) { pos = max(pos_p, pos_w); } else if (pos_p != string::npos) { pos = pos_p; } else { pos = pos_w; } return pos; } string base_name(string path) { size_t pos = find_last_folder_separator(path); if (pos == string::npos) return path; else return path.substr(pos+1); } string dir_name(string path) { size_t pos = find_last_folder_separator(path); if (pos == string::npos) return ""; else return path.substr(0, pos+1); } string join_paths(string l, string r) { if (l.empty()) return r; if (r.empty()) return l; if (is_absolute_path(r)) return r; if (l[l.length()-1] != '/') l += '/'; while ((r.length() > 3) && ((r.substr(0, 3) == "../") || (r.substr(0, 3)) == "..\\")) { r = r.substr(3); size_t pos = find_last_folder_separator(l, l.length() - 2); l = l.substr(0, pos == string::npos ? pos : pos + 1); } return l + r; } bool is_absolute_path(const string& path) { if (path[0] == '/') return true; // TODO: UN-HACKIFY THIS #ifdef _WIN32 if (path.length() >= 2 && isalpha(path[0]) && path[1] == ':') return true; #endif return false; } string make_absolute_path(const string& path, const string& cwd) { return (is_absolute_path(path) ? path : join_paths(cwd, path)); } string resolve_relative_path(const string& uri, const string& base, const string& cwd) { string absolute_uri = make_absolute_path(uri, cwd); string absolute_base = make_absolute_path(base, cwd); string stripped_uri = ""; string stripped_base = ""; size_t index = 0; size_t minSize = min(absolute_uri.size(), absolute_base.size()); for (size_t i = 0; i < minSize; ++i) { if (absolute_uri[i] != absolute_base[i]) break; if (absolute_uri[i] == '/') index = i + 1; } for (size_t i = index; i < absolute_uri.size(); ++i) { stripped_uri += absolute_uri[i]; } for (size_t i = index; i < absolute_base.size(); ++i) { stripped_base += absolute_base[i]; } size_t directories = 0; for (size_t i = 0; i < stripped_base.size(); ++i) { if (stripped_base[i] == '/') ++directories; } string result = ""; for (size_t i = 0; i < directories; ++i) { result += "../"; } result += stripped_uri; return result; } char* resolve_and_load(string path, string& real_path) { // Resolution order for ambiguous imports: // (1) filename as given // (2) underscore + given // (3) underscore + given + extension // (4) given + extension char* contents = 0; real_path = path; // if the file isn't found with the given filename ... if (!(contents = read_file(real_path))) { string dir(dir_name(path)); string base(base_name(path)); string _base("_" + base); real_path = dir + _base; // if the file isn't found with '_' + filename ... if (!(contents = read_file(real_path))) { string _base_scss(_base + ".scss"); real_path = dir + _base_scss; // if the file isn't found with '_' + filename + ".scss" ... if (!(contents = read_file(real_path))) { string _base_sass(_base + ".sass"); real_path = dir + _base_sass; // if the file isn't found with '_' + filename + ".sass" ... if (!(contents = read_file(real_path))) { string base_scss(base + ".scss"); real_path = dir + base_scss; // if the file isn't found with filename + ".scss" ... if (!(contents = read_file(real_path))) { string base_sass(base + ".sass"); real_path = dir + base_sass; // if the file isn't found with filename + ".sass" ... if (!(contents = read_file(real_path))) { // default back to scss version real_path = dir + base_scss; } } } } } } string extension; if (real_path.length() > 5) { extension = real_path.substr(real_path.length() - 5, 5); } for(int i=0; i<extension.size();++i) extension[i] = tolower(extension[i]); if (extension == ".sass" && contents != 0) { char * converted = ocbnet::sass2scss(contents, SASS2SCSS_PRETTIFY_1); delete[] contents; // free the indented contents return converted; // should be freed by caller } else { return contents; } } char* read_file(string path) { struct stat st; if (stat(path.c_str(), &st) == -1 || S_ISDIR(st.st_mode)) return 0; ifstream file(path.c_str(), ios::in | ios::binary | ios::ate); string extension; if (path.length() > 5) { extension = path.substr(path.length() - 5, 5); } char* contents = 0; if (file.is_open()) { size_t size = file.tellg(); contents = new char[size + 1]; // extra byte for the null char file.seekg(0, ios::beg); file.read(contents, size); contents[size] = '\0'; file.close(); } for(int i=0; i<extension.size();++i) extension[i] = tolower(extension[i]); if (extension == ".sass" && contents != 0) { char * converted = ocbnet::sass2scss(contents, SASS2SCSS_PRETTIFY_1); delete[] contents; // free the indented contents return converted; // should be freed by caller } else { return contents; } } } } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 NEC Corporation * All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this * distribution, and is available at http://www.eclipse.org/legal/epl-v10.html */ #include <vtn_drv_module.hh> namespace unc { namespace driver { /** * @brief : constructor */ VtnDrvIntf::VtnDrvIntf(const pfc_modattr_t* attr) : Module(attr), taskq_(NULL), ctrl_inst_(NULL) { ODC_FUNC_TRACE; } /** * VtnDrvIntf(): * @brief : destructor */ VtnDrvIntf::~VtnDrvIntf() { ODC_FUNC_TRACE; std::map <unc_key_type_t, unc::driver::KtHandler*> ::iterator map_it; for (map_it = map_kt_.begin(); map_it != map_kt_.end(); map_it++) { delete (map_it)->second; } map_kt_.clear(); } /** * @brief : This Function is called to load the vtndrvintf module * @param[in] : None * @retval : PFC_FALSE/PFC_TRUE */ pfc_bool_t VtnDrvIntf::init(void) { ODC_FUNC_TRACE; uint32_t concurrency = 1; taskq_ = pfc::core::TaskQueue::create(concurrency); ControllerFramework *ctrl_inst_= new ControllerFramework(taskq_); PFC_ASSERT(ctrl_inst_ != NULL); set_controller_instance(ctrl_inst_); // Initialize KT_Handler_Instance KtHandler* ctrl_req = new unc::driver::KtRequestHandler<key_ctr_t, val_ctr_t, controller_command>(NULL); if (ctrl_req == NULL) { pfc_log_error("controller request handler is NULL"); return PFC_FALSE; } map_kt_.insert(std::pair<unc_key_type_t, unc::driver::KtHandler*>( UNC_KT_CONTROLLER, ctrl_req)); KtHandler* kt_root_req = new unc::driver::KtRequestHandler<key_root_t, val_root_t, unc::driver::root_driver_command>(&map_kt_); if (kt_root_req == NULL) { pfc_log_error("KT_ROOT request handler is NULL"); return PFC_FALSE; } map_kt_.insert(std::pair<unc_key_type_t, unc::driver::KtHandler*>( UNC_KT_ROOT, kt_root_req)); KtHandler* vtn_req = new unc::driver::KtRequestHandler<key_vtn_t, val_vtn_t, unc::driver::vtn_driver_command>(NULL); if (vtn_req == NULL) { pfc_log_error("vtn request handler is NULL"); return PFC_FALSE; } map_kt_.insert(std::pair<unc_key_type_t, unc::driver::KtHandler*>(UNC_KT_VTN, vtn_req)); KtHandler* vbr_req = new unc::driver::KtRequestHandler<key_vbr_t, val_vbr_t, unc::driver::vbr_driver_command> (NULL); if (vbr_req == NULL) { pfc_log_error("vbr request handler is NULL"); return PFC_FALSE; } map_kt_.insert(std::pair<unc_key_type_t, unc::driver::KtHandler*>( UNC_KT_VBRIDGE, vbr_req)); KtHandler* vbrif_req = new unc::driver::KtRequestHandler<key_vbr_if_t, pfcdrv_val_vbr_if_t, unc::driver::vbrif_driver_command>(NULL); if (vbrif_req == NULL) { pfc_log_error("vbr interface request handler is NULL"); return PFC_FALSE; } map_kt_.insert(std::pair<unc_key_type_t, unc::driver::KtHandler*>( UNC_KT_VBR_IF, vbrif_req)); KtHandler* vbrvlanmap_req = new unc::driver::KtRequestHandler<key_vlan_map_t, val_vlan_map_t, unc::driver::vbrvlanmap_driver_command> (NULL); if (vbrvlanmap_req == NULL) { pfc_log_error("vbrvlanmap request handler is NULL"); return PFC_FALSE; } map_kt_.insert(std::pair<unc_key_type_t, unc::driver::KtHandler*>( UNC_KT_VBR_VLANMAP, vbrvlanmap_req)); unc::tclib::TcLibModule* tclib_obj = static_cast<unc::tclib::TcLibModule*>(pfc::core::Module::getInstance( "tclib")); if (tclib_obj == NULL) { pfc_log_error("tclib getInstance failed"); return PFC_FALSE; } tclib_obj->TcLibRegisterHandler(new DriverTxnInterface(ctrl_inst_, map_kt_)); return PFC_TRUE; } /** * @brief : This Function is called to unload the vtndrvintf module * @param[in] : None * @retval : PFC_TRUE */ pfc_bool_t VtnDrvIntf::fini(void) { ODC_FUNC_TRACE; if (taskq_) { delete taskq_; taskq_ = NULL; } if (ctrl_inst_) { delete ctrl_inst_; ctrl_inst_ = NULL; } if (!map_kt_.empty()) { map_kt_.clear(); } return PFC_TRUE; } /** * @brief : This Function recevies the ipc request and process the same * @param[in] : sess, service * @retval : PFC_IPCRESP_FATAL/PFC_IPCINT_EVSESS_OK */ pfc_ipcresp_t VtnDrvIntf::ipcService(pfc::core::ipc::ServerSession& sess, pfc_ipcid_t service) { ODC_FUNC_TRACE; pfc::core::ipc::ServerSession* p_sess=&sess; odl_drv_request_header_t request_hdr; drv_resp_code_t resp_code = DRVAPI_RESPONSE_FAILURE; memset(&request_hdr, 0, sizeof(request_hdr)); VtnDrvRetEnum result = get_request_header(p_sess, request_hdr); if (VTN_DRV_RET_SUCCESS != result) { pfc_log_error("VtnDrvIntfservice::%s Failed to get argument err=%d", PFC_FUNCNAME, result); return PFC_IPCRESP_FATAL; } if (map_kt_.empty()) { pfc_log_debug("map_kt empty"); return PFC_IPCRESP_FATAL; } KtHandler *hnd_ptr = get_kt_handler(request_hdr.key_type); if (hnd_ptr == NULL) { pfc_log_debug("Key Type Not Supported %d", request_hdr.key_type); return PFC_IPCRESP_FATAL; } resp_code = hnd_ptr->handle_request(sess, request_hdr, ctrl_inst_); if (resp_code != DRVAPI_RESPONSE_SUCCESS) { pfc_log_debug("handle_request fail for key:%d", request_hdr.key_type); return PFC_IPCRESP_FATAL; } return DRVAPI_RESPONSE_SUCCESS; } /** * @brief : This function parse the session and fills * odl_drv_request_header_t * @param[in] : sess, request_hdr * @retval : VTN_DRV_RET_FAILURE /VTN_DRV_RET_SUCCESS */ VtnDrvRetEnum VtnDrvIntf::get_request_header( pfc::core::ipc::ServerSession* sess, odl_drv_request_header_t &request_hdr) { ODC_FUNC_TRACE; PFC_ASSERT(sess != NULL); uint32_t err = 0, keytype; err = sess->getArgument(IPC_SESSION_ID_INDEX, request_hdr.header.session_id); if (err) { pfc_log_error("Failed to receive client session id: (err = %d)", err); return VTN_DRV_RET_FAILURE; } err = sess->getArgument(IPC_CONFIG_ID_INDEX, request_hdr.header.config_id); if (err) { pfc_log_error("Failed to receive configurationid: (err = %d)", err); return VTN_DRV_RET_FAILURE; } const char *ctr_name; err = sess->getArgument(IPC_CONTROLLER_ID_INDEX, ctr_name); if (err) { pfc_log_error("Failed to receive controller id: (err = %d)", err); return VTN_DRV_RET_FAILURE; } strncpy(reinterpret_cast<char*>(request_hdr.controller_name), ctr_name, sizeof(request_hdr.controller_name) - 1); const char *domain_name; err = sess->getArgument(IPC_DOMAIN_ID_INDEX, domain_name); if (err) { pfc_log_error("Failed to receive domain id: (err = %d)", err); return VTN_DRV_RET_FAILURE; } strncpy(reinterpret_cast<char*>(request_hdr.header.domain_id), domain_name, sizeof(request_hdr.header.domain_id) - 1); err = sess->getArgument(IPC_OPERATION_INDEX, request_hdr.header.operation); if (err) { pfc_log_error("Failed to receive operation: (err = %d)", err); return VTN_DRV_RET_FAILURE; } err = sess->getArgument(IPC_OPTION1_INDEX, request_hdr.header.option1); if (err) { pfc_log_error("Failed to receive option1 : (err = %d)", err); return VTN_DRV_RET_FAILURE; } err = sess->getArgument(IPC_OPTION2_INDEX, request_hdr.header.option2); if (err) { pfc_log_error("Failed to receive option2 : (err = %d)", err); return VTN_DRV_RET_FAILURE; } err = sess->getArgument(IPC_DATA_TYPE_INDEX, request_hdr.header.data_type); if (err) { pfc_log_error("Failed to receive data_type: (err = %d)", err); return VTN_DRV_RET_FAILURE; } err = sess->getArgument(IPC_KEY_TYPE_INDEX, keytype); if (err) { pfc_log_error("Failed to receive key type: (err = %d)", err); return VTN_DRV_RET_FAILURE; } request_hdr.key_type=(unc_key_type_t)keytype; pfc_log_debug("Keytype is %d", request_hdr.key_type); return VTN_DRV_RET_SUCCESS; } /** * @brief : This Function returns the kt_handler for * the appropriate key types * @param[in] : key type * @retval : KtHandler* */ KtHandler* VtnDrvIntf::get_kt_handler(unc_key_type_t kt) { std::map <unc_key_type_t, unc::driver::KtHandler*>:: iterator iter = map_kt_.begin(); iter = map_kt_.find(kt); if (iter != map_kt_.end()) { return iter->second; } return NULL; } /** * @brief : This Function is called to register the driver handler * with respect to the controller type * @param[in] : *drvobj * @retval : VTN_DRV_RET_SUCCESS */ VtnDrvRetEnum VtnDrvIntf:: register_driver(driver *drv_obj) { if (drv_obj == NULL) { pfc_log_error("driver handler is NULL"); return VTN_DRV_RET_FAILURE; } unc_keytype_ctrtype_t ctr_type = drv_obj->get_controller_type(); ctrl_inst_->RegisterDriver(ctr_type, drv_obj); return VTN_DRV_RET_SUCCESS; } } // namespace driver } // namespace unc PFC_MODULE_IPC_DECL(unc::driver::VtnDrvIntf, 3); <commit_msg>Set IPC timeout as infinite for Audit Operations<commit_after>/* * Copyright (c) 2013 NEC Corporation * All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this * distribution, and is available at http://www.eclipse.org/legal/epl-v10.html */ #include <vtn_drv_module.hh> namespace unc { namespace driver { /** * @brief : constructor */ VtnDrvIntf::VtnDrvIntf(const pfc_modattr_t* attr) : Module(attr), taskq_(NULL), ctrl_inst_(NULL) { ODC_FUNC_TRACE; } /** * VtnDrvIntf(): * @brief : destructor */ VtnDrvIntf::~VtnDrvIntf() { ODC_FUNC_TRACE; std::map <unc_key_type_t, unc::driver::KtHandler*> ::iterator map_it; for (map_it = map_kt_.begin(); map_it != map_kt_.end(); map_it++) { delete (map_it)->second; } map_kt_.clear(); } /** * @brief : This Function is called to load the vtndrvintf module * @param[in] : None * @retval : PFC_FALSE/PFC_TRUE */ pfc_bool_t VtnDrvIntf::init(void) { ODC_FUNC_TRACE; uint32_t concurrency = 1; taskq_ = pfc::core::TaskQueue::create(concurrency); ControllerFramework *ctrl_inst_= new ControllerFramework(taskq_); PFC_ASSERT(ctrl_inst_ != NULL); set_controller_instance(ctrl_inst_); // Initialize KT_Handler_Instance KtHandler* ctrl_req = new unc::driver::KtRequestHandler<key_ctr_t, val_ctr_t, controller_command>(NULL); if (ctrl_req == NULL) { pfc_log_error("controller request handler is NULL"); return PFC_FALSE; } map_kt_.insert(std::pair<unc_key_type_t, unc::driver::KtHandler*>( UNC_KT_CONTROLLER, ctrl_req)); KtHandler* kt_root_req = new unc::driver::KtRequestHandler<key_root_t, val_root_t, unc::driver::root_driver_command>(&map_kt_); if (kt_root_req == NULL) { pfc_log_error("KT_ROOT request handler is NULL"); return PFC_FALSE; } map_kt_.insert(std::pair<unc_key_type_t, unc::driver::KtHandler*>( UNC_KT_ROOT, kt_root_req)); KtHandler* vtn_req = new unc::driver::KtRequestHandler<key_vtn_t, val_vtn_t, unc::driver::vtn_driver_command>(NULL); if (vtn_req == NULL) { pfc_log_error("vtn request handler is NULL"); return PFC_FALSE; } map_kt_.insert(std::pair<unc_key_type_t, unc::driver::KtHandler*>(UNC_KT_VTN, vtn_req)); KtHandler* vbr_req = new unc::driver::KtRequestHandler<key_vbr_t, val_vbr_t, unc::driver::vbr_driver_command> (NULL); if (vbr_req == NULL) { pfc_log_error("vbr request handler is NULL"); return PFC_FALSE; } map_kt_.insert(std::pair<unc_key_type_t, unc::driver::KtHandler*>( UNC_KT_VBRIDGE, vbr_req)); KtHandler* vbrif_req = new unc::driver::KtRequestHandler<key_vbr_if_t, pfcdrv_val_vbr_if_t, unc::driver::vbrif_driver_command>(NULL); if (vbrif_req == NULL) { pfc_log_error("vbr interface request handler is NULL"); return PFC_FALSE; } map_kt_.insert(std::pair<unc_key_type_t, unc::driver::KtHandler*>( UNC_KT_VBR_IF, vbrif_req)); KtHandler* vbrvlanmap_req = new unc::driver::KtRequestHandler<key_vlan_map_t, val_vlan_map_t, unc::driver::vbrvlanmap_driver_command> (NULL); if (vbrvlanmap_req == NULL) { pfc_log_error("vbrvlanmap request handler is NULL"); return PFC_FALSE; } map_kt_.insert(std::pair<unc_key_type_t, unc::driver::KtHandler*>( UNC_KT_VBR_VLANMAP, vbrvlanmap_req)); unc::tclib::TcLibModule* tclib_obj = static_cast<unc::tclib::TcLibModule*>(pfc::core::Module::getInstance( "tclib")); if (tclib_obj == NULL) { pfc_log_error("tclib getInstance failed"); return PFC_FALSE; } tclib_obj->TcLibRegisterHandler(new DriverTxnInterface(ctrl_inst_, map_kt_)); return PFC_TRUE; } /** * @brief : This Function is called to unload the vtndrvintf module * @param[in] : None * @retval : PFC_TRUE */ pfc_bool_t VtnDrvIntf::fini(void) { ODC_FUNC_TRACE; if (taskq_) { delete taskq_; taskq_ = NULL; } if (ctrl_inst_) { delete ctrl_inst_; ctrl_inst_ = NULL; } if (!map_kt_.empty()) { map_kt_.clear(); } return PFC_TRUE; } /** * @brief : This Function recevies the ipc request and process the same * @param[in] : sess, service * @retval : PFC_IPCRESP_FATAL/PFC_IPCINT_EVSESS_OK */ pfc_ipcresp_t VtnDrvIntf::ipcService(pfc::core::ipc::ServerSession& sess, pfc_ipcid_t service) { ODC_FUNC_TRACE; pfc::core::ipc::ServerSession* p_sess=&sess; odl_drv_request_header_t request_hdr; drv_resp_code_t resp_code = DRVAPI_RESPONSE_FAILURE; memset(&request_hdr, 0, sizeof(request_hdr)); VtnDrvRetEnum result = get_request_header(p_sess, request_hdr); if (VTN_DRV_RET_SUCCESS != result) { pfc_log_error("VtnDrvIntfservice::%s Failed to get argument err=%d", PFC_FUNCNAME, result); return PFC_IPCRESP_FATAL; } if (map_kt_.empty()) { pfc_log_debug("map_kt empty"); return PFC_IPCRESP_FATAL; } KtHandler *hnd_ptr = get_kt_handler(request_hdr.key_type); if (hnd_ptr == NULL) { pfc_log_debug("Key Type Not Supported %d", request_hdr.key_type); return PFC_IPCRESP_FATAL; } // Set Timeout as infinite for audit operation if (request_hdr.key_type == UNC_KT_ROOT) { sess.setTimeout(NULL); } resp_code = hnd_ptr->handle_request(sess, request_hdr, ctrl_inst_); if (resp_code != DRVAPI_RESPONSE_SUCCESS) { pfc_log_debug("handle_request fail for key:%d", request_hdr.key_type); return PFC_IPCRESP_FATAL; } return DRVAPI_RESPONSE_SUCCESS; } /** * @brief : This function parse the session and fills * odl_drv_request_header_t * @param[in] : sess, request_hdr * @retval : VTN_DRV_RET_FAILURE /VTN_DRV_RET_SUCCESS */ VtnDrvRetEnum VtnDrvIntf::get_request_header( pfc::core::ipc::ServerSession* sess, odl_drv_request_header_t &request_hdr) { ODC_FUNC_TRACE; PFC_ASSERT(sess != NULL); uint32_t err = 0, keytype; err = sess->getArgument(IPC_SESSION_ID_INDEX, request_hdr.header.session_id); if (err) { pfc_log_error("Failed to receive client session id: (err = %d)", err); return VTN_DRV_RET_FAILURE; } err = sess->getArgument(IPC_CONFIG_ID_INDEX, request_hdr.header.config_id); if (err) { pfc_log_error("Failed to receive configurationid: (err = %d)", err); return VTN_DRV_RET_FAILURE; } const char *ctr_name; err = sess->getArgument(IPC_CONTROLLER_ID_INDEX, ctr_name); if (err) { pfc_log_error("Failed to receive controller id: (err = %d)", err); return VTN_DRV_RET_FAILURE; } strncpy(reinterpret_cast<char*>(request_hdr.controller_name), ctr_name, sizeof(request_hdr.controller_name) - 1); const char *domain_name; err = sess->getArgument(IPC_DOMAIN_ID_INDEX, domain_name); if (err) { pfc_log_error("Failed to receive domain id: (err = %d)", err); return VTN_DRV_RET_FAILURE; } strncpy(reinterpret_cast<char*>(request_hdr.header.domain_id), domain_name, sizeof(request_hdr.header.domain_id) - 1); err = sess->getArgument(IPC_OPERATION_INDEX, request_hdr.header.operation); if (err) { pfc_log_error("Failed to receive operation: (err = %d)", err); return VTN_DRV_RET_FAILURE; } err = sess->getArgument(IPC_OPTION1_INDEX, request_hdr.header.option1); if (err) { pfc_log_error("Failed to receive option1 : (err = %d)", err); return VTN_DRV_RET_FAILURE; } err = sess->getArgument(IPC_OPTION2_INDEX, request_hdr.header.option2); if (err) { pfc_log_error("Failed to receive option2 : (err = %d)", err); return VTN_DRV_RET_FAILURE; } err = sess->getArgument(IPC_DATA_TYPE_INDEX, request_hdr.header.data_type); if (err) { pfc_log_error("Failed to receive data_type: (err = %d)", err); return VTN_DRV_RET_FAILURE; } err = sess->getArgument(IPC_KEY_TYPE_INDEX, keytype); if (err) { pfc_log_error("Failed to receive key type: (err = %d)", err); return VTN_DRV_RET_FAILURE; } request_hdr.key_type=(unc_key_type_t)keytype; pfc_log_debug("Keytype is %d", request_hdr.key_type); return VTN_DRV_RET_SUCCESS; } /** * @brief : This Function returns the kt_handler for * the appropriate key types * @param[in] : key type * @retval : KtHandler* */ KtHandler* VtnDrvIntf::get_kt_handler(unc_key_type_t kt) { std::map <unc_key_type_t, unc::driver::KtHandler*>:: iterator iter = map_kt_.begin(); iter = map_kt_.find(kt); if (iter != map_kt_.end()) { return iter->second; } return NULL; } /** * @brief : This Function is called to register the driver handler * with respect to the controller type * @param[in] : *drvobj * @retval : VTN_DRV_RET_SUCCESS */ VtnDrvRetEnum VtnDrvIntf:: register_driver(driver *drv_obj) { if (drv_obj == NULL) { pfc_log_error("driver handler is NULL"); return VTN_DRV_RET_FAILURE; } unc_keytype_ctrtype_t ctr_type = drv_obj->get_controller_type(); ctrl_inst_->RegisterDriver(ctr_type, drv_obj); return VTN_DRV_RET_SUCCESS; } } // namespace driver } // namespace unc PFC_MODULE_IPC_DECL(unc::driver::VtnDrvIntf, 3); <|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 "GLSL/OgreGLSLPreprocessor.h" #include "OgreString.h" #include <gtest/gtest.h> using namespace Ogre; TEST(CPreprocessorTests, MacroBraces) { CPreprocessor prep; String src = "#define MY_MACRO(x) print( x )\n" "MY_MACRO( (myValue * 3) * 2)"; size_t olen; char* out = prep.Parse(src.c_str(), src.size(), olen); String str(out, olen); StringUtil::trim(str); EXPECT_EQ(str, "print( (myValue * 3) * 2 )"); free(out); } TEST(CPreprocessorTests, ElseIf) { CPreprocessor prep; String src = "#define A 0\n" "#if A == 1\n" "value is 1\n" "#elif A == 0\n" "value is 0\n" "#endif"; size_t olen; char* out = prep.Parse(src.c_str(), src.size(), olen); String str(out, olen); StringUtil::trim(str); EXPECT_EQ(str, "value is 0"); free(out); } <commit_msg>Tests: add MacroExpansion Test<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 "GLSL/OgreGLSLPreprocessor.h" #include "OgreString.h" #include <gtest/gtest.h> using namespace Ogre; TEST(CPreprocessorTests, MacroBraces) { CPreprocessor prep; String src = "#define MY_MACRO(x) print( x )\n" "MY_MACRO( (myValue * 3) * 2)"; size_t olen; char* out = prep.Parse(src.c_str(), src.size(), olen); String str(out, olen); StringUtil::trim(str); EXPECT_EQ(str, "print( (myValue * 3) * 2 )"); free(out); } TEST(CPreprocessorTests, MacroExpansion) { CPreprocessor prep; String src = "#define mad( a, b, c ) fma( a, b, c )\n" "mad( x.s, y, a )"; size_t olen; char* out = prep.Parse(src.c_str(), src.size(), olen); String str(out, olen); StringUtil::trim(str); EXPECT_EQ(str, "fma( x.s, y, a )"); free(out); } TEST(CPreprocessorTests, ElseIf) { CPreprocessor prep; String src = "#define A 0\n" "#if A == 1\n" "value is 1\n" "#elif A == 0\n" "value is 0\n" "#endif"; size_t olen; char* out = prep.Parse(src.c_str(), src.size(), olen); String str(out, olen); StringUtil::trim(str); EXPECT_EQ(str, "value is 0"); free(out); } <|endoftext|>
<commit_before>//===--- TerminalReaderWin.cpp - Input From Windows Console -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the interface for reading from Window's cmd.exe console. // // Axel Naumann <axel@cern.ch>, 2011-05-12 //===----------------------------------------------------------------------===// #ifdef WIN32 #include "textinput/StreamReaderWin.h" #include <io.h> #include <stdio.h> #include <Windows.h> // MSVC 7.1 is missing these definitions: #ifndef ENABLE_QUICK_EDIT_MODE # define ENABLE_QUICK_EDIT_MODE 0x0040 #endif #ifndef ENABLE_EXTENDED_FLAGS # define ENABLE_EXTENDED_FLAGS 0x0080 #endif #ifndef ENABLE_LINE_INPUT # define ENABLE_LINE_INPUT 0x0002 #endif #ifndef ENABLE_PROCESSED_INPUT # define ENABLE_PROCESSED_INPUT 0x0001 #endif #ifndef ENABLE_ECHO_INPUT # define ENABLE_ECHO_INPUT 0x0004 #endif #ifndef ENABLE_INSERT_MODE # define ENABLE_INSERT_MODE 0x0020 #endif // End MSVC 7.1 quirks namespace textinput { StreamReaderWin::StreamReaderWin(): fHaveInputFocus(false), fIsConsole(true), fOldMode(0), fMyMode(0) { fIn = ::GetStdHandle(STD_INPUT_HANDLE); fIsConsole = ::GetConsoleMode(fIn, &fOldMode) != 0; fMyMode = fOldMode | ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS; fMyMode = fOldMode & ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT | ENABLE_INSERT_MODE); } StreamReaderWin::~StreamReaderWin() {} void StreamReaderWin::GrabInputFocus() { if (fHaveInputFocus) return; if (fIsConsole && !SetConsoleMode(fIn, fMyMode)) { fIsConsole = false; } fHaveInputFocus = true; } void StreamReaderWin::ReleaseInputFocus() { if (!fHaveInputFocus) return; if (fIsConsole && !SetConsoleMode(fIn, fOldMode)) { fIsConsole = false; } fHaveInputFocus = false; } bool StreamReaderWin::HavePendingInput() { DWORD ret = ::WaitForSingleObject(fIn, 0); if (ret == WAIT_FAILED) { HandleError("waiting for console input"); // We don't know. Better block rather than veto input: return true; } return ret == WAIT_OBJECT_0; } bool StreamReaderWin::ReadInput(size_t& nRead, InputData& in) { DWORD NRead = 0; char C; if (fIsConsole) { INPUT_RECORD buf; if (!::ReadConsoleInput(fIn, &buf, 1, &NRead)) { HandleError("reading console input"); return false; } switch (buf.EventType) { case KEY_EVENT: { if (!buf.Event.KeyEvent.bKeyDown) return false; WORD Key = buf.Event.KeyEvent.wVirtualKeyCode; if (buf.Event.KeyEvent.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) { in.SetModifier(InputData::kModCtrl); } if ((Key >= 0x30 && Key <= 0x5A /*0-Z*/) || (Key >= VK_NUMPAD0 && Key <= VK_DIVIDE) || (Key >= VK_OEM_PLUS && Key <= VK_OEM_102) || Key == VK_SPACE) { C = buf.Event.KeyEvent.uChar.AsciiChar; if (buf.Event.KeyEvent.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) { // C is already 1.. } } else { switch (Key) { case VK_BACK: in.SetExtended(InputData::kEIBackSpace); break; case VK_TAB: in.SetExtended(InputData::kEITab); break; case VK_RETURN: in.SetExtended(InputData::kEIEnter); break; case VK_ESCAPE: in.SetExtended(InputData::kEIEsc); break; case VK_PRIOR: in.SetExtended(InputData::kEIPgUp); break; case VK_NEXT: in.SetExtended(InputData::kEIPgDown); break; case VK_END: in.SetExtended(InputData::kEIEnd); break; case VK_HOME: in.SetExtended(InputData::kEIHome); break; case VK_LEFT: in.SetExtended(InputData::kEILeft); break; case VK_UP: in.SetExtended(InputData::kEIUp); break; case VK_RIGHT: in.SetExtended(InputData::kEIRight); break; case VK_DOWN: in.SetExtended(InputData::kEIDown); break; case VK_INSERT: in.SetExtended(InputData::kEIIns); break; case VK_DELETE: in.SetExtended(InputData::kEIDel); break; case VK_F1: in.SetExtended(InputData::kEIF1); break; case VK_F2: in.SetExtended(InputData::kEIF2); break; case VK_F3: in.SetExtended(InputData::kEIF3); break; case VK_F4: in.SetExtended(InputData::kEIF4); break; case VK_F5: in.SetExtended(InputData::kEIF5); break; case VK_F6: in.SetExtended(InputData::kEIF6); break; case VK_F7: in.SetExtended(InputData::kEIF7); break; case VK_F8: in.SetExtended(InputData::kEIF8); break; case VK_F9: in.SetExtended(InputData::kEIF9); break; case VK_F10: in.SetExtended(InputData::kEIF10); break; case VK_F11: in.SetExtended(InputData::kEIF11); break; case VK_F12: in.SetExtended(InputData::kEIF12); break; default: in.SetExtended(InputData::kEIUninitialized); return false; } return true; } break; } case WINDOW_BUFFER_SIZE_EVENT: in.SetExtended(InputData::kEIResizeEvent); ++nRead; return true; break; default: return false; } } else { if (!::ReadFile(fIn, &C, 1, &NRead, NULL)) { HandleError("reading file input"); return false; } } HandleKeyEvent(C, in); ++nRead; return true; } void StreamReaderWin::HandleError(const char* Where) const { DWORD Err = GetLastError(); LPVOID MsgBuf = 0; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, Err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &MsgBuf, 0, NULL); printf("Error %d in textinput::StreamReaderWin %s: %s\n", Err, Where, MsgBuf); LocalFree(MsgBuf); } void StreamReaderWin::HandleKeyEvent(unsigned char C, InputData& in) { if (isprint(C)) { in.SetRaw(C); } else if (C < 32) { in.SetRaw(C); in.SetModifier(InputData::kModCtrl); } else { // woohoo, what's that?! in.SetRaw(C); } } } #endif // WIN32 <commit_msg>Semicolon and colon are fine characters, too: accept them as character input.<commit_after>//===--- TerminalReaderWin.cpp - Input From Windows Console -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the interface for reading from Window's cmd.exe console. // // Axel Naumann <axel@cern.ch>, 2011-05-12 //===----------------------------------------------------------------------===// #ifdef WIN32 #include "textinput/StreamReaderWin.h" #include <io.h> #include <stdio.h> #include <Windows.h> // MSVC 7.1 is missing these definitions: #ifndef ENABLE_QUICK_EDIT_MODE # define ENABLE_QUICK_EDIT_MODE 0x0040 #endif #ifndef ENABLE_EXTENDED_FLAGS # define ENABLE_EXTENDED_FLAGS 0x0080 #endif #ifndef ENABLE_LINE_INPUT # define ENABLE_LINE_INPUT 0x0002 #endif #ifndef ENABLE_PROCESSED_INPUT # define ENABLE_PROCESSED_INPUT 0x0001 #endif #ifndef ENABLE_ECHO_INPUT # define ENABLE_ECHO_INPUT 0x0004 #endif #ifndef ENABLE_INSERT_MODE # define ENABLE_INSERT_MODE 0x0020 #endif // End MSVC 7.1 quirks namespace textinput { StreamReaderWin::StreamReaderWin(): fHaveInputFocus(false), fIsConsole(true), fOldMode(0), fMyMode(0) { fIn = ::GetStdHandle(STD_INPUT_HANDLE); fIsConsole = ::GetConsoleMode(fIn, &fOldMode) != 0; fMyMode = fOldMode | ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS; fMyMode = fOldMode & ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT | ENABLE_ECHO_INPUT | ENABLE_INSERT_MODE); } StreamReaderWin::~StreamReaderWin() {} void StreamReaderWin::GrabInputFocus() { if (fHaveInputFocus) return; if (fIsConsole && !SetConsoleMode(fIn, fMyMode)) { fIsConsole = false; } fHaveInputFocus = true; } void StreamReaderWin::ReleaseInputFocus() { if (!fHaveInputFocus) return; if (fIsConsole && !SetConsoleMode(fIn, fOldMode)) { fIsConsole = false; } fHaveInputFocus = false; } bool StreamReaderWin::HavePendingInput() { DWORD ret = ::WaitForSingleObject(fIn, 0); if (ret == WAIT_FAILED) { HandleError("waiting for console input"); // We don't know. Better block rather than veto input: return true; } return ret == WAIT_OBJECT_0; } bool StreamReaderWin::ReadInput(size_t& nRead, InputData& in) { DWORD NRead = 0; char C; if (fIsConsole) { INPUT_RECORD buf; if (!::ReadConsoleInput(fIn, &buf, 1, &NRead)) { HandleError("reading console input"); return false; } switch (buf.EventType) { case KEY_EVENT: { if (!buf.Event.KeyEvent.bKeyDown) return false; WORD Key = buf.Event.KeyEvent.wVirtualKeyCode; if (buf.Event.KeyEvent.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) { in.SetModifier(InputData::kModCtrl); } if ((Key >= 0x30 && Key <= 0x5A /*0-Z*/) || (Key >= VK_NUMPAD0 && Key <= VK_DIVIDE) || (Key >= VK_OEM_1 && Key <= VK_OEM_102) || Key == VK_SPACE) { C = buf.Event.KeyEvent.uChar.AsciiChar; if (buf.Event.KeyEvent.dwControlKeyState & (LEFT_CTRL_PRESSED | RIGHT_CTRL_PRESSED)) { // C is already 1.. } } else { switch (Key) { case VK_BACK: in.SetExtended(InputData::kEIBackSpace); break; case VK_TAB: in.SetExtended(InputData::kEITab); break; case VK_RETURN: in.SetExtended(InputData::kEIEnter); break; case VK_ESCAPE: in.SetExtended(InputData::kEIEsc); break; case VK_PRIOR: in.SetExtended(InputData::kEIPgUp); break; case VK_NEXT: in.SetExtended(InputData::kEIPgDown); break; case VK_END: in.SetExtended(InputData::kEIEnd); break; case VK_HOME: in.SetExtended(InputData::kEIHome); break; case VK_LEFT: in.SetExtended(InputData::kEILeft); break; case VK_UP: in.SetExtended(InputData::kEIUp); break; case VK_RIGHT: in.SetExtended(InputData::kEIRight); break; case VK_DOWN: in.SetExtended(InputData::kEIDown); break; case VK_INSERT: in.SetExtended(InputData::kEIIns); break; case VK_DELETE: in.SetExtended(InputData::kEIDel); break; case VK_F1: in.SetExtended(InputData::kEIF1); break; case VK_F2: in.SetExtended(InputData::kEIF2); break; case VK_F3: in.SetExtended(InputData::kEIF3); break; case VK_F4: in.SetExtended(InputData::kEIF4); break; case VK_F5: in.SetExtended(InputData::kEIF5); break; case VK_F6: in.SetExtended(InputData::kEIF6); break; case VK_F7: in.SetExtended(InputData::kEIF7); break; case VK_F8: in.SetExtended(InputData::kEIF8); break; case VK_F9: in.SetExtended(InputData::kEIF9); break; case VK_F10: in.SetExtended(InputData::kEIF10); break; case VK_F11: in.SetExtended(InputData::kEIF11); break; case VK_F12: in.SetExtended(InputData::kEIF12); break; default: in.SetExtended(InputData::kEIUninitialized); return false; } return true; } break; } case WINDOW_BUFFER_SIZE_EVENT: in.SetExtended(InputData::kEIResizeEvent); ++nRead; return true; break; default: return false; } } else { if (!::ReadFile(fIn, &C, 1, &NRead, NULL)) { HandleError("reading file input"); return false; } } HandleKeyEvent(C, in); ++nRead; return true; } void StreamReaderWin::HandleError(const char* Where) const { DWORD Err = GetLastError(); LPVOID MsgBuf = 0; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, Err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &MsgBuf, 0, NULL); printf("Error %d in textinput::StreamReaderWin %s: %s\n", Err, Where, MsgBuf); LocalFree(MsgBuf); } void StreamReaderWin::HandleKeyEvent(unsigned char C, InputData& in) { if (isprint(C)) { in.SetRaw(C); } else if (C < 32) { in.SetRaw(C); in.SetModifier(InputData::kModCtrl); } else { // woohoo, what's that?! in.SetRaw(C); } } } #endif // WIN32 <|endoftext|>
<commit_before>// =========================================================================== // (C) 1996-98 Vienna University of Technology // =========================================================================== // NAME: bboxarea // TYPE: c++ code // PROJECT: Bounding Box Area // CONTENT: Computes area of 2D projection of 3D oriented bounding box // VERSION: 1.0 // =========================================================================== // AUTHORS: ds Dieter Schmalstieg // ep Erik Pojar // =========================================================================== // HISTORY: // // 19-sep-99 15:23:03 ds last modification // 01-dec-98 15:23:03 ep created // =========================================================================== #include <Inventor/Xt/SoXt.h> #include <Inventor/Xt/SoXtRenderArea.h> #include <Inventor/Xt/viewers/SoXtExaminerViewer.h> #include <Inventor/nodes/SoCone.h> #include <Inventor/nodes/SoCube.h> #include <Inventor/nodes/SoDirectionalLight.h> #include <Inventor/nodes/SoMaterial.h> #include <Inventor/nodes/SoPerspectiveCamera.h> #include <Inventor/nodes/SoSeparator.h> #include <Inventor/nodes/SoCallback.h> #include <Inventor/elements/SoCacheElement.h> #include <Inventor/elements/SoViewingMatrixElement.h> #include <Inventor/elements/SoViewVolumeElement.h> #include <Inventor/manips/SoTransformerManip.h> #include <Inventor/actions/SoSearchAction.h> #include <Inventor/actions/SoGetMatrixAction.h> #include <Inventor/actions/SoGetBoundingBoxAction.h> #include <Inventor/SbLinear.h> //---------------------------------------------------------------------------- // SAMPLE CODE STARTS HERE //---------------------------------------------------------------------------- // NOTE: This sample program requires OPEN INVENTOR! //indexlist: this table stores the 64 possible cases of classification of //the eyepoint with respect to the 6 defining planes of the bbox (2^6=64) //only 26 (3^3-1, where 1 is "inside" cube) of these cases are valid. //the first 6 numbers in each row are the indices of the bbox vertices that //form the outline of which we want to compute the area (counterclockwise //ordering), the 7th entry means the number of vertices in the outline. //there are 6 cases with a single face and and a 4-vertex outline, and //20 cases with 2 or 3 faces and a 6-vertex outline. a value of 0 indicates //an invalid case. const int indexlist[64][7] = { {-1,-1,-1,-1,-1,-1, 0}, // 0 inside { 0, 4, 7, 3,-1,-1, 4}, // 1 left { 1, 2, 6, 5,-1,-1, 4}, // 2 right {-1,-1,-1,-1,-1,-1, 0}, // 3 - { 0, 1, 5, 4,-1,-1, 4}, // 4 bottom { 0, 1, 5, 4, 7, 3, 6}, // 5 bottom, left { 0, 1, 2, 6, 5, 4, 6}, // 6 bottom, right {-1,-1,-1,-1,-1,-1, 0}, // 7 - { 2, 3, 7, 6,-1,-1, 4}, // 8 top { 0, 4, 7, 6, 2, 3, 6}, // 9 top, left { 1, 2, 3, 7, 6, 5, 6}, //10 top, right {-1,-1,-1,-1,-1,-1, 0}, //11 - {-1,-1,-1,-1,-1,-1, 0}, //12 - {-1,-1,-1,-1,-1,-1, 0}, //13 - {-1,-1,-1,-1,-1,-1, 0}, //14 - {-1,-1,-1,-1,-1,-1, 0}, //15 - { 0, 3, 2, 1,-1,-1, 4}, //16 front { 0, 4, 7, 3, 2, 1, 6}, //17 front, left { 0, 3, 2, 6, 5, 1, 6}, //18 front, right {-1,-1,-1,-1,-1,-1, 0}, //19 - { 0, 3, 2, 1, 5, 4, 6}, //20 front, bottom { 1, 5, 4, 7, 3, 2, 6}, //21 front, bottom, left { 0, 3, 2, 6, 5, 4, 6}, //22 front, bottom, right {-1,-1,-1,-1,-1,-1, 0}, //23 - { 0, 3, 7, 6, 2, 1, 6}, //24 front, top { 0, 4, 7, 6, 2, 1, 6}, //25 front, top, left { 0, 3, 7, 6, 5, 1, 6}, //26 front, top, right {-1,-1,-1,-1,-1,-1, 0}, //27 - {-1,-1,-1,-1,-1,-1, 0}, //28 - {-1,-1,-1,-1,-1,-1, 0}, //29 - {-1,-1,-1,-1,-1,-1, 0}, //30 - {-1,-1,-1,-1,-1,-1, 0}, //31 - { 4, 5, 6, 7,-1,-1, 4}, //32 back { 0, 4, 5, 6, 7, 3, 6}, //33 back, left { 1, 2, 6, 7, 4, 5, 6}, //34 back, right {-1,-1,-1,-1,-1,-1, 0}, //35 - { 0, 1, 5, 6, 7, 4, 6}, //36 back, bottom { 0, 1, 5, 6, 7, 3, 6}, //37 back, bottom, left { 0, 1, 2, 6, 7, 4, 6}, //38 back, bottom, right {-1,-1,-1,-1,-1,-1, 0}, //39 - { 2, 3, 7, 4, 5, 6, 6}, //40 back, top { 0, 4, 5, 6, 2, 3, 6}, //41 back, top, left { 1, 2, 3, 7, 4, 5, 6}, //42 back, top, right {-1,-1,-1,-1,-1,-1, 0}, //43 invalid {-1,-1,-1,-1,-1,-1, 0}, //44 invalid {-1,-1,-1,-1,-1,-1, 0}, //45 invalid {-1,-1,-1,-1,-1,-1, 0}, //46 invalid {-1,-1,-1,-1,-1,-1, 0}, //47 invalid {-1,-1,-1,-1,-1,-1, 0}, //48 invalid {-1,-1,-1,-1,-1,-1, 0}, //49 invalid {-1,-1,-1,-1,-1,-1, 0}, //50 invalid {-1,-1,-1,-1,-1,-1, 0}, //51 invalid {-1,-1,-1,-1,-1,-1, 0}, //52 invalid {-1,-1,-1,-1,-1,-1, 0}, //53 invalid {-1,-1,-1,-1,-1,-1, 0}, //54 invalid {-1,-1,-1,-1,-1,-1, 0}, //55 invalid {-1,-1,-1,-1,-1,-1, 0}, //56 invalid {-1,-1,-1,-1,-1,-1, 0}, //57 invalid {-1,-1,-1,-1,-1,-1, 0}, //58 invalid {-1,-1,-1,-1,-1,-1, 0}, //59 invalid {-1,-1,-1,-1,-1,-1, 0}, //60 invalid {-1,-1,-1,-1,-1,-1, 0}, //61 invalid {-1,-1,-1,-1,-1,-1, 0}, //62 invalid {-1,-1,-1,-1,-1,-1, 0} //63 invalid }; //---------------------------------------------------------------------------- // calculateBoxArea: computes the screen-projected 2D area of an oriented 3D // bounding box //---------------------------------------------------------------------------- float calculateBoxArea( const SbVec3f eye, //eye point (in bbox object coordinates) const SbBox3f& box, //3d bbox const SbMatrix& mat, //free transformation for bbox const SbViewVolume& volume) //view volume { SbVec3f min = box.getMin(), max = box.getMax(); //get box corners //compute 6-bit code to classify eye with respect to the 6 defining planes //of the bbox int pos = ((eye[0] < min[0]) ? 1 : 0) // 1 = left + ((eye[0] > max[0]) ? 2 : 0) // 2 = right + ((eye[1] < min[1]) ? 4 : 0) // 4 = bottom + ((eye[1] > max[1]) ? 8 : 0) // 8 = top + ((eye[2] < min[2]) ? 16 : 0) // 16 = front + ((eye[2] > max[2]) ? 32 : 0); // 32 = back int num = indexlist[pos][6]; //look up number of vertices in outline if (!num) return -1.0; //zero indicates invalid case, return -1 SbVec3f vertexBox[8],dst[8],tmp; //generate 8 corners of the bbox vertexBox[0] = SbVec3f (min[0],min[1],min[2]); // 7+------+6 vertexBox[1] = SbVec3f (max[0],min[1],min[2]); // /| /| vertexBox[2] = SbVec3f (max[0],max[1],min[2]); // / | / | vertexBox[3] = SbVec3f (min[0],max[1],min[2]); // / 4+---/--+5 vertexBox[4] = SbVec3f (min[0],min[1],max[2]); // 3+------+2 / y z vertexBox[5] = SbVec3f (max[0],min[1],max[2]); // | / | / | / vertexBox[6] = SbVec3f (max[0],max[1],max[2]); // |/ |/ |/ vertexBox[7] = SbVec3f (min[0],max[1],max[2]); // 0+------+1 *---x float sum = 0; int i; for(i=0; i<num; i++) //transform all outline corners into 2D screen space { mat.multVecMatrix(vertexBox[indexlist[pos][i]],tmp); //orient vertex volume.projectToScreen(tmp,dst[i]); //project } sum = (dst[num-1][0] - dst[0][0]) * (dst[num-1][1] + dst[0][1]); for (i=0; i<num-1; i++) sum += (dst[i][0] - dst[i+1][0]) * (dst[i][1] + dst[i+1][1]); return sum * 0.5; //return computed value corrected by 0.5 } //---------------------------------------------------------------------------- // SAMPLE CODE ENDS HERE //---------------------------------------------------------------------------- SoNode* node; SoPath* path; SoGetBoundingBoxAction* bbaction = new SoGetBoundingBoxAction(SbViewportRegion()); SoGetMatrixAction* matrixaction = new SoGetMatrixAction(SbViewportRegion()); void callbackFunc(void*, SoAction* action) { if (action->isOfType(SoGLRenderAction::getClassTypeId())) { SoState* state = action->getState(); bbaction->apply(node); SbBox3f box = bbaction->getBoundingBox(); matrixaction->apply(path); SbMatrix mat = matrixaction->getMatrix(); SbMatrix camera = SoViewingMatrixElement::get(state); SbMatrix a = mat; mat.multRight(camera); SbMatrix inv = mat.inverse(); float res = calculateBoxArea(SbVec3f(inv[3][0],inv[3][1],inv[3][2]), box,a,SoViewVolumeElement::get(state)); printf ("Area: %f\n",res); // to keep us updated... SoCacheElement::invalidate(action->getState()); } } //---------------------------------------------------------------------------- void main(int , char** argv) { // Initialize Inventor. This returns a main window to use. // If unsuccessful, exit. Widget myWindow = SoXt::init(argv[0]); // pass the app name if (myWindow == NULL) exit(1); SoSeparator* root = new SoSeparator; SoMaterial* myMaterial = new SoMaterial; root->ref(); root->addChild(new SoDirectionalLight); myMaterial->diffuseColor.setValue(1.0, 0.0, 0.0); // Red root->addChild(myMaterial); SoTransformerManip* manip = new SoTransformerManip; root->addChild(manip); SoCube* cube = new SoCube; node = cube; root->addChild(cube); SoCallback* callback = new SoCallback; callback->setCallback(callbackFunc); root->addChild(callback); SoXtExaminerViewer* myViewer = new SoXtExaminerViewer(myWindow); myViewer->setSceneGraph(root); myViewer->setTitle("BBox Size"); SoSearchAction mySearcher; mySearcher.setType (SoCube::getClassTypeId(),FALSE); mySearcher.setInterest (SoSearchAction::FIRST); mySearcher.apply(root); path = mySearcher.getPath(); SoXt::show(myWindow); // Display main window SoXt::mainLoop(); // Main Inventor event loop } //---------------------------------------------------------------------------- //eof <commit_msg>Close issue #4 - note orthographic camera test, and smaller table<commit_after>// =========================================================================== // (C) 1996-98 Vienna University of Technology // =========================================================================== // NAME: bboxarea // TYPE: c++ code // PROJECT: Bounding Box Area // CONTENT: Computes area of 2D projection of 3D oriented bounding box // VERSION: 1.0 // =========================================================================== // AUTHORS: ds Dieter Schmalstieg // ep Erik Pojar // =========================================================================== // HISTORY: // // 19-sep-99 15:23:03 ds last modification // 01-dec-98 15:23:03 ep created // =========================================================================== #include <Inventor/Xt/SoXt.h> #include <Inventor/Xt/SoXtRenderArea.h> #include <Inventor/Xt/viewers/SoXtExaminerViewer.h> #include <Inventor/nodes/SoCone.h> #include <Inventor/nodes/SoCube.h> #include <Inventor/nodes/SoDirectionalLight.h> #include <Inventor/nodes/SoMaterial.h> #include <Inventor/nodes/SoPerspectiveCamera.h> #include <Inventor/nodes/SoSeparator.h> #include <Inventor/nodes/SoCallback.h> #include <Inventor/elements/SoCacheElement.h> #include <Inventor/elements/SoViewingMatrixElement.h> #include <Inventor/elements/SoViewVolumeElement.h> #include <Inventor/manips/SoTransformerManip.h> #include <Inventor/actions/SoSearchAction.h> #include <Inventor/actions/SoGetMatrixAction.h> #include <Inventor/actions/SoGetBoundingBoxAction.h> #include <Inventor/SbLinear.h> //---------------------------------------------------------------------------- // SAMPLE CODE STARTS HERE //---------------------------------------------------------------------------- // NOTE: This sample program requires OPEN INVENTOR! //indexlist: this table stores the 64 possible cases of classification of //the eyepoint with respect to the 6 defining planes of the bbox (2^6=64) //only 26 (3^3-1, where 1 is "inside" cube) of these cases are valid. //the first 6 numbers in each row are the indices of the bbox vertices that //form the outline of which we want to compute the area (counterclockwise //ordering), the 7th entry means the number of vertices in the outline. //there are 6 cases with a single face and and a 4-vertex outline, and //20 cases with 2 or 3 faces and a 6-vertex outline. a value of 0 indicates //an invalid case. //note: this table can be 27 entries, if space is a concern. See //"Game Math Case Studies," by Eric Lengyel, //http://www.terathon.com/gdc15_lengyel.pdf const int indexlist[64][7] = { {-1,-1,-1,-1,-1,-1, 0}, // 0 inside { 0, 4, 7, 3,-1,-1, 4}, // 1 left { 1, 2, 6, 5,-1,-1, 4}, // 2 right {-1,-1,-1,-1,-1,-1, 0}, // 3 - { 0, 1, 5, 4,-1,-1, 4}, // 4 bottom { 0, 1, 5, 4, 7, 3, 6}, // 5 bottom, left { 0, 1, 2, 6, 5, 4, 6}, // 6 bottom, right {-1,-1,-1,-1,-1,-1, 0}, // 7 - { 2, 3, 7, 6,-1,-1, 4}, // 8 top { 0, 4, 7, 6, 2, 3, 6}, // 9 top, left { 1, 2, 3, 7, 6, 5, 6}, //10 top, right {-1,-1,-1,-1,-1,-1, 0}, //11 - {-1,-1,-1,-1,-1,-1, 0}, //12 - {-1,-1,-1,-1,-1,-1, 0}, //13 - {-1,-1,-1,-1,-1,-1, 0}, //14 - {-1,-1,-1,-1,-1,-1, 0}, //15 - { 0, 3, 2, 1,-1,-1, 4}, //16 front { 0, 4, 7, 3, 2, 1, 6}, //17 front, left { 0, 3, 2, 6, 5, 1, 6}, //18 front, right {-1,-1,-1,-1,-1,-1, 0}, //19 - { 0, 3, 2, 1, 5, 4, 6}, //20 front, bottom { 1, 5, 4, 7, 3, 2, 6}, //21 front, bottom, left { 0, 3, 2, 6, 5, 4, 6}, //22 front, bottom, right {-1,-1,-1,-1,-1,-1, 0}, //23 - { 0, 3, 7, 6, 2, 1, 6}, //24 front, top { 0, 4, 7, 6, 2, 1, 6}, //25 front, top, left { 0, 3, 7, 6, 5, 1, 6}, //26 front, top, right {-1,-1,-1,-1,-1,-1, 0}, //27 - {-1,-1,-1,-1,-1,-1, 0}, //28 - {-1,-1,-1,-1,-1,-1, 0}, //29 - {-1,-1,-1,-1,-1,-1, 0}, //30 - {-1,-1,-1,-1,-1,-1, 0}, //31 - { 4, 5, 6, 7,-1,-1, 4}, //32 back { 0, 4, 5, 6, 7, 3, 6}, //33 back, left { 1, 2, 6, 7, 4, 5, 6}, //34 back, right {-1,-1,-1,-1,-1,-1, 0}, //35 - { 0, 1, 5, 6, 7, 4, 6}, //36 back, bottom { 0, 1, 5, 6, 7, 3, 6}, //37 back, bottom, left { 0, 1, 2, 6, 7, 4, 6}, //38 back, bottom, right {-1,-1,-1,-1,-1,-1, 0}, //39 - { 2, 3, 7, 4, 5, 6, 6}, //40 back, top { 0, 4, 5, 6, 2, 3, 6}, //41 back, top, left { 1, 2, 3, 7, 4, 5, 6}, //42 back, top, right {-1,-1,-1,-1,-1,-1, 0}, //43 invalid {-1,-1,-1,-1,-1,-1, 0}, //44 invalid {-1,-1,-1,-1,-1,-1, 0}, //45 invalid {-1,-1,-1,-1,-1,-1, 0}, //46 invalid {-1,-1,-1,-1,-1,-1, 0}, //47 invalid {-1,-1,-1,-1,-1,-1, 0}, //48 invalid {-1,-1,-1,-1,-1,-1, 0}, //49 invalid {-1,-1,-1,-1,-1,-1, 0}, //50 invalid {-1,-1,-1,-1,-1,-1, 0}, //51 invalid {-1,-1,-1,-1,-1,-1, 0}, //52 invalid {-1,-1,-1,-1,-1,-1, 0}, //53 invalid {-1,-1,-1,-1,-1,-1, 0}, //54 invalid {-1,-1,-1,-1,-1,-1, 0}, //55 invalid {-1,-1,-1,-1,-1,-1, 0}, //56 invalid {-1,-1,-1,-1,-1,-1, 0}, //57 invalid {-1,-1,-1,-1,-1,-1, 0}, //58 invalid {-1,-1,-1,-1,-1,-1, 0}, //59 invalid {-1,-1,-1,-1,-1,-1, 0}, //60 invalid {-1,-1,-1,-1,-1,-1, 0}, //61 invalid {-1,-1,-1,-1,-1,-1, 0}, //62 invalid {-1,-1,-1,-1,-1,-1, 0} //63 invalid }; //---------------------------------------------------------------------------- // calculateBoxArea: computes the screen-projected 2D area of an oriented 3D // bounding box //---------------------------------------------------------------------------- float calculateBoxArea( const SbVec3f eye, //eye point (in bbox object coordinates) const SbBox3f& box, //3d bbox const SbMatrix& mat, //free transformation for bbox const SbViewVolume& volume) //view volume { SbVec3f min = box.getMin(), max = box.getMax(); //get box corners //compute 6-bit code to classify eye with respect to the 6 defining planes //of the bbox int pos = ((eye[0] < min[0]) ? 1 : 0) // 1 = left + ((eye[0] > max[0]) ? 2 : 0) // 2 = right + ((eye[1] < min[1]) ? 4 : 0) // 4 = bottom + ((eye[1] > max[1]) ? 8 : 0) // 8 = top + ((eye[2] < min[2]) ? 16 : 0) // 16 = front + ((eye[2] > max[2]) ? 32 : 0); // 32 = back //note: for an orthographic camera, the view direction is used instead, the //eye location is irrelevant. The test is along these lines: //int pos = ((dir[0] > 0) ? 1 : 0) // 1 = left // + ((dir[0] < 0) ? 2 : 0) // 2 = right // + ((dir[1] > 0) ? 4 : 0) // 4 = bottom // + ((dir[1] < 0) ? 8 : 0) // 8 = top // + ((dir[2] > 0) ? 16 : 0) // 16 = front // + ((dir[2] < 0) ? 32 : 0); // 32 = back int num = indexlist[pos][6]; //look up number of vertices in outline if (!num) return -1.0; //zero indicates invalid case, return -1 SbVec3f vertexBox[8],dst[8],tmp; //generate 8 corners of the bbox vertexBox[0] = SbVec3f (min[0],min[1],min[2]); // 7+------+6 vertexBox[1] = SbVec3f (max[0],min[1],min[2]); // /| /| vertexBox[2] = SbVec3f (max[0],max[1],min[2]); // / | / | vertexBox[3] = SbVec3f (min[0],max[1],min[2]); // / 4+---/--+5 vertexBox[4] = SbVec3f (min[0],min[1],max[2]); // 3+------+2 / y z vertexBox[5] = SbVec3f (max[0],min[1],max[2]); // | / | / | / vertexBox[6] = SbVec3f (max[0],max[1],max[2]); // |/ |/ |/ vertexBox[7] = SbVec3f (min[0],max[1],max[2]); // 0+------+1 *---x float sum = 0; int i; for(i=0; i<num; i++) //transform all outline corners into 2D screen space { mat.multVecMatrix(vertexBox[indexlist[pos][i]],tmp); //orient vertex volume.projectToScreen(tmp,dst[i]); //project } sum = (dst[num-1][0] - dst[0][0]) * (dst[num-1][1] + dst[0][1]); for (i=0; i<num-1; i++) sum += (dst[i][0] - dst[i+1][0]) * (dst[i][1] + dst[i+1][1]); return sum * 0.5; //return computed value corrected by 0.5 } //---------------------------------------------------------------------------- // SAMPLE CODE ENDS HERE //---------------------------------------------------------------------------- SoNode* node; SoPath* path; SoGetBoundingBoxAction* bbaction = new SoGetBoundingBoxAction(SbViewportRegion()); SoGetMatrixAction* matrixaction = new SoGetMatrixAction(SbViewportRegion()); void callbackFunc(void*, SoAction* action) { if (action->isOfType(SoGLRenderAction::getClassTypeId())) { SoState* state = action->getState(); bbaction->apply(node); SbBox3f box = bbaction->getBoundingBox(); matrixaction->apply(path); SbMatrix mat = matrixaction->getMatrix(); SbMatrix camera = SoViewingMatrixElement::get(state); SbMatrix a = mat; mat.multRight(camera); SbMatrix inv = mat.inverse(); float res = calculateBoxArea(SbVec3f(inv[3][0],inv[3][1],inv[3][2]), box,a,SoViewVolumeElement::get(state)); printf ("Area: %f\n",res); // to keep us updated... SoCacheElement::invalidate(action->getState()); } } //---------------------------------------------------------------------------- void main(int , char** argv) { // Initialize Inventor. This returns a main window to use. // If unsuccessful, exit. Widget myWindow = SoXt::init(argv[0]); // pass the app name if (myWindow == NULL) exit(1); SoSeparator* root = new SoSeparator; SoMaterial* myMaterial = new SoMaterial; root->ref(); root->addChild(new SoDirectionalLight); myMaterial->diffuseColor.setValue(1.0, 0.0, 0.0); // Red root->addChild(myMaterial); SoTransformerManip* manip = new SoTransformerManip; root->addChild(manip); SoCube* cube = new SoCube; node = cube; root->addChild(cube); SoCallback* callback = new SoCallback; callback->setCallback(callbackFunc); root->addChild(callback); SoXtExaminerViewer* myViewer = new SoXtExaminerViewer(myWindow); myViewer->setSceneGraph(root); myViewer->setTitle("BBox Size"); SoSearchAction mySearcher; mySearcher.setType (SoCube::getClassTypeId(),FALSE); mySearcher.setInterest (SoSearchAction::FIRST); mySearcher.apply(root); path = mySearcher.getPath(); SoXt::show(myWindow); // Display main window SoXt::mainLoop(); // Main Inventor event loop } //---------------------------------------------------------------------------- //eof <|endoftext|>
<commit_before>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() #include "catch.hpp" #include <vector> #include "tclap/ValueArg.h" #include "Simulation.hpp" TEST_CASE("The Simulation parses command line arguments", "[Simulation]") { warped::Simulation* s = nullptr; std::vector<const char*> v {"prog", "-c", "filename", "-u", "100"}; SECTION("Simulation supports default arguments") { REQUIRE_NOTHROW((s = new warped::Simulation {"model", (int)v.size(), v.data()})); } SECTION("Simulation supports custom arguments") { TCLAP::ValueArg<int> arg("a", "arg", "", true, 0, "int"); std::vector<TCLAP::Arg*> v2 {&arg}; v.push_back("-a"); v.push_back("42"); REQUIRE_NOTHROW((s = new warped::Simulation {"model", (int)v.size(), v.data(), v2})); REQUIRE(arg.getValue() == 42); } delete s; } TEST_CASE("The Simulation can be constructed without command line parsing", "[Simulation]") { warped::Simulation* s = nullptr; REQUIRE_NOTHROW((s = new warped::Simulation {"filename", 100})); delete s; }<commit_msg>Changed command line argument<commit_after>#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() #include "catch.hpp" #include <vector> #include "tclap/ValueArg.h" #include "Simulation.hpp" TEST_CASE("The Simulation parses command line arguments", "[Simulation]") { warped::Simulation* s = nullptr; std::vector<const char*> v {"prog", "-c", "filename", "-t", "100"}; SECTION("Simulation supports default arguments") { REQUIRE_NOTHROW((s = new warped::Simulation {"model", (int)v.size(), v.data()})); } SECTION("Simulation supports custom arguments") { TCLAP::ValueArg<int> arg("a", "arg", "", true, 0, "int"); std::vector<TCLAP::Arg*> v2 {&arg}; v.push_back("-a"); v.push_back("42"); REQUIRE_NOTHROW((s = new warped::Simulation {"model", (int)v.size(), v.data(), v2})); REQUIRE(arg.getValue() == 42); } delete s; } TEST_CASE("The Simulation can be constructed without command line parsing", "[Simulation]") { warped::Simulation* s = nullptr; REQUIRE_NOTHROW((s = new warped::Simulation {"filename", 100})); delete s; }<|endoftext|>
<commit_before>// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <stdio.h> #include <stdlib.h> #include <vespa/vespalib/net/socket_address.h> #include <vespa/vespalib/stllike/string.h> #include <vespa/vespalib/util/stringfmt.h> #include <set> using vespalib::SocketAddress; std::set<vespalib::string> make_ip_set() { std::set<vespalib::string> result; for (const auto &addr: SocketAddress::get_interfaces()) { result.insert(addr.ip_address()); } return result; } vespalib::string get_hostname() { std::vector<char> result(4096, '\0'); gethostname(&result[0], 4000); return SocketAddress::normalize(&result[0]); } bool check(const vespalib::string &name, const std::set<vespalib::string> &ip_set, vespalib::string &error_msg) { auto addr_list = SocketAddress::resolve(80, name.c_str()); if (addr_list.empty()) { error_msg = vespalib::make_string("hostname '%s' could not be resolved", name.c_str()); return false; } for (const SocketAddress &addr: addr_list) { vespalib::string ip_addr = addr.ip_address(); if (ip_set.count(ip_addr) == 0) { error_msg = vespalib::make_string("hostname '%s' resolves to ip address not owned by this host (%s)", name.c_str(), ip_addr.c_str()); return false; } } return true; } int main(int, char **) { auto my_ip_set = make_ip_set(); vespalib::string my_hostname = get_hostname(); vespalib::string my_hostname_error; vespalib::string localhost = "localhost"; vespalib::string localhost_error; if (check(my_hostname, my_ip_set, my_hostname_error)) { fprintf(stdout, "%s\n", my_hostname.c_str()); } else if (check(localhost, my_ip_set, localhost_error)) { fprintf(stdout, "%s\n", localhost.c_str()); } else { fprintf(stderr, "FATAL: hostname detection failed\n"); fprintf(stderr, " INFO: canonical hostname (from gethostname/getaddrinfo): %s\n", my_hostname.c_str()); fprintf(stderr, " ERROR: %s\n", my_hostname_error.c_str()); fprintf(stderr, " INFO: falling back to local hostname: %s\n", localhost.c_str()); fprintf(stderr, " ERROR: %s\n", localhost_error.c_str()); return 1; } return 0; } <commit_msg>Print infor when detecting hostname fails and we fallback to localhost<commit_after>// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <stdio.h> #include <stdlib.h> #include <vespa/vespalib/net/socket_address.h> #include <vespa/vespalib/stllike/string.h> #include <vespa/vespalib/util/stringfmt.h> #include <set> using vespalib::SocketAddress; std::set<vespalib::string> make_ip_set() { std::set<vespalib::string> result; for (const auto &addr: SocketAddress::get_interfaces()) { result.insert(addr.ip_address()); } return result; } vespalib::string get_hostname() { std::vector<char> result(4096, '\0'); gethostname(&result[0], 4000); return SocketAddress::normalize(&result[0]); } bool check(const vespalib::string &name, const std::set<vespalib::string> &ip_set, vespalib::string &error_msg) { auto addr_list = SocketAddress::resolve(80, name.c_str()); if (addr_list.empty()) { error_msg = vespalib::make_string("hostname '%s' could not be resolved", name.c_str()); return false; } for (const SocketAddress &addr: addr_list) { vespalib::string ip_addr = addr.ip_address(); if (ip_set.count(ip_addr) == 0) { error_msg = vespalib::make_string("hostname '%s' resolves to ip address not owned by this host (%s)", name.c_str(), ip_addr.c_str()); return false; } } return true; } int main(int, char **) { auto my_ip_set = make_ip_set(); vespalib::string my_hostname = get_hostname(); vespalib::string my_hostname_error; vespalib::string localhost = "localhost"; vespalib::string localhost_error; if (check(my_hostname, my_ip_set, my_hostname_error)) { fprintf(stdout, "%s\n", my_hostname.c_str()); } else if (check(localhost, my_ip_set, localhost_error)) { fprintf(stderr, "INFO: hostname detection failed, falling back to local hostname: %s", localhost.c_str()); fprintf(stderr, " INFO: canonical hostname (from gethostname/getaddrinfo): %s\n", my_hostname.c_str()); fprintf(stderr, " INFO: %s\n", my_hostname_error.c_str()); fprintf(stdout, "%s\n", localhost.c_str()); } else { fprintf(stderr, "FATAL: hostname detection failed\n"); fprintf(stderr, " INFO: canonical hostname (from gethostname/getaddrinfo): %s\n", my_hostname.c_str()); fprintf(stderr, " ERROR: %s\n", my_hostname_error.c_str()); fprintf(stderr, " INFO: falling back to local hostname: %s\n", localhost.c_str()); fprintf(stderr, " ERROR: %s\n", localhost_error.c_str()); return 1; } return 0; } <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "EigenKernel.h" #include "MooseEigenSystem.h" #include "MooseApp.h" #include "Executioner.h" #include "EigenExecutionerBase.h" #include "Assembly.h" // libMesh includes #include "libmesh/quadrature.h" template<> InputParameters validParams<EigenKernel>() { InputParameters params = validParams<KernelBase>(); params.addParam<bool>("eigen", true, "Use for eigenvalue problem (true) or source problem (false)"); params.addParam<PostprocessorName>("eigen_postprocessor", 1.0, "The name of the postprocessor that provides the eigenvalue."); params.registerBase("EigenKernel"); return params; } EigenKernel::EigenKernel(const InputParameters & parameters) : KernelBase(parameters), _u(_is_implicit ? _var.sln() : _var.slnOld()), _grad_u(_is_implicit ? _var.gradSln() : _var.gradSlnOld()), _eigen(getParam<bool>("eigen")), _eigen_sys(dynamic_cast<MooseEigenSystem *>(&_fe_problem.getNonlinearSystemBase())), _eigenvalue(NULL) { // The name to the postprocessor storing the eigenvalue std::string eigen_pp_name; // If the "eigen_postprocessor" is given, use it. The isParamValid does not work here because of the default value, which // you don't want to use if an EigenExecutioner exists. if (hasPostprocessor("eigen_postprocessor")) eigen_pp_name = getParam<PostprocessorName>("eigen_postprocessor"); // Attempt to extract the eigenvalue postprocessor from the Executioner else { EigenExecutionerBase * exec = dynamic_cast<EigenExecutionerBase *>(_app.getExecutioner()); if (exec) eigen_pp_name = exec->getParam<PostprocessorName>("bx_norm"); } // If the postprocessor name was not provided and an EigenExecutionerBase is not being used, // use the default value from the "eigen_postprocessor" parameter if (eigen_pp_name.empty()) _eigenvalue = &getDefaultPostprocessorValue("eigen_postprocessor"); // If the name does exist, then use the postprocessor value else { if (_is_implicit) _eigenvalue = &getPostprocessorValueByName(eigen_pp_name); else { EigenExecutionerBase * exec = dynamic_cast<EigenExecutionerBase *>(_app.getExecutioner()); if (exec) _eigenvalue = &exec->eigenvalueOld(); else _eigenvalue = &getPostprocessorValueOldByName(eigen_pp_name); } } } void EigenKernel::computeResidual() { DenseVector<Number> & re = _assembly.residualBlock(_var.number()); _local_re.resize(re.size()); _local_re.zero(); mooseAssert(*_eigenvalue != 0.0, "Can't divide by zero eigenvalue in EigenKernel!"); Real one_over_eigen = 1.0 / *_eigenvalue; for (_i = 0; _i < _test.size(); _i++) for (_qp = 0; _qp < _qrule->n_points(); _qp++) _local_re(_i) += _JxW[_qp] * _coord[_qp] * one_over_eigen * computeQpResidual(); re += _local_re; if (_has_save_in) { Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx); for (const auto & var : _save_in) var->sys().solution().add_vector(_local_re, var->dofIndices()); } } void EigenKernel::computeJacobian() { if (!_is_implicit) return; DenseMatrix<Number> & ke = _assembly.jacobianBlock(_var.number(), _var.number()); _local_ke.resize(ke.m(), ke.n()); _local_ke.zero(); mooseAssert(*_eigenvalue != 0.0, "Can't divide by zero eigenvalue in EigenKernel!"); Real one_over_eigen = 1.0 / *_eigenvalue; for (_i = 0; _i < _test.size(); _i++) for (_j = 0; _j < _phi.size(); _j++) for (_qp = 0; _qp < _qrule->n_points(); _qp++) _local_ke(_i, _j) += _JxW[_qp] * _coord[_qp] * one_over_eigen * computeQpJacobian(); ke += _local_ke; if (_has_diag_save_in) { unsigned int rows = ke.m(); DenseVector<Number> diag(rows); for (unsigned int i=0; i<rows; i++) diag(i) = _local_ke(i,i); Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx); for (unsigned int i=0; i<_diag_save_in.size(); i++) _diag_save_in[i]->sys().solution().add_vector(diag, _diag_save_in[i]->dofIndices()); } } void EigenKernel::computeOffDiagJacobian(unsigned int jvar) { if (!_is_implicit) return; if (jvar == _var.number()) computeJacobian(); else { DenseMatrix<Number> & ke = _assembly.jacobianBlock(_var.number(), jvar); _local_ke.resize(ke.m(), ke.n()); _local_ke.zero(); mooseAssert(*_eigenvalue != 0.0, "Can't divide by zero eigenvalue in EigenKernel!"); Real one_over_eigen = 1.0 / *_eigenvalue; for (_i = 0; _i < _test.size(); _i++) for (_j = 0; _j < _phi.size(); _j++) for (_qp = 0; _qp < _qrule->n_points(); _qp++) _local_ke(_i, _j) += _JxW[_qp] * _coord[_qp] * computeQpOffDiagJacobian(jvar); ke += _local_ke; } } bool EigenKernel::enabled() { bool flag = MooseObject::enabled(); if (_eigen) { if (_is_implicit) return flag && (!_eigen_sys->activeOnOld()); else return flag && _eigen_sys->activeOnOld(); } else return flag; } <commit_msg>fix a small bug in the previous commit #8103<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "EigenKernel.h" #include "MooseEigenSystem.h" #include "MooseApp.h" #include "Executioner.h" #include "EigenExecutionerBase.h" #include "Assembly.h" // libMesh includes #include "libmesh/quadrature.h" template<> InputParameters validParams<EigenKernel>() { InputParameters params = validParams<KernelBase>(); params.addParam<bool>("eigen", true, "Use for eigenvalue problem (true) or source problem (false)"); params.addParam<PostprocessorName>("eigen_postprocessor", 1.0, "The name of the postprocessor that provides the eigenvalue."); params.registerBase("EigenKernel"); return params; } EigenKernel::EigenKernel(const InputParameters & parameters) : KernelBase(parameters), _u(_is_implicit ? _var.sln() : _var.slnOld()), _grad_u(_is_implicit ? _var.gradSln() : _var.gradSlnOld()), _eigen(getParam<bool>("eigen")), _eigen_sys(dynamic_cast<MooseEigenSystem *>(&_fe_problem.getNonlinearSystemBase())), _eigenvalue(NULL) { // The name to the postprocessor storing the eigenvalue std::string eigen_pp_name; // If the "eigen_postprocessor" is given, use it. The isParamValid does not work here because of the default value, which // you don't want to use if an EigenExecutioner exists. if (hasPostprocessor("eigen_postprocessor")) eigen_pp_name = getParam<PostprocessorName>("eigen_postprocessor"); // Attempt to extract the eigenvalue postprocessor from the Executioner else { EigenExecutionerBase * exec = dynamic_cast<EigenExecutionerBase *>(_app.getExecutioner()); if (exec) eigen_pp_name = exec->getParam<PostprocessorName>("bx_norm"); } // If the postprocessor name was not provided and an EigenExecutionerBase is not being used, // use the default value from the "eigen_postprocessor" parameter if (eigen_pp_name.empty()) _eigenvalue = &getDefaultPostprocessorValue("eigen_postprocessor"); // If the name does exist, then use the postprocessor value else { if (_is_implicit) _eigenvalue = &getPostprocessorValueByName(eigen_pp_name); else { EigenExecutionerBase * exec = dynamic_cast<EigenExecutionerBase *>(_app.getExecutioner()); if (exec) _eigenvalue = &exec->eigenvalueOld(); else _eigenvalue = &getPostprocessorValueOldByName(eigen_pp_name); } } } void EigenKernel::computeResidual() { DenseVector<Number> & re = _assembly.residualBlock(_var.number()); _local_re.resize(re.size()); _local_re.zero(); mooseAssert(*_eigenvalue != 0.0, "Can't divide by zero eigenvalue in EigenKernel!"); Real one_over_eigen = 1.0 / *_eigenvalue; for (_i = 0; _i < _test.size(); _i++) for (_qp = 0; _qp < _qrule->n_points(); _qp++) _local_re(_i) += _JxW[_qp] * _coord[_qp] * one_over_eigen * computeQpResidual(); re += _local_re; if (_has_save_in) { Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx); for (const auto & var : _save_in) var->sys().solution().add_vector(_local_re, var->dofIndices()); } } void EigenKernel::computeJacobian() { if (!_is_implicit) return; DenseMatrix<Number> & ke = _assembly.jacobianBlock(_var.number(), _var.number()); _local_ke.resize(ke.m(), ke.n()); _local_ke.zero(); mooseAssert(*_eigenvalue != 0.0, "Can't divide by zero eigenvalue in EigenKernel!"); Real one_over_eigen = 1.0 / *_eigenvalue; for (_i = 0; _i < _test.size(); _i++) for (_j = 0; _j < _phi.size(); _j++) for (_qp = 0; _qp < _qrule->n_points(); _qp++) _local_ke(_i, _j) += _JxW[_qp] * _coord[_qp] * one_over_eigen * computeQpJacobian(); ke += _local_ke; if (_has_diag_save_in) { unsigned int rows = ke.m(); DenseVector<Number> diag(rows); for (unsigned int i=0; i<rows; i++) diag(i) = _local_ke(i,i); Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx); for (unsigned int i=0; i<_diag_save_in.size(); i++) _diag_save_in[i]->sys().solution().add_vector(diag, _diag_save_in[i]->dofIndices()); } } void EigenKernel::computeOffDiagJacobian(unsigned int jvar) { if (!_is_implicit) return; if (jvar == _var.number()) computeJacobian(); else { DenseMatrix<Number> & ke = _assembly.jacobianBlock(_var.number(), jvar); _local_ke.resize(ke.m(), ke.n()); _local_ke.zero(); mooseAssert(*_eigenvalue != 0.0, "Can't divide by zero eigenvalue in EigenKernel!"); Real one_over_eigen = 1.0 / *_eigenvalue; for (_i = 0; _i < _test.size(); _i++) for (_j = 0; _j < _phi.size(); _j++) for (_qp = 0; _qp < _qrule->n_points(); _qp++) _local_ke(_i, _j) += _JxW[_qp] * _coord[_qp] * one_over_eigen * computeQpOffDiagJacobian(jvar); ke += _local_ke; } } bool EigenKernel::enabled() { bool flag = MooseObject::enabled(); if (_eigen) { if (_is_implicit) return flag && (!_eigen_sys->activeOnOld()); else return flag && _eigen_sys->activeOnOld(); } else return flag; } <|endoftext|>
<commit_before>//-------------------------------------------------------------------------------------------------- /** * @file envVars.cpp * * Environment variable helper functions used by various modules. * * Copyright (C) Sierra Wireless Inc. */ //-------------------------------------------------------------------------------------------------- #include "mkTools.h" #include <string.h> //-------------------------------------------------------------------------------------------------- /** * Maximum length of the environment variable */ //-------------------------------------------------------------------------------------------------- #define ENV_VAR_MAX_LEN 1024 /// The standard C environment variable list. extern char**environ; namespace envVars { //-------------------------------------------------------------------------------------------------- /** * Fetch the value of a given optional environment variable. * * @return The value ("" if not found). */ //-------------------------------------------------------------------------------------------------- std::string Get ( const std::string& name ///< The name of the environment variable. ) //-------------------------------------------------------------------------------------------------- { char envVar[ENV_VAR_MAX_LEN] = {0}; const char* value = getenv(name.c_str()); if (value == nullptr) { return std::string(); } // If variable is longer than MAX_LEN, it will be truncated strncpy(envVar, value, sizeof(envVar) - 1); return std::string(envVar); } //-------------------------------------------------------------------------------------------------- /** * Fetch the value of a given mandatory environment variable. * * @return The value. * * @throw Exception if environment variable not found. */ //-------------------------------------------------------------------------------------------------- std::string GetRequired ( const std::string& name ///< The name of the environment variable. ) //-------------------------------------------------------------------------------------------------- { char envVar[ENV_VAR_MAX_LEN] = {0}; const char* value = getenv(name.c_str()); if (value == nullptr) { throw mk::Exception_t( mk::format(LE_I18N("The required environment variable %s has not been set."), name) ); } // If variable is longer than MAX_LEN, it will be truncated strncpy(envVar, value, sizeof(envVar) - 1); return std::string(envVar); } //-------------------------------------------------------------------------------------------------- /** * Set the value of a given environment variable. If the variable already exists, replaces its * value. */ //-------------------------------------------------------------------------------------------------- void Set ( const std::string& name, ///< The name of the environment variable. const std::string& value ///< The value of the environment variable. ) //-------------------------------------------------------------------------------------------------- { if (setenv(name.c_str(), value.c_str(), true /* overwrite existing */) != 0) { throw mk::Exception_t( mk::format(LE_I18N("Failed to set environment variable '%s' to '%s'."), name, value) ); } } //-------------------------------------------------------------------------------------------------- /** * Set compiler, linker, etc. environment variables according to the target device type, if they're * not already set. */ //-------------------------------------------------------------------------------------------------- static void SetToolChainVars ( const mk::BuildParams_t& buildParams ) //-------------------------------------------------------------------------------------------------- { if (!buildParams.cCompilerPath.empty()) { auto cCompilerPath = buildParams.cCompilerPath; if (!buildParams.compilerCachePath.empty()) { cCompilerPath = buildParams.compilerCachePath + " " + buildParams.cCompilerPath; } Set("CC", cCompilerPath.c_str()); } if (!buildParams.cxxCompilerPath.empty()) { auto cxxCompilerPath = buildParams.cxxCompilerPath; if (!buildParams.compilerCachePath.empty()) { cxxCompilerPath = buildParams.compilerCachePath + " " + buildParams.cxxCompilerPath; } Set("CXX", cxxCompilerPath.c_str()); } if (!buildParams.toolChainDir.empty()) { Set("TOOLCHAIN_DIR", buildParams.toolChainDir.c_str()); } if (!buildParams.toolChainPrefix.empty()) { Set("TOOLCHAIN_PREFIX", buildParams.toolChainPrefix.c_str()); } if (!buildParams.sysrootDir.empty()) { Set("LEGATO_SYSROOT", buildParams.sysrootDir.c_str()); } if (!buildParams.linkerPath.empty()) { Set("LD", buildParams.linkerPath.c_str()); } if (!buildParams.archiverPath.empty()) { Set("AR", buildParams.archiverPath.c_str()); } if (!buildParams.assemblerPath.empty()) { Set("AS", buildParams.assemblerPath.c_str()); } if (!buildParams.stripPath.empty()) { Set("STRIP", buildParams.stripPath.c_str()); } if (!buildParams.objcopyPath.empty()) { Set("OBJCOPY", buildParams.objcopyPath.c_str()); } if (!buildParams.readelfPath.empty()) { Set("READELF", buildParams.readelfPath.c_str()); } else { std::cout << "*************************** readelfPath is empty\n"; } if (!buildParams.compilerCachePath.empty()) { Set("CCACHE", buildParams.compilerCachePath.c_str()); } } //---------------------------------------------------------------------------------------------- /** * Adds target-specific environment variables (e.g., LEGATO_TARGET) to the process's environment. * * The environment will get inherited by any child processes, including the shell that is used * to run the compiler and linker. Also, this allows these environment variables to be used in * paths in .sdef, .adef, and .cdef files. */ //---------------------------------------------------------------------------------------------- void SetTargetSpecific ( const mk::BuildParams_t& buildParams ) //-------------------------------------------------------------------------------------------------- { // WARNING: If you add another target-specific variable, remember to update IsReserved(). // Set compiler, linker, etc variables specific to the target device type, if they're not set. SetToolChainVars(buildParams); // Set LEGATO_TARGET. Set("LEGATO_TARGET", buildParams.target.c_str()); // Set LEGATO_BUILD based on the contents of LEGATO_ROOT, which must be already defined. std::string path = GetRequired("LEGATO_ROOT"); if (path.empty()) { throw mk::Exception_t(LE_I18N("LEGATO_ROOT environment variable is empty.")); } path = path::Combine(path, "build/" + buildParams.target); Set("LEGATO_BUILD", path.c_str()); } //---------------------------------------------------------------------------------------------- /** * Checks if a given environment variable name is one of the reserved environment variable names * (e.g., LEGATO_TARGET). * * @return true if reserved, false if not. */ //---------------------------------------------------------------------------------------------- bool IsReserved ( const std::string& name ///< Name of the variable. ) //-------------------------------------------------------------------------------------------------- { return ( (name == "LEGATO_ROOT") || (name == "LEGATO_TARGET") || (name == "LEGATO_BUILD") || (name == "LEGATO_SYSROOT") || (name == "CURDIR")); } //-------------------------------------------------------------------------------------------------- /** * Gets the file system path to the file in which environment variabls are saved. **/ //-------------------------------------------------------------------------------------------------- static std::string GetSaveFilePath ( const mk::BuildParams_t& buildParams ) //-------------------------------------------------------------------------------------------------- { return path::Combine(buildParams.workingDir, "mktool_environment"); } //-------------------------------------------------------------------------------------------------- /** * Saves the environment variables (in a file in the build's working directory) * for later use by MatchesSaved(). */ //-------------------------------------------------------------------------------------------------- void Save ( const mk::BuildParams_t& buildParams ) //-------------------------------------------------------------------------------------------------- { auto filePath = GetSaveFilePath(buildParams); // Make sure the containing directory exists. file::MakeDir(buildParams.workingDir); // Open the file std::ofstream saveFile(filePath); if (!saveFile.is_open()) { throw mk::Exception_t( mk::format(LE_I18N("Failed to open file '%s' for writing."), filePath) ); } // Write each environment variable as a line in the file. for (int i = 0; environ[i] != NULL; i++) { saveFile << environ[i] << '\n'; if (saveFile.fail()) { throw mk::Exception_t( mk::format(LE_I18N("Error writing to file '%s'."), filePath) ); } } // Close the file. saveFile.close(); if (saveFile.fail()) { throw mk::Exception_t( mk::format(LE_I18N("Error closing file '%s'."), filePath) ); } } //-------------------------------------------------------------------------------------------------- /** * Compares the current environment variables with those stored in the build's working directory. * * @return true if the environment variabls are effectively the same or * false if there's a significant difference. */ //-------------------------------------------------------------------------------------------------- bool MatchesSaved ( const mk::BuildParams_t& buildParams ) //-------------------------------------------------------------------------------------------------- { auto filePath = GetSaveFilePath(buildParams); if (!file::FileExists(filePath)) { if (buildParams.beVerbose) { std::cout << LE_I18N("Environment variables from previous run not found.") << std::endl; } return false; } // Open the file std::ifstream saveFile(filePath); if (!saveFile.is_open()) { throw mk::Exception_t( mk::format(LE_I18N("Failed to open file '%s' for reading."), filePath) ); } int i; char lineBuff[8 * 1024]; // For each environment variable in the process's current set, for (i = 0; environ[i] != NULL; i++) { // Read a line from the file (discarding '\n') and check for EOF or error. saveFile.getline(lineBuff, sizeof(lineBuff)); if (saveFile.eof()) { if (buildParams.beVerbose) { std::cout << mk::format(LE_I18N("Env var '%s' was added."), environ[i]) << std::endl; } goto different; } else if (!saveFile.good()) { throw mk::Exception_t( mk::format(LE_I18N("Error reading from file '%s'."), filePath) ); } // Compare the line from the file with the environment variable. if (strcmp(environ[i], lineBuff) != 0) { if (buildParams.beVerbose) { std::cout << mk::format(LE_I18N("Env var '%s' became '%s'."), lineBuff, environ[i]) << std::endl; } goto different; } } // Read one more line to make sure we get an end-of-file, otherwise there are less args // this time than last time. saveFile.getline(lineBuff, sizeof(lineBuff)); if (saveFile.eof()) { return true; } if (buildParams.beVerbose) { std::cout << mk::format(LE_I18N("Env var '%s' was removed."), lineBuff) << std::endl; } different: if (buildParams.beVerbose) { std::cout << LE_I18N("Environment variables are different this time.") << std::endl; } return false; } } // namespace envVars <commit_msg>Coverity fix CID 157303 - tainted string<commit_after>//-------------------------------------------------------------------------------------------------- /** * @file envVars.cpp * * Environment variable helper functions used by various modules. * * Copyright (C) Sierra Wireless Inc. */ //-------------------------------------------------------------------------------------------------- #include "mkTools.h" #include <string.h> //-------------------------------------------------------------------------------------------------- /** * Maximum length of the environment variable */ //-------------------------------------------------------------------------------------------------- #define ENV_VAR_MAX_LEN 1024 /// The standard C environment variable list. extern char**environ; namespace envVars { //-------------------------------------------------------------------------------------------------- /** * Safely copy the environment variable. */ //-------------------------------------------------------------------------------------------------- static void SafeCopyEnvVar ( char* dst, ///< Destination pointer. const char* src, ///< Source pointer. uint32_t dstSize ///< Destination buffer size. ) { // If variable is longer than MAX_LEN, it will be truncated. Zero at the end is guaranteed. strncpy(dst, src, dstSize - 1); dst[dstSize - 1] = '\0'; } //-------------------------------------------------------------------------------------------------- /** * Fetch the value of a given optional environment variable. * * @return The value ("" if not found). */ //-------------------------------------------------------------------------------------------------- std::string Get ( const std::string& name ///< The name of the environment variable. ) //-------------------------------------------------------------------------------------------------- { char envVar[ENV_VAR_MAX_LEN] = {0}; const char* value = getenv(name.c_str()); if (value == nullptr) { return std::string(); } SafeCopyEnvVar(envVar, value, sizeof(envVar)); return std::string(envVar); } //-------------------------------------------------------------------------------------------------- /** * Fetch the value of a given mandatory environment variable. * * @return The value. * * @throw Exception if environment variable not found. */ //-------------------------------------------------------------------------------------------------- std::string GetRequired ( const std::string& name ///< The name of the environment variable. ) //-------------------------------------------------------------------------------------------------- { char envVar[ENV_VAR_MAX_LEN] = {0}; const char* value = getenv(name.c_str()); if (value == nullptr) { throw mk::Exception_t( mk::format(LE_I18N("The required environment variable %s has not been set."), name) ); } SafeCopyEnvVar(envVar, value, sizeof(envVar)); return std::string(envVar); } //-------------------------------------------------------------------------------------------------- /** * Set the value of a given environment variable. If the variable already exists, replaces its * value. */ //-------------------------------------------------------------------------------------------------- void Set ( const std::string& name, ///< The name of the environment variable. const std::string& value ///< The value of the environment variable. ) //-------------------------------------------------------------------------------------------------- { if (setenv(name.c_str(), value.c_str(), true /* overwrite existing */) != 0) { throw mk::Exception_t( mk::format(LE_I18N("Failed to set environment variable '%s' to '%s'."), name, value) ); } } //-------------------------------------------------------------------------------------------------- /** * Set compiler, linker, etc. environment variables according to the target device type, if they're * not already set. */ //-------------------------------------------------------------------------------------------------- static void SetToolChainVars ( const mk::BuildParams_t& buildParams ) //-------------------------------------------------------------------------------------------------- { if (!buildParams.cCompilerPath.empty()) { auto cCompilerPath = buildParams.cCompilerPath; if (!buildParams.compilerCachePath.empty()) { cCompilerPath = buildParams.compilerCachePath + " " + buildParams.cCompilerPath; } Set("CC", cCompilerPath); } if (!buildParams.cxxCompilerPath.empty()) { auto cxxCompilerPath = buildParams.cxxCompilerPath; if (!buildParams.compilerCachePath.empty()) { cxxCompilerPath = buildParams.compilerCachePath + " " + buildParams.cxxCompilerPath; } Set("CXX", cxxCompilerPath); } if (!buildParams.toolChainDir.empty()) { Set("TOOLCHAIN_DIR", buildParams.toolChainDir); } if (!buildParams.toolChainPrefix.empty()) { Set("TOOLCHAIN_PREFIX", buildParams.toolChainPrefix); } if (!buildParams.sysrootDir.empty()) { Set("LEGATO_SYSROOT", buildParams.sysrootDir); } if (!buildParams.linkerPath.empty()) { Set("LD", buildParams.linkerPath); } if (!buildParams.archiverPath.empty()) { Set("AR", buildParams.archiverPath); } if (!buildParams.assemblerPath.empty()) { Set("AS", buildParams.assemblerPath); } if (!buildParams.stripPath.empty()) { Set("STRIP", buildParams.stripPath); } if (!buildParams.objcopyPath.empty()) { Set("OBJCOPY", buildParams.objcopyPath); } if (!buildParams.readelfPath.empty()) { Set("READELF", buildParams.readelfPath); } else { std::cout << "*************************** readelfPath is empty\n"; } if (!buildParams.compilerCachePath.empty()) { Set("CCACHE", buildParams.compilerCachePath); } } //---------------------------------------------------------------------------------------------- /** * Adds target-specific environment variables (e.g., LEGATO_TARGET) to the process's environment. * * The environment will get inherited by any child processes, including the shell that is used * to run the compiler and linker. Also, this allows these environment variables to be used in * paths in .sdef, .adef, and .cdef files. */ //---------------------------------------------------------------------------------------------- void SetTargetSpecific ( const mk::BuildParams_t& buildParams ) //-------------------------------------------------------------------------------------------------- { // WARNING: If you add another target-specific variable, remember to update IsReserved(). // Set compiler, linker, etc variables specific to the target device type, if they're not set. SetToolChainVars(buildParams); // Set LEGATO_TARGET. Set("LEGATO_TARGET", buildParams.target); // Set LEGATO_BUILD based on the contents of LEGATO_ROOT, which must be already defined. std::string path = GetRequired("LEGATO_ROOT"); if (path.empty()) { throw mk::Exception_t(LE_I18N("LEGATO_ROOT environment variable is empty.")); } path = path::Combine(path, "build/" + buildParams.target); Set("LEGATO_BUILD", path); } //---------------------------------------------------------------------------------------------- /** * Checks if a given environment variable name is one of the reserved environment variable names * (e.g., LEGATO_TARGET). * * @return true if reserved, false if not. */ //---------------------------------------------------------------------------------------------- bool IsReserved ( const std::string& name ///< Name of the variable. ) //-------------------------------------------------------------------------------------------------- { return ( (name == "LEGATO_ROOT") || (name == "LEGATO_TARGET") || (name == "LEGATO_BUILD") || (name == "LEGATO_SYSROOT") || (name == "CURDIR")); } //-------------------------------------------------------------------------------------------------- /** * Gets the file system path to the file in which environment variabls are saved. **/ //-------------------------------------------------------------------------------------------------- static std::string GetSaveFilePath ( const mk::BuildParams_t& buildParams ) //-------------------------------------------------------------------------------------------------- { return path::Combine(buildParams.workingDir, "mktool_environment"); } //-------------------------------------------------------------------------------------------------- /** * Saves the environment variables (in a file in the build's working directory) * for later use by MatchesSaved(). */ //-------------------------------------------------------------------------------------------------- void Save ( const mk::BuildParams_t& buildParams ) //-------------------------------------------------------------------------------------------------- { auto filePath = GetSaveFilePath(buildParams); // Make sure the containing directory exists. file::MakeDir(buildParams.workingDir); // Open the file std::ofstream saveFile(filePath); if (!saveFile.is_open()) { throw mk::Exception_t( mk::format(LE_I18N("Failed to open file '%s' for writing."), filePath) ); } // Write each environment variable as a line in the file. for (int i = 0; environ[i] != NULL; i++) { saveFile << environ[i] << '\n'; if (saveFile.fail()) { throw mk::Exception_t( mk::format(LE_I18N("Error writing to file '%s'."), filePath) ); } } // Close the file. saveFile.close(); if (saveFile.fail()) { throw mk::Exception_t( mk::format(LE_I18N("Error closing file '%s'."), filePath) ); } } //-------------------------------------------------------------------------------------------------- /** * Compares the current environment variables with those stored in the build's working directory. * * @return true if the environment variabls are effectively the same or * false if there's a significant difference. */ //-------------------------------------------------------------------------------------------------- bool MatchesSaved ( const mk::BuildParams_t& buildParams ) //-------------------------------------------------------------------------------------------------- { auto filePath = GetSaveFilePath(buildParams); if (!file::FileExists(filePath)) { if (buildParams.beVerbose) { std::cout << LE_I18N("Environment variables from previous run not found.") << std::endl; } return false; } // Open the file std::ifstream saveFile(filePath); if (!saveFile.is_open()) { throw mk::Exception_t( mk::format(LE_I18N("Failed to open file '%s' for reading."), filePath) ); } int i; char lineBuff[8 * 1024]; // For each environment variable in the process's current set, for (i = 0; environ[i] != NULL; i++) { // Read a line from the file (discarding '\n') and check for EOF or error. saveFile.getline(lineBuff, sizeof(lineBuff)); if (saveFile.eof()) { if (buildParams.beVerbose) { std::cout << mk::format(LE_I18N("Env var '%s' was added."), environ[i]) << std::endl; } goto different; } else if (!saveFile.good()) { throw mk::Exception_t( mk::format(LE_I18N("Error reading from file '%s'."), filePath) ); } // Compare the line from the file with the environment variable. if (strcmp(environ[i], lineBuff) != 0) { if (buildParams.beVerbose) { std::cout << mk::format(LE_I18N("Env var '%s' became '%s'."), lineBuff, environ[i]) << std::endl; } goto different; } } // Read one more line to make sure we get an end-of-file, otherwise there are less args // this time than last time. saveFile.getline(lineBuff, sizeof(lineBuff)); if (saveFile.eof()) { return true; } if (buildParams.beVerbose) { std::cout << mk::format(LE_I18N("Env var '%s' was removed."), lineBuff) << std::endl; } different: if (buildParams.beVerbose) { std::cout << LE_I18N("Environment variables are different this time.") << std::endl; } return false; } } // namespace envVars <|endoftext|>
<commit_before>// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include <luabind/luabind.hpp> #include <luabind/class_info.hpp> struct X { void f() {} int x; int y; }; void test_main(lua_State* L) { using namespace luabind; bind_class_info(L); module(L) [ class_<X>("X") .def(constructor<>()) .def("f", &X::f) .def_readonly("x", &X::x) .def_readonly("y", &X::y) ]; DOSTRING(L, "x = X()\n" "info = class_info(x)\n" "assert(info.name == 'X')\n" "assert(info.methods['f'] == x.f)\n" "assert(info.methods['__init'] == x.__init)\n" "assert(info.attributes[1] == 'y')\n" "assert(info.attributes[2] == 'x')\n" "names = class_names()\n" "assert(type(names) == 'table')\n" "assert(#names == 2)\n" "assert(names[1] == 'X' or names[2] == 'X')\n" "assert(names[1] == 'class_info_data' or names[2] == 'class_info_data')\n" ); } <commit_msg>Test that class_info() don't crash when passed non-luabind objects.<commit_after>// Copyright Daniel Wallin 2009. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test.hpp" #include <luabind/luabind.hpp> #include <luabind/class_info.hpp> struct X { void f() {} int x; int y; }; void test_main(lua_State* L) { using namespace luabind; bind_class_info(L); module(L) [ class_<X>("X") .def(constructor<>()) .def("f", &X::f) .def_readonly("x", &X::x) .def_readonly("y", &X::y) ]; DOSTRING(L, "x = X()\n" "info = class_info(x)\n" "assert(info.name == 'X')\n" "assert(info.methods['f'] == x.f)\n" "assert(info.methods['__init'] == x.__init)\n" "assert(info.attributes[1] == 'y')\n" "assert(info.attributes[2] == 'x')\n" "info = class_info(2)\n" "assert(info.name == 'number')\n" "assert(#info.methods == 0)\n" "assert(#info.attributes == 0)\n" "names = class_names()\n" "assert(type(names) == 'table')\n" "assert(#names == 2)\n" "assert(names[1] == 'X' or names[2] == 'X')\n" "assert(names[1] == 'class_info_data' or names[2] == 'class_info_data')\n" ); } <|endoftext|>
<commit_before>#include "test.hh" #include "../src/controller.cc" #include "mock-ptrace.hh" static int test_thread(void *priv) { return 0; } TEST(controllerForkError) { IController &controller = IController::getInstance(); MockPtrace &ptrace = (MockPtrace &)IPtrace::getInstance(); EXPECT_CALL(ptrace, forkAndAttach()) .Times(AtLeast(1)) .WillRepeatedly(Return(-1)); controller.run(); } TEST(controllerAddProcessForkError) { IController &controller = IController::getInstance(); MockPtrace &ptrace = (MockPtrace &)IPtrace::getInstance(); EXPECT_CALL(ptrace, forkAndAttach()) .Times(AtLeast(1)) .WillRepeatedly(Return(-1)); controller.addThread(test_thread, NULL); controller.run(); } TEST(controllerRunChild, DEADLINE_REALTIME_MS(10000)) { IController &controller = IController::getInstance(); MockPtrace &ptrace = (MockPtrace &)IPtrace::getInstance(); EXPECT_CALL(ptrace, forkAndAttach()) .Times(AtLeast(1)) .WillRepeatedly(Return(100)); IPtrace::PtraceEvent ev, evDefault; evDefault.type = ptrace_exit; evDefault.eventId = 0; ev.type = ptrace_breakpoint; ev.eventId = 100; ev.addr = NULL; EXPECT_CALL(ptrace, continueExecution(_)) .Times(AtLeast(1)) .WillOnce(Return(ev)) .WillRepeatedly(Return(evDefault)); EXPECT_CALL(ptrace, singleStep(_)) .Times(AtLeast(1)); // Add two threads controller.addThread(test_thread, NULL); controller.addThread(test_thread, NULL); controller.run(); } TEST(controllerTestThreadRemoval) { Controller &controller = (Controller &)IController::getInstance(); MockPtrace &ptrace = (MockPtrace &)IPtrace::getInstance(); IPtrace::PtraceEvent ev; EXPECT_CALL(ptrace, singleStep(_)) .Times(AtLeast(1)); ev.addr = (void *)Controller::threadExit; ev.eventId = 10; ev.type = ptrace_breakpoint; controller.addThread(test_thread, NULL); controller.addThread(test_thread, NULL); ASSERT_EQ(controller.m_nThreads, 2); // Will remove thread since it exited controller.handleBreakpoint(ev); ASSERT_EQ(controller.m_nThreads, 1); } <commit_msg>controller: unit test: Test scheduler lock/unlock<commit_after>#include "test.hh" #include "../src/controller.cc" #include "mock-ptrace.hh" static int test_thread(void *priv) { return 0; } class MockThreadSelector : public Controller::IThreadSelector { public: MOCK_METHOD4(selectThread, int(int curThread, int nThreads, uint64_t timeUs, const IPtrace::PtraceEvent *)); }; TEST(controllerForkError) { IController &controller = IController::getInstance(); MockPtrace &ptrace = (MockPtrace &)IPtrace::getInstance(); EXPECT_CALL(ptrace, forkAndAttach()) .Times(AtLeast(1)) .WillRepeatedly(Return(-1)); controller.run(); } TEST(controllerAddProcessForkError) { IController &controller = IController::getInstance(); MockPtrace &ptrace = (MockPtrace &)IPtrace::getInstance(); EXPECT_CALL(ptrace, forkAndAttach()) .Times(AtLeast(1)) .WillRepeatedly(Return(-1)); controller.addThread(test_thread, NULL); controller.run(); } TEST(controllerRunChild, DEADLINE_REALTIME_MS(10000)) { IController &controller = IController::getInstance(); MockPtrace &ptrace = (MockPtrace &)IPtrace::getInstance(); EXPECT_CALL(ptrace, forkAndAttach()) .Times(AtLeast(1)) .WillRepeatedly(Return(100)); IPtrace::PtraceEvent ev, evDefault; evDefault.type = ptrace_exit; evDefault.eventId = 0; ev.type = ptrace_breakpoint; ev.eventId = 100; ev.addr = NULL; EXPECT_CALL(ptrace, continueExecution(_)) .Times(AtLeast(1)) .WillOnce(Return(ev)) .WillRepeatedly(Return(evDefault)); EXPECT_CALL(ptrace, singleStep(_)) .Times(AtLeast(1)); // Add two threads controller.addThread(test_thread, NULL); controller.addThread(test_thread, NULL); controller.run(); } TEST(controllerTestThreadRemoval) { Controller &controller = (Controller &)IController::getInstance(); MockPtrace &ptrace = (MockPtrace &)IPtrace::getInstance(); IPtrace::PtraceEvent ev; EXPECT_CALL(ptrace, singleStep(_)) .Times(AtLeast(1)); ev.addr = (void *)Controller::threadExit; ev.eventId = 10; ev.type = ptrace_breakpoint; controller.addThread(test_thread, NULL); controller.addThread(test_thread, NULL); ASSERT_EQ(controller.m_nThreads, 2); // Will remove thread since it exited controller.handleBreakpoint(ev); ASSERT_EQ(controller.m_nThreads, 1); } TEST(controllerThreadScheduling) { Controller &controller = (Controller &)IController::getInstance(); MockPtrace &ptrace = (MockPtrace &)IPtrace::getInstance(); IPtrace::PtraceEvent ev; ev.type = ptrace_breakpoint; ev.eventId = 100; ev.addr = (void *)(((unsigned long)test_thread) + 1); // No function! EXPECT_CALL(ptrace, continueExecution(_)) .Times(AtLeast(1)) .WillRepeatedly(Return(ev)); EXPECT_CALL(ptrace, singleStep(_)) .Times(AtLeast(1)); // Add two threads controller.addThread(test_thread, NULL); controller.addThread(test_thread, NULL); MockThreadSelector selector; controller.setThreadSelector(&selector); EXPECT_CALL(selector, selectThread(_,_,_,_)) .Times(Exactly(1)) .WillOnce(Return(1)); EXPECT_CALL(ptrace, saveRegisters(_,_)) .Times(AtLeast(1)); EXPECT_CALL(ptrace, loadRegisters(_,_)) .Times(AtLeast(1)); ASSERT_EQ(controller.m_curThread, 0); controller.continueExecution(); ASSERT_EQ(controller.m_curThread, 1); int level = controller.lockScheduler(); ASSERT_EQ(level, 0); // Should not have changed thread controller.continueExecution(); ASSERT_EQ(controller.m_curThread, 1); controller.unlockScheduler(level); } <|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. *****************************************************************************/ /** * @file **/ #include <iostream> #include <string> #include <vector> #include "gflags/gflags.h" #include "modules/common/log.h" #include "modules/common/math/vec2d.h" #include "modules/common/util/util.h" #include "modules/map/pnc_map/path.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/reference_line/qp_spline_reference_line_smoother.h" #include "modules/planning/reference_line/reference_line.h" #include "modules/planning/reference_line/reference_line_smoother.h" DEFINE_string(input_file, "", "input file with format x,y per line"); DEFINE_string(output_file, "", "output file with format x,y per line"); DEFINE_double(anchor_step_length, 5.0, "Smooth every 5 meters"); DEFINE_double(smooth_length, 200, "Smooth this amount of length "); DEFINE_double(lateral_bound, 0.2, "Lateral bound"); DEFINE_double(longitudinal_bound, 1.0, "Longitudinal bound"); namespace apollo { namespace planning { using common::math::LineSegment2d; using common::math::Vec2d; using common::util::DistanceXY; using hdmap::MapPathPoint; class SmootherUtil { public: explicit SmootherUtil(const std::string& filename) { filename_ = filename; std::ifstream ifs(filename.c_str(), std::ifstream::in); std::string point_str; while (std::getline(ifs, point_str)) { std::size_t idx = point_str.find(','); if (idx == std::string::npos) { continue; } auto x_str = point_str.substr(0, idx); auto y_str = point_str.substr(idx + 1); raw_points_.emplace_back(std::stod(x_str), std::stod(y_str)); } CHECK(common::util::GetProtoFromFile(FLAGS_smoother_config_filename, &config_)) << "Failed to read smoother config file: " << FLAGS_smoother_config_filename; } bool Smooth() { if (raw_points_.size() <= 2) { AERROR << "the original point size is " << raw_points_.size(); return false; } for (std::size_t i = 1; i < raw_points_.size(); ++i) { std::vector<ReferencePoint> ref_points; std::size_t j = i; for (double s = 0.0; s < FLAGS_smooth_length && j < raw_points_.size(); ++j) { LineSegment2d segment(raw_points_[j - 1], raw_points_[j]); ref_points.emplace_back(MapPathPoint(raw_points_[j], segment.heading()), 0.0, 0.0, 0.0, 0.0); s += segment.length(); } i = std::max(i, j - 1); raw_reference_lines_.emplace_back(ref_points); } for (std::size_t i = 0; i < raw_reference_lines_.size(); ++i) { const auto& raw_ref_line = raw_reference_lines_[i]; ReferencePoint init_point; if (i == 0) { init_point = raw_ref_line.GetReferencePoint(0.0); } else { init_point = raw_reference_lines_[i - 1].reference_points().back(); } const auto anchor_points = CreateAnchorPoints(init_point, raw_ref_line); std::unique_ptr<ReferenceLineSmoother> smoother_ptr( new QpSplineReferenceLineSmoother(config_)); smoother_ptr->SetAnchorPoints(anchor_points); ReferenceLine ref_line; if (!smoother_ptr->Smooth(raw_reference_lines_[i], &ref_line)) { AERROR << "smooth failed with reference line points: " << raw_reference_lines_[i].reference_points().size() << " Length: " << raw_reference_lines_[i].Length(); return false; } reference_points_.insert(reference_points_.end(), ref_line.reference_points().begin() + 1, ref_line.reference_points().end()); } return true; } void Export(const std::string& filename) { std::ofstream ofs(filename.c_str()); ofs.precision(6); double s = 0.0; for (std::size_t i = 0; i + 1 < reference_points_.size(); ++i) { const auto& point = reference_points_[i]; ofs << std::fixed << "{\"kappa\": " << point.kappa() << ", \"s\": " << s << ", \"theta\": " << point.heading() << ", \"x\":" << point.x() << ", \"y\":" << point.y() << ", \"dkappa\":" << point.dkappa() << "}" << std::endl; s += DistanceXY(reference_points_[i + 1], reference_points_[i]); } ofs.close(); AINFO << "Smoothed result saved to " << filename; } private: std::vector<AnchorPoint> CreateAnchorPoints(const ReferencePoint& init_point, const ReferenceLine& ref_line) { std::vector<AnchorPoint> anchor_points; int num_of_anchors = std::max( 2, static_cast<int>(ref_line.Length() / FLAGS_anchor_step_length + 0.5)); std::vector<double> anchor_s; common::util::uniform_slice(0.0, ref_line.Length(), num_of_anchors - 1, &anchor_s); bool set_init_point = false; for (const double s : anchor_s) { ReferencePoint ref_point; if (!set_init_point) { set_init_point = true; ref_point = init_point; } else { ref_point = ref_line.GetReferencePoint(s); } AnchorPoint anchor; anchor.path_point.set_x(ref_point.x()); anchor.path_point.set_y(ref_point.y()); anchor.path_point.set_z(0.0); anchor.path_point.set_s(s); anchor.path_point.set_theta(ref_point.heading()); anchor.lateral_bound = FLAGS_lateral_bound; anchor.longitudinal_bound = FLAGS_longitudinal_bound; anchor_points.emplace_back(anchor); } anchor_points.front().longitudinal_bound = 1e-6; anchor_points.front().lateral_bound = 1e-6; anchor_points.front().enforced = true; anchor_points.back().longitudinal_bound = 1e-6; anchor_points.back().lateral_bound = 1e-6; anchor_points.back().enforced = true; return anchor_points; } private: std::string filename_; std::vector<common::math::Vec2d> raw_points_; std::vector<ReferenceLine> raw_reference_lines_; std::vector<ReferencePoint> reference_points_; ReferenceLineSmootherConfig config_; }; } // namespace planning } // namespace apollo int main(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); if (FLAGS_input_file.empty()) { AERROR << "need to provide --input_file"; return 0; } apollo::planning::SmootherUtil smoother_util(FLAGS_input_file); if (!smoother_util.Smooth()) { AERROR << "Failed to smooth a the line"; } if (FLAGS_output_file.empty()) { FLAGS_output_file = FLAGS_input_file + ".smoothed"; AINFO << "Output file not provided, set to: " << FLAGS_output_file; } smoother_util.Export(FLAGS_output_file); return 0; } <commit_msg>smooth tool: change stitch point flexibility to zero<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. *****************************************************************************/ /** * @file **/ #include <iostream> #include <string> #include <vector> #include "gflags/gflags.h" #include "modules/common/log.h" #include "modules/common/math/vec2d.h" #include "modules/common/util/util.h" #include "modules/map/pnc_map/path.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/reference_line/qp_spline_reference_line_smoother.h" #include "modules/planning/reference_line/reference_line.h" #include "modules/planning/reference_line/reference_line_smoother.h" DEFINE_string(input_file, "", "input file with format x,y per line"); DEFINE_string(output_file, "", "output file with format x,y per line"); DEFINE_double(anchor_step_length, 5.0, "Smooth every 5 meters"); DEFINE_double(smooth_length, 200, "Smooth this amount of length "); DEFINE_double(lateral_bound, 0.2, "Lateral bound"); DEFINE_double(longitudinal_bound, 1.0, "Longitudinal bound"); namespace apollo { namespace planning { using common::math::LineSegment2d; using common::math::Vec2d; using common::util::DistanceXY; using hdmap::MapPathPoint; class SmootherUtil { public: explicit SmootherUtil(const std::string& filename) { filename_ = filename; std::ifstream ifs(filename.c_str(), std::ifstream::in); std::string point_str; while (std::getline(ifs, point_str)) { std::size_t idx = point_str.find(','); if (idx == std::string::npos) { continue; } auto x_str = point_str.substr(0, idx); auto y_str = point_str.substr(idx + 1); raw_points_.emplace_back(std::stod(x_str), std::stod(y_str)); } CHECK(common::util::GetProtoFromFile(FLAGS_smoother_config_filename, &config_)) << "Failed to read smoother config file: " << FLAGS_smoother_config_filename; } bool Smooth() { if (raw_points_.size() <= 2) { AERROR << "the original point size is " << raw_points_.size(); return false; } for (std::size_t i = 1; i < raw_points_.size(); ++i) { std::vector<ReferencePoint> ref_points; std::size_t j = i; for (double s = 0.0; s < FLAGS_smooth_length && j < raw_points_.size(); ++j) { LineSegment2d segment(raw_points_[j - 1], raw_points_[j]); ref_points.emplace_back(MapPathPoint(raw_points_[j], segment.heading()), 0.0, 0.0, 0.0, 0.0); s += segment.length(); } i = std::max(i, j - 1); raw_reference_lines_.emplace_back(ref_points); } for (std::size_t i = 0; i < raw_reference_lines_.size(); ++i) { const auto& raw_ref_line = raw_reference_lines_[i]; ReferencePoint init_point; if (i == 0) { init_point = raw_ref_line.GetReferencePoint(0.0); } else { init_point = raw_reference_lines_[i - 1].reference_points().back(); } const auto anchor_points = CreateAnchorPoints(init_point, raw_ref_line); std::unique_ptr<ReferenceLineSmoother> smoother_ptr( new QpSplineReferenceLineSmoother(config_)); smoother_ptr->SetAnchorPoints(anchor_points); ReferenceLine ref_line; if (!smoother_ptr->Smooth(raw_reference_lines_[i], &ref_line)) { AERROR << "smooth failed with reference line points: " << raw_reference_lines_[i].reference_points().size() << " Length: " << raw_reference_lines_[i].Length(); return false; } reference_points_.insert(reference_points_.end(), ref_line.reference_points().begin() + 1, ref_line.reference_points().end()); } return true; } void Export(const std::string& filename) { std::ofstream ofs(filename.c_str()); ofs.precision(6); double s = 0.0; for (std::size_t i = 0; i + 1 < reference_points_.size(); ++i) { const auto& point = reference_points_[i]; ofs << std::fixed << "{\"kappa\": " << point.kappa() << ", \"s\": " << s << ", \"theta\": " << point.heading() << ", \"x\":" << point.x() << ", \"y\":" << point.y() << ", \"dkappa\":" << point.dkappa() << "}" << std::endl; s += DistanceXY(reference_points_[i + 1], reference_points_[i]); } ofs.close(); AINFO << "Smoothed result saved to " << filename; } private: std::vector<AnchorPoint> CreateAnchorPoints(const ReferencePoint& init_point, const ReferenceLine& ref_line) { std::vector<AnchorPoint> anchor_points; int num_of_anchors = std::max( 2, static_cast<int>(ref_line.Length() / FLAGS_anchor_step_length + 0.5)); std::vector<double> anchor_s; common::util::uniform_slice(0.0, ref_line.Length(), num_of_anchors - 1, &anchor_s); bool set_init_point = false; for (const double s : anchor_s) { ReferencePoint ref_point; if (!set_init_point) { set_init_point = true; ref_point = init_point; } else { ref_point = ref_line.GetReferencePoint(s); } AnchorPoint anchor; anchor.path_point.set_x(ref_point.x()); anchor.path_point.set_y(ref_point.y()); anchor.path_point.set_z(0.0); anchor.path_point.set_s(s); anchor.path_point.set_theta(ref_point.heading()); anchor.lateral_bound = FLAGS_lateral_bound; anchor.longitudinal_bound = FLAGS_longitudinal_bound; anchor_points.emplace_back(anchor); } anchor_points.front().longitudinal_bound = 0; anchor_points.front().lateral_bound = 0; anchor_points.front().enforced = true; anchor_points.back().longitudinal_bound = 0; anchor_points.back().lateral_bound = 0; anchor_points.back().enforced = true; return anchor_points; } private: std::string filename_; std::vector<common::math::Vec2d> raw_points_; std::vector<ReferenceLine> raw_reference_lines_; std::vector<ReferencePoint> reference_points_; ReferenceLineSmootherConfig config_; }; } // namespace planning } // namespace apollo int main(int argc, char* argv[]) { google::InitGoogleLogging(argv[0]); google::ParseCommandLineFlags(&argc, &argv, true); if (FLAGS_input_file.empty()) { AERROR << "need to provide --input_file"; return 0; } apollo::planning::SmootherUtil smoother_util(FLAGS_input_file); if (!smoother_util.Smooth()) { AERROR << "Failed to smooth a the line"; } if (FLAGS_output_file.empty()) { FLAGS_output_file = FLAGS_input_file + ".smoothed"; AINFO << "Output file not provided, set to: " << FLAGS_output_file; } smoother_util.Export(FLAGS_output_file); return 0; } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. Eigen itself is part of the KDE project. // // Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com> // // Eigen 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 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" struct Good1 { MatrixXd m; // good: m will allocate its own array, taking care of alignment. Good1() : m(20,20) {} }; struct Good2 { Matrix3d m; // good: m's size isn't a multiple of 16 bytes, so m doesn't have to be aligned }; struct Good3 { Vector2f m; // good: same reason }; struct Bad4 { Vector2d m; // bad: sizeof(m)%16==0 so alignment is required }; struct Bad5 { Matrix<float, 2, 6> m; // bad: same reason }; struct Bad6 { Matrix<double, 3, 4> m; // bad: same reason }; struct Good7 { EIGEN_MAKE_ALIGNED_OPERATOR_NEW Vector2d m; float f; // make the struct have sizeof%16!=0 to make it a little more tricky when we allow an array of 2 such objects }; struct Good8 { EIGEN_MAKE_ALIGNED_OPERATOR_NEW float f; // try the f at first -- the EIGEN_ALIGN_128 attribute of m should make that still work Matrix4f m; }; struct Good9 { Matrix<float,2,2,DontAlign> m; // good: no alignment requested float f; }; template<bool Align> struct Depends { EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(Align) Vector2d m; float f; }; template<typename T> void check_unalignedassert_good() { T *x, *y; x = new T; delete x; y = new T[2]; delete[] y; } #ifdef EIGEN_ARCH_WANTS_ALIGNMENT template<typename T> void check_unalignedassert_bad() { float buf[sizeof(T)+16]; float *unaligned = buf; while((reinterpret_cast<size_t>(unaligned)&0xf)==0) ++unaligned; // make sure unaligned is really unaligned T *x = ::new(static_cast<void*>(unaligned)) T; x->~T(); } #endif void unalignedassert() { check_unalignedassert_good<Good1>(); check_unalignedassert_good<Good2>(); check_unalignedassert_good<Good3>(); #ifdef EIGEN_ARCH_WANTS_ALIGNMENT VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad4>()); VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad5>()); VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad6>()); #endif check_unalignedassert_good<Good7>(); check_unalignedassert_good<Good8>(); check_unalignedassert_good<Good9>(); check_unalignedassert_good<Depends<true> >(); #ifdef EIGEN_ARCH_WANTS_ALIGNMENT VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Depends<false> >()); #endif } void test_unalignedassert() { CALL_SUBTEST(unalignedassert()); } <commit_msg>oops, #ifdef instead of #if ---> bug<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. Eigen itself is part of the KDE project. // // Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com> // // Eigen 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 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" struct Good1 { MatrixXd m; // good: m will allocate its own array, taking care of alignment. Good1() : m(20,20) {} }; struct Good2 { Matrix3d m; // good: m's size isn't a multiple of 16 bytes, so m doesn't have to be aligned }; struct Good3 { Vector2f m; // good: same reason }; struct Bad4 { Vector2d m; // bad: sizeof(m)%16==0 so alignment is required }; struct Bad5 { Matrix<float, 2, 6> m; // bad: same reason }; struct Bad6 { Matrix<double, 3, 4> m; // bad: same reason }; struct Good7 { EIGEN_MAKE_ALIGNED_OPERATOR_NEW Vector2d m; float f; // make the struct have sizeof%16!=0 to make it a little more tricky when we allow an array of 2 such objects }; struct Good8 { EIGEN_MAKE_ALIGNED_OPERATOR_NEW float f; // try the f at first -- the EIGEN_ALIGN_128 attribute of m should make that still work Matrix4f m; }; struct Good9 { Matrix<float,2,2,DontAlign> m; // good: no alignment requested float f; }; template<bool Align> struct Depends { EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(Align) Vector2d m; float f; }; template<typename T> void check_unalignedassert_good() { T *x, *y; x = new T; delete x; y = new T[2]; delete[] y; } #if EIGEN_ARCH_WANTS_ALIGNMENT template<typename T> void check_unalignedassert_bad() { float buf[sizeof(T)+16]; float *unaligned = buf; while((reinterpret_cast<size_t>(unaligned)&0xf)==0) ++unaligned; // make sure unaligned is really unaligned T *x = ::new(static_cast<void*>(unaligned)) T; x->~T(); } #endif void unalignedassert() { check_unalignedassert_good<Good1>(); check_unalignedassert_good<Good2>(); check_unalignedassert_good<Good3>(); #if EIGEN_ARCH_WANTS_ALIGNMENT VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad4>()); VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad5>()); VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad6>()); #endif check_unalignedassert_good<Good7>(); check_unalignedassert_good<Good8>(); check_unalignedassert_good<Good9>(); check_unalignedassert_good<Depends<true> >(); #if EIGEN_ARCH_WANTS_ALIGNMENT VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Depends<false> >()); #endif } void test_unalignedassert() { CALL_SUBTEST(unalignedassert()); } <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. Eigen itself is part of the KDE project. // // Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com> // // Eigen 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 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" struct Good1 { MatrixXd m; // good: m will allocate its own array, taking care of alignment. Good1() : m(20,20) {} }; struct Good2 { Matrix3d m; // good: m's size isn't a multiple of 16 bytes, so m doesn't have to be aligned }; struct Good3 { Vector2f m; // good: same reason }; struct Bad4 { Vector2d m; // bad: sizeof(m)%16==0 so alignment is required }; struct Bad5 { Matrix<float, 2, 6> m; // bad: same reason }; struct Bad6 { Matrix<double, 3, 4> m; // bad: same reason }; struct Good7 { EIGEN_MAKE_ALIGNED_OPERATOR_NEW Vector2d m; float f; // make the struct have sizeof%16!=0 to make it a little more tricky when we allow an array of 2 such objects }; struct Good8 { EIGEN_MAKE_ALIGNED_OPERATOR_NEW float f; // try the f at first -- the EIGEN_ALIGN_128 attribute of m should make that still work Matrix4f m; }; struct Good9 { Matrix<float,2,2,DontAlign> m; // good: no alignment requested float f; }; template<bool Align> struct Depends { EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(Align) Vector2d m; float f; }; template<typename T> void check_unalignedassert_good() { T *x, *y; x = new T; delete x; y = new T[2]; delete[] y; } #ifdef EIGEN_ARCH_WANTS_ALIGNMENT template<typename T> void check_unalignedassert_bad() { float buf[sizeof(T)+16]; float *unaligned = buf; while((reinterpret_cast<size_t>(unaligned)&0xf)==0) ++unaligned; // make sure unaligned is really unaligned T *x = ::new(static_cast<void*>(unaligned)) T; x->~T(); } #endif void unalignedassert() { check_unalignedassert_good<Good1>(); check_unalignedassert_good<Good2>(); check_unalignedassert_good<Good3>(); #ifdef EIGEN_ARCH_WANTS_ALIGNMENT VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad4>()); VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad5>()); VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad6>()); #endif check_unalignedassert_good<Good7>(); check_unalignedassert_good<Good8>(); check_unalignedassert_good<Good9>(); check_unalignedassert_good<Depends<true> >(); #ifdef EIGEN_ARCH_WANTS_ALIGNMENT VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Depends<false> >()); #endif } void test_unalignedassert() { CALL_SUBTEST(unalignedassert()); } <commit_msg>oops, #ifdef instead of #if ---> bug<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. Eigen itself is part of the KDE project. // // Copyright (C) 2008 Benoit Jacob <jacob.benoit.1@gmail.com> // // Eigen 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 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" struct Good1 { MatrixXd m; // good: m will allocate its own array, taking care of alignment. Good1() : m(20,20) {} }; struct Good2 { Matrix3d m; // good: m's size isn't a multiple of 16 bytes, so m doesn't have to be aligned }; struct Good3 { Vector2f m; // good: same reason }; struct Bad4 { Vector2d m; // bad: sizeof(m)%16==0 so alignment is required }; struct Bad5 { Matrix<float, 2, 6> m; // bad: same reason }; struct Bad6 { Matrix<double, 3, 4> m; // bad: same reason }; struct Good7 { EIGEN_MAKE_ALIGNED_OPERATOR_NEW Vector2d m; float f; // make the struct have sizeof%16!=0 to make it a little more tricky when we allow an array of 2 such objects }; struct Good8 { EIGEN_MAKE_ALIGNED_OPERATOR_NEW float f; // try the f at first -- the EIGEN_ALIGN_128 attribute of m should make that still work Matrix4f m; }; struct Good9 { Matrix<float,2,2,DontAlign> m; // good: no alignment requested float f; }; template<bool Align> struct Depends { EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF(Align) Vector2d m; float f; }; template<typename T> void check_unalignedassert_good() { T *x, *y; x = new T; delete x; y = new T[2]; delete[] y; } #if EIGEN_ARCH_WANTS_ALIGNMENT template<typename T> void check_unalignedassert_bad() { float buf[sizeof(T)+16]; float *unaligned = buf; while((reinterpret_cast<size_t>(unaligned)&0xf)==0) ++unaligned; // make sure unaligned is really unaligned T *x = ::new(static_cast<void*>(unaligned)) T; x->~T(); } #endif void unalignedassert() { check_unalignedassert_good<Good1>(); check_unalignedassert_good<Good2>(); check_unalignedassert_good<Good3>(); #if EIGEN_ARCH_WANTS_ALIGNMENT VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad4>()); VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad5>()); VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Bad6>()); #endif check_unalignedassert_good<Good7>(); check_unalignedassert_good<Good8>(); check_unalignedassert_good<Good9>(); check_unalignedassert_good<Depends<true> >(); #if EIGEN_ARCH_WANTS_ALIGNMENT VERIFY_RAISES_ASSERT(check_unalignedassert_bad<Depends<false> >()); #endif } void test_unalignedassert() { CALL_SUBTEST(unalignedassert()); } <|endoftext|>
<commit_before>/* * Recognizer.cc * * Copyright (C) 2015 Linas Vepstas * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the * exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef _OPENCOG_RECOGNIZER_H #define _OPENCOG_RECOGNIZER_H #include <set> #include <opencog/query/DefaultPatternMatchCB.h> #include <opencog/atoms/pattern/PatternLink.h> #include "BindLinkAPI.h" namespace opencog { /** * Very rough, crude, experimental prototype for the idea that * pattern recognition is the dual of pattern matching. * That is, rather than using one query pattern to search a large * collection of data, this does the opposite: given a single piece of * data, it searches for all rules/queries which apply to it. * * The file /examples/aiml/recog.scm provides a very simple example. * The implementation here is very minimalistic, and does many things * wrong: * -- it fails to perform any type-checking to make sure the variable * constraints are satisfied. * -- AIML wants a left-to-right traversal, this does an omni- * directional exploration. (which is OK, but is not how AIML is * defined...) * -- This hasn't been thought through thoroughly. There are almost * surely some weird gotcha's. */ class Recognizer : public virtual DefaultPatternMatchCB { protected: const Pattern* _pattern; Handle _root; Handle _starter_term; size_t _cnt; bool do_search(PatternMatchEngine*, const Handle&); bool loose_match(const Handle&, const Handle&); public: OrderedHandleSet _rules; Recognizer(AtomSpace* as) : DefaultPatternMatchCB(as) {} virtual void set_pattern(const Variables& vars, const Pattern& pat) { _pattern = &pat; DefaultPatternMatchCB::set_pattern(vars, pat); } virtual bool initiate_search(PatternMatchEngine*); virtual bool node_match(const Handle&, const Handle&); virtual bool link_match(const LinkPtr&, const LinkPtr&); virtual bool fuzzy_match(const Handle&, const Handle&); virtual bool grounding(const HandleMap &var_soln, const HandleMap &term_soln); }; } // namespace opencog #endif // _OPENCOG_RECOGNIZER_H using namespace opencog; // Uncomment below to enable debug print #define DEBUG #ifdef DEBUG #define dbgprt(f, varargs...) logger().fine(f, ##varargs) #else #define dbgprt(f, varargs...) #endif /* ======================================================== */ bool Recognizer::do_search(PatternMatchEngine* pme, const Handle& top) { if (top->isLink()) { // Recursively drill down and explore every possible node as // a search starting point. This is needed, as the patterns we // compare against might not be connected. for (const Handle& h : top->getOutgoingSet()) { _starter_term = top; bool found = do_search(pme, h); if (found) return true; } return false; } IncomingSet iset = get_incoming_set(top); size_t sz = iset.size(); for (size_t i = 0; i < sz; i++) { Handle h(iset[i]); dbgprt("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr\n"); dbgprt("Loop candidate (%lu - %s):\n%s\n", _cnt++, top->toShortString().c_str(), h->toShortString().c_str()); bool found = pme->explore_neighborhood(_root, _starter_term, h); // Terminate search if satisfied. if (found) return true; } return false; } bool Recognizer::initiate_search(PatternMatchEngine* pme) { const HandleSeq& clauses = _pattern->cnf_clauses; _cnt = 0; for (const Handle& h: clauses) { _root = h; bool found = do_search(pme, h); if (found) return true; } return false; } bool Recognizer::node_match(const Handle& npat_h, const Handle& nsoln_h) { if (npat_h == nsoln_h) return true; Type tso = nsoln_h->getType(); if (VARIABLE_NODE == tso or GLOB_NODE == tso) return true; return false; } bool Recognizer::link_match(const LinkPtr& lpat, const LinkPtr& lsoln) { // Self-compares always proceed. if (lpat == lsoln) return true; // mis-matched types are a dead-end. if (lpat->getType() != lsoln->getType()) return false; // Globs are arity-changing. But there is a minimum length. // Note that the inequality is backwards, here: the soln has the // globs! (and so lpat must have arity equal or greater than soln) if (lpat->getArity() < lsoln->getArity()) return false; return true; } bool Recognizer::loose_match(const Handle& npat_h, const Handle& nsoln_h) { Type gtype = nsoln_h->getType(); // Variable matches anything; move to next. if (VARIABLE_NODE == gtype) return true; // Strict match for link types. if (npat_h->getType() != gtype) return false; if (not npat_h->isNode()) return true; // If we are here, we know we have nodes. Ask for a strict match. if (npat_h != nsoln_h) return false; return true; } bool Recognizer::fuzzy_match(const Handle& npat_h, const Handle& nsoln_h) { // If we are here, then there are probably glob nodes in the soln. // Try to match them, rigorously. This might be a bad idea, though; // if we are too rigorous here, and have a bug, we may fail to find // a good pattern. if (not npat_h->isLink() or not nsoln_h->isLink()) return false; const HandleSeq &osg = nsoln_h->getOutgoingSet(); size_t osg_size = osg.size(); // Lets not waste time, if there's no glob there. bool have_glob = false; for (size_t j=0; j<osg_size; j++) { if (osg[j]->getType() == GLOB_NODE) { have_glob = true; break; } } if (not have_glob) return false; const HandleSeq &osp = npat_h->getOutgoingSet(); size_t osp_size = osp.size(); size_t max_size = std::max(osg_size, osp_size); // Do a side-by-side compare. This is not as rigorous as // PatternMatchEngine::tree_compare() nor does it handle the bells // and whistles (ChoiceLink, QuoteLink, etc). for (size_t ip=0, jg=0; ip<osp_size and jg<osg_size; ip++, jg++) { if (GLOB_NODE != osg[jg]->getType()) { if (loose_match(osp[ip], osg[jg])) continue; return false; } // If we are here, we have a glob in the soln. If the glob is at // the end, it eats everything, so its a match. Else, resume // matching at the end of the glob. if ((jg+1) == osg_size) return true; const Handle& post(osg[jg+1]); ip++; while (ip < max_size and not loose_match(osp[ip], post)) { ip++; } // If ip ran past the end, then the post was not found. This is // a mismatch. if (not (ip < max_size)) return false; // Go around again, look for more GlobNodes. Back up by one, so // that the for-loop increment gets us back on track. ip--; } return true; } bool Recognizer::grounding(const HandleMap &var_soln, const HandleMap &term_soln) { Handle rule = term_soln.at(_root); _rules.insert(rule); // Look for more groundings. return false; } Handle opencog::recognize(AtomSpace* as, const Handle& hlink) { PatternLinkPtr bl(PatternLinkCast(hlink)); if (NULL == bl) bl = createPatternLink(*LinkCast(hlink)); Recognizer reco(as); bl->satisfy(reco); HandleSeq hs; for (const Handle& h : reco._rules) hs.push_back(h); return as->add_link(SET_LINK, hs); } <commit_msg>Bug-fix a pattern lookup.<commit_after>/* * Recognizer.cc * * Copyright (C) 2015 Linas Vepstas * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the * exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef _OPENCOG_RECOGNIZER_H #define _OPENCOG_RECOGNIZER_H #include <set> #include <opencog/query/DefaultPatternMatchCB.h> #include <opencog/atoms/pattern/PatternLink.h> #include "BindLinkAPI.h" namespace opencog { /** * Very rough, crude, experimental prototype for the idea that * pattern recognition is the dual of pattern matching. * That is, rather than using one query pattern to search a large * collection of data, this does the opposite: given a single piece of * data, it searches for all rules/queries which apply to it. * * The file /examples/aiml/recog.scm provides a very simple example. * The implementation here is very minimalistic, and does many things * wrong: * -- it fails to perform any type-checking to make sure the variable * constraints are satisfied. * -- AIML wants a left-to-right traversal, this does an omni- * directional exploration. (which is OK, but is not how AIML is * defined...) * -- This hasn't been thought through thoroughly. There are almost * surely some weird gotcha's. */ class Recognizer : public virtual DefaultPatternMatchCB { protected: const Pattern* _pattern; Handle _root; Handle _starter_term; size_t _cnt; bool do_search(PatternMatchEngine*, const Handle&); bool loose_match(const Handle&, const Handle&); public: OrderedHandleSet _rules; Recognizer(AtomSpace* as) : DefaultPatternMatchCB(as) {} virtual void set_pattern(const Variables& vars, const Pattern& pat) { _pattern = &pat; DefaultPatternMatchCB::set_pattern(vars, pat); } virtual bool initiate_search(PatternMatchEngine*); virtual bool node_match(const Handle&, const Handle&); virtual bool link_match(const LinkPtr&, const LinkPtr&); virtual bool fuzzy_match(const Handle&, const Handle&); virtual bool grounding(const HandleMap &var_soln, const HandleMap &term_soln); }; } // namespace opencog #endif // _OPENCOG_RECOGNIZER_H using namespace opencog; // Uncomment below to enable debug print #define DEBUG #ifdef DEBUG #define dbgprt(f, varargs...) logger().fine(f, ##varargs) #else #define dbgprt(f, varargs...) #endif /* ======================================================== */ bool Recognizer::do_search(PatternMatchEngine* pme, const Handle& top) { if (top->isLink()) { // Recursively drill down and explore every possible node as // a search starting point. This is needed, as the patterns we // compare against might not be connected. for (const Handle& h : top->getOutgoingSet()) { _starter_term = top; bool found = do_search(pme, h); if (found) return true; } return false; } IncomingSet iset = get_incoming_set(top); size_t sz = iset.size(); for (size_t i = 0; i < sz; i++) { Handle h(iset[i]); dbgprt("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr\n"); dbgprt("Loop candidate (%lu - %s):\n%s\n", _cnt++, top->toShortString().c_str(), h->toShortString().c_str()); bool found = pme->explore_neighborhood(_root, _starter_term, h); // Terminate search if satisfied. if (found) return true; } return false; } bool Recognizer::initiate_search(PatternMatchEngine* pme) { const HandleSeq& clauses = _pattern->cnf_clauses; _cnt = 0; for (const Handle& h: clauses) { _root = h; bool found = do_search(pme, h); if (found) return true; } return false; } bool Recognizer::node_match(const Handle& npat_h, const Handle& nsoln_h) { if (npat_h == nsoln_h) return true; Type tso = nsoln_h->getType(); if (VARIABLE_NODE == tso or GLOB_NODE == tso) return true; return false; } bool Recognizer::link_match(const LinkPtr& lpat, const LinkPtr& lsoln) { // Self-compares always proceed. if (lpat == lsoln) return true; // mis-matched types are a dead-end. if (lpat->getType() != lsoln->getType()) return false; // Globs are arity-changing. But there is a minimum length. // Note that the inequality is backwards, here: the soln has the // globs! (and so lpat must have arity equal or greater than soln) if (lpat->getArity() < lsoln->getArity()) return false; return true; } bool Recognizer::loose_match(const Handle& npat_h, const Handle& nsoln_h) { Type gtype = nsoln_h->getType(); // Variable matches anything; move to next. if (VARIABLE_NODE == gtype) return true; // Strict match for link types. if (npat_h->getType() != gtype) return false; if (not npat_h->isNode()) return true; // If we are here, we know we have nodes. Ask for a strict match. if (npat_h != nsoln_h) return false; return true; } bool Recognizer::fuzzy_match(const Handle& npat_h, const Handle& nsoln_h) { // If we are here, then there are probably glob nodes in the soln. // Try to match them, fairly rigorously. Exactly what constitutes // an OK match is still a bit up in the air. if (not npat_h->isLink() or not nsoln_h->isLink()) return false; const HandleSeq &osg = nsoln_h->getOutgoingSet(); size_t osg_size = osg.size(); // Lets not waste time, if there's no glob there. bool have_glob = false; for (size_t j=0; j<osg_size; j++) { if (osg[j]->getType() == GLOB_NODE) { have_glob = true; break; } } if (not have_glob) return false; const HandleSeq &osp = npat_h->getOutgoingSet(); size_t osp_size = osp.size(); size_t max_size = std::max(osg_size, osp_size); // Do a side-by-side compare. This is not as rigorous as // PatternMatchEngine::tree_compare() nor does it handle the bells // and whistles (ChoiceLink, QuoteLink, etc). size_t ip=0, jg=0; for (; ip<osp_size and jg<osg_size; ip++, jg++) { if (GLOB_NODE != osg[jg]->getType()) { if (loose_match(osp[ip], osg[jg])) continue; return false; } // If we are here, we have a glob in the soln. If the glob is at // the end, it eats everything, so its a match. Else, resume // matching at the end of the glob. if ((jg+1) == osg_size) return true; const Handle& post(osg[jg+1]); ip++; while (ip < max_size and not loose_match(osp[ip], post)) { ip++; } // If ip ran past the end, then the post was not found. This is // a mismatch. if (not (ip < max_size)) return false; // Go around again, look for more GlobNodes. Back up by one, so // that the for-loop increment gets us back on track. ip--; } // If we are here, then we should have matched up all the atoms; // if we exited the loop because pattern or grounding was short, // then its a mis-match. if (ip != osp_size or jg != osg_size) return false; return true; } bool Recognizer::grounding(const HandleMap &var_soln, const HandleMap &term_soln) { Handle rule = term_soln.at(_root); _rules.insert(rule); // Look for more groundings. return false; } Handle opencog::recognize(AtomSpace* as, const Handle& hlink) { PatternLinkPtr bl(PatternLinkCast(hlink)); if (NULL == bl) bl = createPatternLink(*LinkCast(hlink)); Recognizer reco(as); bl->satisfy(reco); HandleSeq hs; for (const Handle& h : reco._rules) hs.push_back(h); return as->add_link(SET_LINK, hs); } <|endoftext|>
<commit_before>#include <iostream> #include <stdlib.h> #include "color.h" //#include <conio.h> using namespace std; char square[10] = {'o','1','2','3','4','5','6','7','8','9'}; int checkwin(); void board(); int main() { int player = 1,i,choice; char mark; do { board(); player=(player%2)?1:2; cout << "Player " << player << ", enter a number: "; cin >> choice; mark=(player == 1) ? 'X' : 'O'; if (choice == 1 && square[1] == '1') square[1] = mark; else if (choice == 2 && square[2] == '2') square[2] = mark; else if (choice == 3 && square[3] == '3') square[3] = mark; else if (choice == 4 && square[4] == '4') square[4] = mark; else if (choice == 5 && square[5] == '5') square[5] = mark; else if (choice == 6 && square[6] == '6') square[6] = mark; else if (choice == 7 && square[7] == '7') square[7] = mark; else if (choice == 8 && square[8] == '8') square[8] = mark; else if (choice == 9 && square[9] == '9') square[9] = mark; else { cout<<"Invalid move "; player--; cin.ignore(); cin.get(); } i=checkwin(); player++; }while(i==-1); board(); if(i==1) cout<<"==>\aPlayer "<<--player<<" win "; else cout<<"==>\aGame draw"; cin.ignore(); cin.get(); return 0; } /********************************************* FUNCTION TO RETURN GAME STATUS 1 FOR GAME IS OVER WITH RESULT -1 FOR GAME IS IN PROGRESS O GAME IS OVER AND NO RESULT **********************************************/ int checkwin() { if (square[1] == square[2] && square[2] == square[3]) return 1; else if (square[4] == square[5] && square[5] == square[6]) return 1; else if (square[7] == square[8] && square[8] == square[9]) return 1; else if (square[1] == square[4] && square[4] == square[7]) return 1; else if (square[2] == square[5] && square[5] == square[8]) return 1; else if (square[3] == square[6] && square[6] == square[9]) return 1; else if (square[1] == square[5] && square[5] == square[9]) return 1; else if (square[3] == square[5] && square[5] == square[7]) return 1; else if (square[1] != '1' && square[2] != '2' && square[3] != '3' && square[4] != '4' && square[5] != '5' && square[6] != '6' && square[7] != '7' && square[8] != '8' && square[9] != '9') return 0; else return -1; } /******************************************************************* FUNCTION TO DRAW BOARD OF TIC TAC TOE WITH PLAYERS MARK ********************************************************************/ void board() { system("clear"); Color::Modifier red(Color::FG_RED); Color::Modifier bgyellow(Color::BG_YELLOW); cout << bgyellow << red << "\n\n\tTic Tac Toe\n\n"; cout << "Player 1 (X) - Player 2 (O)" << endl << endl; cout << endl; cout << " | | " << endl; cout << " " << square[1] << " | " << square[2] << " | " << square[3] << endl; cout << "_____|_____|_____" << endl; cout << " | | " << endl; cout << " " << square[4] << " | " << square[5] << " | " << square[6] << endl; cout << "_____|_____|_____" << endl; cout << " | | " << endl; cout << " " << square[7] << " | " << square[8] << " | " << square[9] << endl; cout << " | | " << endl << endl; } /******************************************************************* END OF PROJECT ********************************************************************/ <commit_msg>Delete game.cpp<commit_after><|endoftext|>
<commit_before>// Copyright © 2016-2017, Prosoft Engineering, Inc. (A.K.A "Prosoft") // 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 Prosoft 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 PROSOFT ENGINEERING, INC. 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 <prosoft/core/config/config_platform.h> #include <thread> #include "filesystem.hpp" #include "filesystem_change_monitor.hpp" #if PS_HAVE_FILESYSTEM_CHANGE_MONITOR #include "catch.hpp" #include "fstestutils.hpp" using namespace prosoft; using namespace prosoft::filesystem; TEST_CASE("filesystem_monitor") { SECTION("default values") { CHECK(is_set(change_event::all & change_event::created)); CHECK(is_set(change_event::all & change_event::removed)); CHECK(is_set(change_event::all & change_event::renamed)); CHECK(is_set(change_event::all & change_event::content_modified)); CHECK(is_set(change_event::all & change_event::metadata_modified)); change_registration reg; CHECK_FALSE(reg); CHECK_FALSE(reg == change_registration()); change_config cfg; CHECK(cfg.state == nullptr); CHECK(cfg.notification_latency > change_config::latency_type()); CHECK(cfg.events == change_event::all); } WHEN("registration is invalid") { change_registration reg; REQUIRE_FALSE(reg); CHECK_THROWS(stop(reg)); } WHEN("args are invalid") { auto nopcb = [](const change_notifications&){}; CHECK_THROWS(monitor(PS_TEXT(""), change_event::none, change_callback{})); CHECK_THROWS(monitor(PS_TEXT("test"), change_event::none, change_callback{})); CHECK_THROWS(monitor(PS_TEXT("test"), change_event::created, change_callback{})); CHECK_THROWS(recursive_monitor(PS_TEXT(""), change_event::none, change_callback{})); CHECK_THROWS(recursive_monitor(PS_TEXT("test"), change_event::none, change_callback{})); CHECK_THROWS(recursive_monitor(PS_TEXT("test"), change_event::created, change_callback{})); } WHEN("unique change registration goes out of scope") { change_registration reg; { unique_change_registration ureg{recursive_monitor(temp_directory_path(), [](const change_notifications&) { })}; reg = ureg; CHECK(reg); } // The reg may still be valid (if internal state is still alive) but it should no longer be registered as a monitor. CHECK_THROWS(stop(reg)); } SECTION("recursive monitor") { const auto root = canonical(temp_directory_path()) / PS_TEXT("fs17test"); create_directory(root); REQUIRE(exists(root)); std::mutex lock; using guard = std::lock_guard<std::mutex>; change_notifications notes; change_config cfg; cfg.notification_latency = change_config::latency_type{0}; // keep coalescing to a minimum constexpr auto sleep_duration = change_config::latency_type{300}; WHEN("creating a file") { const auto p = root / PS_TEXT("1"); error_code ec; REQUIRE_FALSE(exists(p, ec)); unique_change_registration reg{recursive_monitor(root, cfg, [&lock, &notes](const change_notifications& n) { guard lg{lock}; notes.insert(notes.end(), n.begin(), n.end()); })}; CHECK(reg); create_file(p); std::this_thread::sleep_for(sleep_duration); stop(reg); CHECK(remove(p)); CHECK_FALSE(notes.empty()); const auto count = std::count_if(notes.begin(), notes.end(), [](const change_notification& n) { return created(n); }); CHECK(count > 0); } WHEN("modifying the content of a file") { const auto p = create_file(root / PS_TEXT("1")); REQUIRE(exists(p)); unique_change_registration reg{recursive_monitor(root, cfg, [&lock, &notes](const change_notifications& n) { guard lg{lock}; notes.insert(notes.end(), n.begin(), n.end()); })}; CHECK(reg); { std::ofstream stream(p.c_str()); CHECK(stream); stream << "hello world" << std::flush; } std::this_thread::sleep_for(sleep_duration); stop(reg); CHECK(remove(p)); CHECK_FALSE(notes.empty()); const auto count = std::count_if(notes.begin(), notes.end(), [](const change_notification& n) { return modified(n); }); CHECK(count > 0); } WHEN("modifying the metadata of a file") { const auto p = create_file(root / PS_TEXT("1")); REQUIRE(exists(p)); unique_change_registration reg{recursive_monitor(root, cfg, [&lock, &notes](const change_notifications& n) { guard lg{lock}; notes.insert(notes.end(), n.begin(), n.end()); })}; CHECK(reg); using namespace std::chrono; const auto t = std::chrono::system_clock::now() - duration_cast<file_time_type::duration>(seconds(3600)); CHECK_NOTHROW(last_write_time(p, t)); std::this_thread::sleep_for(sleep_duration); stop(reg); CHECK(remove(p)); CHECK_FALSE(notes.empty()); const auto count = std::count_if(notes.begin(), notes.end(), [](const change_notification& n) { return modified(n); }); CHECK(count > 0); } WHEN("removing a file") { const auto p = create_file(root / PS_TEXT("1")); REQUIRE(exists(p)); unique_change_registration reg{recursive_monitor(root, cfg, [&lock, &notes](const change_notifications& n) { guard lg{lock}; notes.insert(notes.end(), n.begin(), n.end()); })}; CHECK(reg); CHECK(remove(p)); std::this_thread::sleep_for(sleep_duration); stop(reg); CHECK_FALSE(notes.empty()); const auto count = std::count_if(notes.begin(), notes.end(), [](const change_notification& n) { return removed(n); }); CHECK(count > 0); } WHEN("renaming a file") { const auto p = create_file(root / PS_TEXT("1")); REQUIRE(exists(p)); unique_change_registration reg{recursive_monitor(root, cfg, [&lock, &notes](const change_notifications& n) { guard lg{lock}; notes.insert(notes.end(), n.begin(), n.end()); })}; CHECK(reg); const auto np = root / PS_TEXT("2"); rename(p, np); std::this_thread::sleep_for(sleep_duration); stop(reg); error_code ec; CHECK_FALSE(exists(p, ec)); CHECK(exists(np)); CHECK(remove(np)); CHECK_FALSE(notes.empty()); const auto count = std::count_if(notes.begin(), notes.end(), [](const change_notification& n) { return renamed(n); }); CHECK(count > 0); } WHEN("the monitor root is renamed") { unique_change_registration reg{recursive_monitor(root, cfg, [&lock, &notes](const change_notifications& n) { guard lg{lock}; notes.insert(notes.end(), n.begin(), n.end()); })}; CHECK(reg); const auto np = root.parent_path() / PS_TEXT("fs17test2"); rename(root, np); std::this_thread::sleep_for(sleep_duration); stop(reg); rename(np, root); // rename back so cleanup succeeds CHECK_FALSE(notes.empty()); const auto i = std::find_if(notes.begin(), notes.end(), [](const change_notification& n) { return is_set(n.event() & (change_event::rescan_required|change_event::renamed)); }); REQUIRE(i != notes.end()); CHECK(i->renamed_to_path() == np); } WHEN("the monitor root is removed") { unique_change_registration reg{recursive_monitor(root, cfg, [&lock, &notes](const change_notifications& n) { guard lg{lock}; notes.insert(notes.end(), n.begin(), n.end()); })}; CHECK(reg); CHECK(remove(root)); std::this_thread::sleep_for(sleep_duration); stop(reg); create_directory(root); // recreate so cleanup succeeds CHECK_FALSE(notes.empty()); const auto count = std::count_if(notes.begin(), notes.end(), [](const change_notification& n) { return is_set(n.event() & (change_event::rescan_required|change_event::removed)); }); CHECK(count > 0); } REQUIRE(remove(root)); } } #endif // PS_HAVE_FILESYSTEM_CHANGE_MONITOR <commit_msg>Fix test failure due to potential race condition<commit_after>// Copyright © 2016-2017, Prosoft Engineering, Inc. (A.K.A "Prosoft") // 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 Prosoft 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 PROSOFT ENGINEERING, INC. 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 <prosoft/core/config/config_platform.h> #include <thread> #include "filesystem.hpp" #include "filesystem_change_monitor.hpp" #if PS_HAVE_FILESYSTEM_CHANGE_MONITOR #include "catch.hpp" #include "fstestutils.hpp" using namespace prosoft; using namespace prosoft::filesystem; TEST_CASE("filesystem_monitor") { SECTION("default values") { CHECK(is_set(change_event::all & change_event::created)); CHECK(is_set(change_event::all & change_event::removed)); CHECK(is_set(change_event::all & change_event::renamed)); CHECK(is_set(change_event::all & change_event::content_modified)); CHECK(is_set(change_event::all & change_event::metadata_modified)); change_registration reg; CHECK_FALSE(reg); CHECK_FALSE(reg == change_registration()); change_config cfg; CHECK(cfg.state == nullptr); CHECK(cfg.notification_latency > change_config::latency_type()); CHECK(cfg.events == change_event::all); } WHEN("registration is invalid") { change_registration reg; REQUIRE_FALSE(reg); CHECK_THROWS(stop(reg)); } WHEN("args are invalid") { auto nopcb = [](const change_notifications&){}; CHECK_THROWS(monitor(PS_TEXT(""), change_event::none, change_callback{})); CHECK_THROWS(monitor(PS_TEXT("test"), change_event::none, change_callback{})); CHECK_THROWS(monitor(PS_TEXT("test"), change_event::created, change_callback{})); CHECK_THROWS(recursive_monitor(PS_TEXT(""), change_event::none, change_callback{})); CHECK_THROWS(recursive_monitor(PS_TEXT("test"), change_event::none, change_callback{})); CHECK_THROWS(recursive_monitor(PS_TEXT("test"), change_event::created, change_callback{})); } WHEN("unique change registration goes out of scope") { change_registration reg; { unique_change_registration ureg{recursive_monitor(temp_directory_path(), [](const change_notifications&) { })}; reg = ureg; CHECK(reg); } // The reg may still be valid (if internal state is still alive) but it should no longer be registered as a monitor. CHECK_THROWS(stop(reg)); } SECTION("recursive monitor") { const auto root = canonical(temp_directory_path()) / PS_TEXT("fs17test"); create_directory(root); REQUIRE(exists(root)); std::mutex lock; using guard = std::lock_guard<std::mutex>; change_notifications notes; change_config cfg; cfg.notification_latency = change_config::latency_type{0}; // keep coalescing to a minimum constexpr auto sleep_duration = change_config::latency_type{300}; WHEN("creating a file") { const auto p = root / PS_TEXT("1"); error_code ec; REQUIRE_FALSE(exists(p, ec)); unique_change_registration reg{recursive_monitor(root, cfg, [&lock, &notes](const change_notifications& n) { guard lg{lock}; notes.insert(notes.end(), n.begin(), n.end()); })}; CHECK(reg); create_file(p); std::this_thread::sleep_for(sleep_duration); stop(reg); CHECK(remove(p)); CHECK_FALSE(notes.empty()); const auto count = std::count_if(notes.begin(), notes.end(), [](const change_notification& n) { return created(n); }); CHECK(count > 0); } WHEN("modifying the content of a file") { const auto p = create_file(root / PS_TEXT("1")); REQUIRE(exists(p)); unique_change_registration reg{recursive_monitor(root, cfg, [&lock, &notes](const change_notifications& n) { guard lg{lock}; notes.insert(notes.end(), n.begin(), n.end()); })}; CHECK(reg); { std::ofstream stream(p.c_str()); CHECK(stream); stream << "hello world" << std::flush; } std::this_thread::sleep_for(sleep_duration); stop(reg); CHECK(remove(p)); CHECK_FALSE(notes.empty()); const auto count = std::count_if(notes.begin(), notes.end(), [](const change_notification& n) { return modified(n); }); CHECK(count > 0); } WHEN("modifying the metadata of a file") { const auto p = create_file(root / PS_TEXT("1")); REQUIRE(exists(p)); unique_change_registration reg{recursive_monitor(root, cfg, [&lock, &notes](const change_notifications& n) { guard lg{lock}; notes.insert(notes.end(), n.begin(), n.end()); })}; CHECK(reg); using namespace std::chrono; const auto t = std::chrono::system_clock::now() - duration_cast<file_time_type::duration>(seconds(3600)); CHECK_NOTHROW(last_write_time(p, t)); std::this_thread::sleep_for(sleep_duration); stop(reg); CHECK(remove(p)); CHECK_FALSE(notes.empty()); const auto count = std::count_if(notes.begin(), notes.end(), [](const change_notification& n) { return modified(n); }); CHECK(count > 0); } WHEN("removing a file") { const auto p = create_file(root / PS_TEXT("1")); REQUIRE(exists(p)); unique_change_registration reg{recursive_monitor(root, cfg, [&lock, &notes](const change_notifications& n) { guard lg{lock}; notes.insert(notes.end(), n.begin(), n.end()); })}; CHECK(reg); CHECK(remove(p)); std::this_thread::sleep_for(sleep_duration); stop(reg); CHECK_FALSE(notes.empty()); const auto count = std::count_if(notes.begin(), notes.end(), [](const change_notification& n) { return removed(n); }); CHECK(count > 0); } WHEN("renaming a file") { const auto p = create_file(root / PS_TEXT("1")); REQUIRE(exists(p)); unique_change_registration reg{recursive_monitor(root, cfg, [&lock, &notes](const change_notifications& n) { guard lg{lock}; notes.insert(notes.end(), n.begin(), n.end()); })}; CHECK(reg); const auto np = root / PS_TEXT("2"); rename(p, np); std::this_thread::sleep_for(sleep_duration); stop(reg); error_code ec; CHECK_FALSE(exists(p, ec)); CHECK(exists(np)); CHECK(remove(np)); CHECK_FALSE(notes.empty()); const auto count = std::count_if(notes.begin(), notes.end(), [](const change_notification& n) { return renamed(n); }); CHECK(count > 0); } WHEN("the monitor root is renamed") { unique_change_registration reg{recursive_monitor(root, cfg, [&lock, &notes](const change_notifications& n) { guard lg{lock}; notes.insert(notes.end(), n.begin(), n.end()); })}; CHECK(reg); const auto np = root.parent_path() / PS_TEXT("fs17test2"); rename(root, np); std::this_thread::sleep_for(sleep_duration); stop(reg); rename(np, root); // rename back so cleanup succeeds CHECK_FALSE(notes.empty()); const auto i = std::find_if(notes.begin(), notes.end(), [](const change_notification& n) { return is_set(n.event() & (change_event::rescan_required|change_event::renamed)); }); REQUIRE(i != notes.end()); if (!i->renamed_to_path().empty()) { // race conditions in event delivery vs. filesystem state can result in an empty path CHECK(i->renamed_to_path() == np); } } WHEN("the monitor root is removed") { unique_change_registration reg{recursive_monitor(root, cfg, [&lock, &notes](const change_notifications& n) { guard lg{lock}; notes.insert(notes.end(), n.begin(), n.end()); })}; CHECK(reg); CHECK(remove(root)); std::this_thread::sleep_for(sleep_duration); stop(reg); create_directory(root); // recreate so cleanup succeeds CHECK_FALSE(notes.empty()); const auto count = std::count_if(notes.begin(), notes.end(), [](const change_notification& n) { return is_set(n.event() & (change_event::rescan_required|change_event::removed)); }); CHECK(count > 0); } REQUIRE(remove(root)); } } #endif // PS_HAVE_FILESYSTEM_CHANGE_MONITOR <|endoftext|>
<commit_before>#include "dynet/io.h" #include "dynet/tensor.h" #include "dynet/except.h" #include "dynet/str-util.h" using namespace std; using namespace dynet; // Precision required not to lose accuracy when serializing float32 to text. // We should probably use std::hexfloat, but it's not supported by some // older incomplete implementations of C++11. static const int FLOAT32_PRECISION = 8; bool valid_key(const std::string & s) { if (s.size() == 0) return true; if (s == "/") return false; auto it = std::find_if(s.begin(), s.end(), [] (char ch) { return ch == ' ' || ch == '#';}); return it == s.end(); } bool valid_pc_key(const std::string & s) { if (s.size() == 0) return true; if (!(startswith(s, "/"))) return false; return valid_key(s); } bool grad_is_zero(const ParameterStorageBase & p){ return !p.has_grad(); } void read_param_header(string line, string &type, string &name, Dim& dim,size_t& byte_count, bool& zero_grad){ // Read header istringstream iss(line); iss >> type >> name >> dim >> byte_count; // Check whether gradient is 0 // Check for EOF (for backward compatibility) string grad; if (!iss.eof()){ iss >> grad; if (grad == "ZERO_GRAD") zero_grad = true; } } TextFileSaver::TextFileSaver(const string & filename, bool append) : datastream(filename, append ? ofstream::app : ofstream::out) { if(!datastream) DYNET_RUNTIME_ERR("Could not write model to " << filename); } void TextFileSaver::save(const ParameterCollection & model, const string & key) { if (!valid_pc_key(key)) DYNET_INVALID_ARG("Key should start with '/' and could not include ' ' or '#': " << key); string key_ = key; if (key_.back() != '/') key_ += "/"; const ParameterCollectionStorage & storage = model.get_storage(); if(key.size() == 0) { for (auto & p : storage.params) save(*p, key); for (auto & p : storage.lookup_params) save(*p, key); } else { size_t strip_size = model.get_fullname().size(); for (auto & p : storage.params) save(*p, key_ + p->name.substr(strip_size)); for (auto & p : storage.lookup_params) save(*p, key_ + p->name.substr(strip_size)); } } void TextFileSaver::save(const Parameter & param, const string & key) { if (!valid_key(key)) DYNET_INVALID_ARG("Key could not include ' ' or '#': " << key); save(*param.p, key); } void TextFileSaver::save(const LookupParameter & param, const string & key) { if (!valid_key(key)) DYNET_INVALID_ARG("Key could not include ' ' or '#': " << key); save(*param.p, key); } void TextFileSaver::save(const ParameterStorage & p, const string & key) { std::ostringstream buffer; buffer.precision(FLOAT32_PRECISION); buffer << dynet::as_vector(p.values) << endl; bool zero_grad = grad_is_zero(p); if(!zero_grad) buffer << dynet::as_vector(p.g) << endl; datastream << "#Parameter# " << (key.size() > 0 ? key : p.name) << ' ' << p.dim << ' ' << buffer.str().size(); if(zero_grad) datastream << " ZERO_GRAD"; else datastream << " FULL_GRAD"; datastream << endl; datastream.write(buffer.str().c_str(), buffer.str().size()); } void TextFileSaver::save(const LookupParameterStorage & p, const string & key) { std::ostringstream buffer; buffer.precision(FLOAT32_PRECISION); buffer << dynet::as_vector(p.all_values) << endl; bool zero_grad = grad_is_zero(p); if(!zero_grad) buffer << dynet::as_vector(p.all_grads) << endl; datastream << "#LookupParameter# " << (key.size() > 0 ? key : p.name) << ' ' << p.all_dim << ' ' << buffer.str().size(); if(zero_grad) datastream << " ZERO_GRAD"; else datastream << " FULL_GRAD"; datastream << endl; datastream.write(buffer.str().c_str(), buffer.str().size()); } TextFileLoader::TextFileLoader(const string & filename) : dataname(filename) { } void TextFileLoader::populate(ParameterCollection & model, const string & key) { ifstream datastream(dataname); if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname); string line, type, name; bool zero_grad = false; Dim dim; size_t byte_count = 0; vector<float> values; Tensor *value_t, *grad_t; size_t param_id = 0, lookup_id = 0; ParameterCollectionStorage & storage = model.get_storage(); string key_ = key; if (key_.back() != '/') key_ += "/"; while(getline(datastream, line)) { read_param_header(line, type, name, dim, byte_count, zero_grad); // Skip ones that don't match if(key.size() != 0 && name.substr(0, key_.size()) != key_) { size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count; datastream.seekg(offset); continue; // Load a parameter } else if(type == "#Parameter#") { values.resize(dim.size()); if(param_id >= storage.params.size()) DYNET_RUNTIME_ERR("Too many parameters to load in populated model at " << name); ParameterStorage & param = *storage.params[param_id++]; if(param.dim != dim) DYNET_RUNTIME_ERR("Dimensions of parameter " << name << " looked up from file (" << dim << ") do not match parameters to be populated (" << param.dim << ")"); value_t = &param.values; grad_t = &param.g; // Load a lookup parameter } else if(type == "#LookupParameter#") { values.resize(dim.size()); if(lookup_id >= storage.lookup_params.size()) DYNET_RUNTIME_ERR("Too many lookup parameters in populated model at " << name); LookupParameterStorage & param = *storage.lookup_params[lookup_id++]; if(param.all_dim != dim) DYNET_RUNTIME_ERR("Dimensions of lookup parameter " << name << " lookup up from file (" << dim << ") do not match parameters to be populated (" << param.all_dim << ")"); value_t = &param.all_values; grad_t = &param.all_grads; } else { DYNET_RUNTIME_ERR("Bad parameter specification in model: " << line); } { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(*value_t, values); if(!zero_grad){ { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(*grad_t, values); } else { TensorTools::zero(*grad_t); } } if(param_id != storage.params.size() || lookup_id != storage.lookup_params.size()) DYNET_RUNTIME_ERR("Number of parameter/lookup parameter objects loaded from file (" << param_id << '/' << lookup_id << ") did not match number to be populated (" << storage.params.size() << '/' << storage.lookup_params.size() << ')'); } void TextFileLoader::populate(Parameter & param, const string & key) { if(key == "") DYNET_INVALID_ARG("TextFileLoader.populate() requires non-empty key"); ifstream datastream(dataname); if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname); string line, type, name; bool zero_grad=false; Dim dim; size_t byte_count = 0; while(getline(datastream, line)) { read_param_header(line, type, name, dim, byte_count, zero_grad); if(type == "#Parameter#" && name == key) { if(param.p->dim != dim) DYNET_RUNTIME_ERR("Attempted to populate parameter where arguments don't match (" << param.p->dim << " != " << dim << ")"); vector<float> values(dim.size()); { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(param.get_storage().values, values); if(!zero_grad){ { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(param.get_storage().g, values); } else { TensorTools::zero(param.get_storage().g); } return; } else { size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count; datastream.seekg(offset); } } DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file"); } void TextFileLoader::populate(LookupParameter & lookup_param, const string & key) { if(key == "") DYNET_INVALID_ARG("TextFileLoader.populate() requires non-empty key"); ifstream datastream(dataname); if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname); string line, type, name; bool zero_grad=false; Dim dim; size_t byte_count = 0; while(getline(datastream, line)) { read_param_header(line, type, name, dim, byte_count, zero_grad); if(type == "#LookupParameter#" && name == key) { if(lookup_param.p->all_dim != dim) DYNET_RUNTIME_ERR("Attempted to populate lookup parameter where arguments don't match (" << lookup_param.p->all_dim << " != " << dim << ")"); vector<float> values(dim.size()); { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(lookup_param.get_storage().all_values, values); if(!zero_grad){ { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(lookup_param.get_storage().all_grads, values); } else { TensorTools::zero(lookup_param.get_storage().all_grads); } return; } else { size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count; datastream.seekg(offset); } } DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file"); } Parameter TextFileLoader::load_param(ParameterCollection & model, const string & key) { if(key == "") DYNET_INVALID_ARG("TextFileLoader.load_param() requires non-empty key"); ifstream datastream(dataname); if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname); string line, type, name; bool zero_grad=false; Dim dim; size_t byte_count = 0; while(getline(datastream, line)) { read_param_header(line, type, name, dim, byte_count, zero_grad); if(type == "#Parameter#" && name == key) { Parameter param = model.add_parameters(dim); param.get_storage().name = name; vector<float> values(dim.size()); { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(param.get_storage().values, values); if(!zero_grad){ { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(param.get_storage().g, values); } else { TensorTools::zero(param.get_storage().g); } return param; } else { size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count; datastream.seekg(offset); } } DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file"); } LookupParameter TextFileLoader::load_lookup_param(ParameterCollection & model, const string & key) { if(key == "") DYNET_INVALID_ARG("TextFileLoader.load_lookup_param() requires non-empty key"); ifstream datastream(dataname); if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname); string line, type, name; bool zero_grad=false; Dim dim; size_t byte_count = 0; while(getline(datastream, line)) { read_param_header(line, type, name, dim, byte_count, zero_grad); if(type == "#LookupParameter#" && name == key) { vector<float> values(dim.size()); size_t size = dim[dim.nd-1]; dim.nd--; LookupParameter lookup_param = model.add_lookup_parameters(size, dim); lookup_param.get_storage().name = name; { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(lookup_param.get_storage().all_values, values); if(!zero_grad){ { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(lookup_param.get_storage().all_grads, values); } else { TensorTools::zero(lookup_param.get_storage().all_grads); } return lookup_param; } else { size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count; datastream.seekg(offset); } } DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file"); } <commit_msg>Made text saving be fixed-width for efficiency<commit_after>#include "dynet/io.h" #include "dynet/tensor.h" #include "dynet/except.h" #include "dynet/str-util.h" using namespace std; using namespace dynet; // Precision required not to lose accuracy when serializing float32 to text. // We should probably use std::hexfloat, but it's not supported by some // older incomplete implementations of C++11. static const int FLOAT32_PRECISION = 8; bool valid_key(const std::string & s) { if (s.size() == 0) return true; if (s == "/") return false; auto it = std::find_if(s.begin(), s.end(), [] (char ch) { return ch == ' ' || ch == '#';}); return it == s.end(); } bool valid_pc_key(const std::string & s) { if (s.size() == 0) return true; if (!(startswith(s, "/"))) return false; return valid_key(s); } bool grad_is_zero(const ParameterStorageBase & p){ return !p.has_grad(); } void read_param_header(string line, string &type, string &name, Dim& dim,size_t& byte_count, bool& zero_grad){ // Read header istringstream iss(line); iss >> type >> name >> dim >> byte_count; // Check whether gradient is 0 // Check for EOF (for backward compatibility) string grad; if (!iss.eof()){ iss >> grad; if (grad == "ZERO_GRAD") zero_grad = true; } } TextFileSaver::TextFileSaver(const string & filename, bool append) : datastream(filename, append ? ofstream::app : ofstream::out) { if(!datastream) DYNET_RUNTIME_ERR("Could not write model to " << filename); datastream.precision(FLOAT32_PRECISION); datastream << std::scientific << std::showpos; } void TextFileSaver::save(const ParameterCollection & model, const string & key) { if (!valid_pc_key(key)) DYNET_INVALID_ARG("Key should start with '/' and could not include ' ' or '#': " << key); string key_ = key; if (key_.back() != '/') key_ += "/"; const ParameterCollectionStorage & storage = model.get_storage(); if(key.size() == 0) { for (auto & p : storage.params) save(*p, key); for (auto & p : storage.lookup_params) save(*p, key); } else { size_t strip_size = model.get_fullname().size(); for (auto & p : storage.params) save(*p, key_ + p->name.substr(strip_size)); for (auto & p : storage.lookup_params) save(*p, key_ + p->name.substr(strip_size)); } } void TextFileSaver::save(const Parameter & param, const string & key) { if (!valid_key(key)) DYNET_INVALID_ARG("Key could not include ' ' or '#': " << key); save(*param.p, key); } void TextFileSaver::save(const LookupParameter & param, const string & key) { if (!valid_key(key)) DYNET_INVALID_ARG("Key could not include ' ' or '#': " << key); save(*param.p, key); } void TextFileSaver::save(const ParameterStorage & p, const string & key) { datastream << "#Parameter# " << (key.size() > 0 ? key : p.name) << ' ' << p.dim << ' '; size_t strsize = p.dim.size() * (FLOAT32_PRECISION + 8) + 1; bool zero_grad = grad_is_zero(p); if(zero_grad) datastream << strsize << " ZERO_GRAD"; else datastream << strsize*2 << " FULL_GRAD"; datastream << endl << dynet::as_vector(p.values) << endl; if(!zero_grad) datastream << dynet::as_vector(p.g) << endl; } void TextFileSaver::save(const LookupParameterStorage & p, const string & key) { datastream << "#LookupParameter# " << (key.size() > 0 ? key : p.name) << ' ' << p.all_dim << ' '; size_t strsize = p.all_dim.size() * (FLOAT32_PRECISION + 8) + 1; bool zero_grad = grad_is_zero(p); if(zero_grad) datastream << strsize << " ZERO_GRAD"; else datastream << strsize*2 << " FULL_GRAD"; datastream << endl << dynet::as_vector(p.all_values) << endl; if(!zero_grad) datastream << dynet::as_vector(p.all_grads) << endl; } TextFileLoader::TextFileLoader(const string & filename) : dataname(filename) { } void TextFileLoader::populate(ParameterCollection & model, const string & key) { ifstream datastream(dataname); if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname); string line, type, name; bool zero_grad = false; Dim dim; size_t byte_count = 0; vector<float> values; Tensor *value_t, *grad_t; size_t param_id = 0, lookup_id = 0; ParameterCollectionStorage & storage = model.get_storage(); string key_ = key; if (key_.back() != '/') key_ += "/"; while(getline(datastream, line)) { read_param_header(line, type, name, dim, byte_count, zero_grad); // Skip ones that don't match if(key.size() != 0 && name.substr(0, key_.size()) != key_) { size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count; datastream.seekg(offset); continue; // Load a parameter } else if(type == "#Parameter#") { values.resize(dim.size()); if(param_id >= storage.params.size()) DYNET_RUNTIME_ERR("Too many parameters to load in populated model at " << name); ParameterStorage & param = *storage.params[param_id++]; if(param.dim != dim) DYNET_RUNTIME_ERR("Dimensions of parameter " << name << " looked up from file (" << dim << ") do not match parameters to be populated (" << param.dim << ")"); value_t = &param.values; grad_t = &param.g; // Load a lookup parameter } else if(type == "#LookupParameter#") { values.resize(dim.size()); if(lookup_id >= storage.lookup_params.size()) DYNET_RUNTIME_ERR("Too many lookup parameters in populated model at " << name); LookupParameterStorage & param = *storage.lookup_params[lookup_id++]; if(param.all_dim != dim) DYNET_RUNTIME_ERR("Dimensions of lookup parameter " << name << " lookup up from file (" << dim << ") do not match parameters to be populated (" << param.all_dim << ")"); value_t = &param.all_values; grad_t = &param.all_grads; } else { DYNET_RUNTIME_ERR("Bad parameter specification in model: " << line); } { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(*value_t, values); if(!zero_grad){ { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(*grad_t, values); } else { TensorTools::zero(*grad_t); } } if(param_id != storage.params.size() || lookup_id != storage.lookup_params.size()) DYNET_RUNTIME_ERR("Number of parameter/lookup parameter objects loaded from file (" << param_id << '/' << lookup_id << ") did not match number to be populated (" << storage.params.size() << '/' << storage.lookup_params.size() << ')'); } void TextFileLoader::populate(Parameter & param, const string & key) { if(key == "") DYNET_INVALID_ARG("TextFileLoader.populate() requires non-empty key"); ifstream datastream(dataname); if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname); string line, type, name; bool zero_grad=false; Dim dim; size_t byte_count = 0; while(getline(datastream, line)) { read_param_header(line, type, name, dim, byte_count, zero_grad); if(type == "#Parameter#" && name == key) { if(param.p->dim != dim) DYNET_RUNTIME_ERR("Attempted to populate parameter where arguments don't match (" << param.p->dim << " != " << dim << ")"); vector<float> values(dim.size()); { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(param.get_storage().values, values); if(!zero_grad){ { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(param.get_storage().g, values); } else { TensorTools::zero(param.get_storage().g); } return; } else { size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count; datastream.seekg(offset); } } DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file"); } void TextFileLoader::populate(LookupParameter & lookup_param, const string & key) { if(key == "") DYNET_INVALID_ARG("TextFileLoader.populate() requires non-empty key"); ifstream datastream(dataname); if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname); string line, type, name; bool zero_grad=false; Dim dim; size_t byte_count = 0; while(getline(datastream, line)) { read_param_header(line, type, name, dim, byte_count, zero_grad); if(type == "#LookupParameter#" && name == key) { if(lookup_param.p->all_dim != dim) DYNET_RUNTIME_ERR("Attempted to populate lookup parameter where arguments don't match (" << lookup_param.p->all_dim << " != " << dim << ")"); vector<float> values(dim.size()); { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(lookup_param.get_storage().all_values, values); if(!zero_grad){ { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(lookup_param.get_storage().all_grads, values); } else { TensorTools::zero(lookup_param.get_storage().all_grads); } return; } else { size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count; datastream.seekg(offset); } } DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file"); } Parameter TextFileLoader::load_param(ParameterCollection & model, const string & key) { if(key == "") DYNET_INVALID_ARG("TextFileLoader.load_param() requires non-empty key"); ifstream datastream(dataname); if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname); string line, type, name; bool zero_grad=false; Dim dim; size_t byte_count = 0; while(getline(datastream, line)) { read_param_header(line, type, name, dim, byte_count, zero_grad); if(type == "#Parameter#" && name == key) { Parameter param = model.add_parameters(dim); param.get_storage().name = name; vector<float> values(dim.size()); { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(param.get_storage().values, values); if(!zero_grad){ { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(param.get_storage().g, values); } else { TensorTools::zero(param.get_storage().g); } return param; } else { size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count; datastream.seekg(offset); } } DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file"); } LookupParameter TextFileLoader::load_lookup_param(ParameterCollection & model, const string & key) { if(key == "") DYNET_INVALID_ARG("TextFileLoader.load_lookup_param() requires non-empty key"); ifstream datastream(dataname); if(!datastream) DYNET_RUNTIME_ERR("Could not read model from " << dataname); string line, type, name; bool zero_grad=false; Dim dim; size_t byte_count = 0; while(getline(datastream, line)) { read_param_header(line, type, name, dim, byte_count, zero_grad); if(type == "#LookupParameter#" && name == key) { vector<float> values(dim.size()); size_t size = dim[dim.nd-1]; dim.nd--; LookupParameter lookup_param = model.add_lookup_parameters(size, dim); lookup_param.get_storage().name = name; { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(lookup_param.get_storage().all_values, values); if(!zero_grad){ { getline(datastream, line); istringstream iss(line); iss >> values; } TensorTools::set_elements(lookup_param.get_storage().all_grads, values); } else { TensorTools::zero(lookup_param.get_storage().all_grads); } return lookup_param; } else { size_t offset = static_cast<size_t>(datastream.tellg()) + byte_count; datastream.seekg(offset); } } DYNET_RUNTIME_ERR("Could not find key " << key << " in the model file"); } <|endoftext|>
<commit_before>#include <Python.h> #include <vector> #include <iostream> #include <cmath> #define file_num 2 #define threshhold 0.6 #define allowable_difference 100 using namespace std; struct peak{ char* chr; int chr_start; int chr_end; float score; float signal; float q_value; float error_rate; }; static PyObject * ens_main(PyObject *self, PyObject *args){ PyObject *peaks_data = (PyObject*)PyList_New(0); PyObject *error_data = (PyObject*)PyList_New(0); PyObject *peak_containor[2]; PyObject *dict_containor = (PyObject*)PyDict_New(); double error_containor[file_num]; std::vector<peak> peak_vec[file_num]; peak* peak_element; char* chr; char* chr_start; char* chr_end; char* signal; char* q_value; char* score; char* error_rate; //////// Python Object to C++ Local variable ///////// if(!PyArg_ParseTuple(args, "O!O!",&PyList_Type,&peaks_data, &PyList_Type, &error_data)) return NULL; for ( int i = 0; i < file_num; i++){ peak_containor[i] = (PyObject*)PyList_New(0); peak_containor[i] = PyList_GetItem(peaks_data,i); error_containor[i] = PyFloat_AsDouble(PyList_GetItem(error_data,i)); } for ( int i = 0; i < file_num; i++){ for ( int j = 0 ; j < PyList_Size(peak_containor[i]) ; j++){ dict_containor = PyList_GetItem(peak_containor[i], j); PyArg_Parse(PyDict_GetItemString(dict_containor,"region_s"), "s", &chr_start); PyArg_Parse(PyDict_GetItemString(dict_containor,"region_e"), "s", &chr_end); PyArg_Parse(PyDict_GetItemString(dict_containor,"chr"), "s", &chr); PyArg_Parse(PyDict_GetItemString(dict_containor,"score"), "s", &score); PyArg_Parse(PyDict_GetItemString(dict_containor,"signalValue"), "s", &signal); PyArg_Parse(PyDict_GetItemString(dict_containor,"qValue"),"s",&q_value); peak_element = new peak; peak_element->chr = chr; peak_element->chr_start = atoi(chr_start); peak_element->chr_end = atoi(chr_end); peak_element->score = atof(score); peak_element->signal = atof(signal); peak_element->q_value = atof(q_value); peak_element->error_rate = error_containor[i]; peak_vec[i].push_back(*peak_element); // printf("now parse %d`s of peak , signal = %f\n", peak_vec[i].size(), peak_element->signal); } } cout <<"==============================================="<<endl; vector<peak>::iterator it[file_num]; for(int i=0; i <file_num; i++) it[i] = peak_vec[i].begin(); double smallest_value, pct; int cnt=0; int chr_check = 0; char current_chr = it[0]->chr[3]; cout <<it[0]->chr<< " " <<it[1]->chr<<endl; smallest_value = it[0]->chr_start; while(1){ for(int i=0; i <file_num; i++){ if(abs(smallest_value - it[i]->chr_start) <allowable_difference){ cnt++; } } pct = cnt / file_num; if(pct > threshhold){ cout <<"=========="<<file_num << " of " <<cnt<<" files are match"<<"=========="<<endl; cout<< it[0]->chr <<endl; cout << it[0]->chr_start<<endl; cout << it[1]->chr_start<<endl; cout <<"===================="<<endl; } cnt = 0; for(int i=0; i <file_num; i++){ if(abs(smallest_value - it[i]->chr_start) <allowable_difference && current_chr == it[i]->chr[3] ){ it[i]++; if(it[i]==peak_vec[i].end()){ it[i]--; it[i]->chr[3] = 'D'; } } } chr_check=0; for(int i=0; i <file_num; i++){ if(it[i]!= peak_vec[i].end() && current_chr == it[i]->chr[3]) chr_check++; } if(double(chr_check) / double(file_num) < threshhold){ cout <<" -----------------======================================="; for(int i=0; i< file_num; i++){ if(it[i]->chr[3]=='D') return Py_BuildValue("i",1); while(it[i]->chr[3] == current_chr){ it[i]++; } } current_chr = it[0]->chr[3]; } smallest_value = it[0]->chr_start < it[1]->chr_start? it[0]->chr_start : it[1]->chr_start; } //////// C++ value to Python Object ///////////////// return Py_BuildValue("i",1); } static PyMethodDef ensembleMethods[] = { {"ensembler", ens_main, METH_VARARGS, "main flow of ensembler."}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initensemble(void){ (void) Py_InitModule("ensemble",ensembleMethods); } int main(int argc, char *argv[]){ Py_SetProgramName(argv[0]); Py_Initialize(); initensemble(); return 0; } <commit_msg>All chromosome + comment<commit_after>#include <Python.h> #include <vector> #include <iostream> #include <cmath> #define file_num 2 #define threshhold 0.6 #define allowable_difference 100 using namespace std; struct peak{ char* chr; int chr_start; int chr_end; float score; float signal; float q_value; float error_rate; }; static PyObject * ens_main(PyObject *self, PyObject *args){ PyObject *peaks_data = (PyObject*)PyList_New(0); PyObject *error_data = (PyObject*)PyList_New(0); PyObject *peak_containor[2]; PyObject *dict_containor = (PyObject*)PyDict_New(); double error_containor[file_num]; std::vector<peak> peak_vec[file_num]; peak* peak_element; char* chr; char* chr_start; char* chr_end; char* signal; char* q_value; char* score; char* error_rate; //////// Python Object to C++ Local variable ///////// if(!PyArg_ParseTuple(args, "O!O!",&PyList_Type,&peaks_data, &PyList_Type, &error_data)) return NULL; for ( int i = 0; i < file_num; i++){ peak_containor[i] = (PyObject*)PyList_New(0); peak_containor[i] = PyList_GetItem(peaks_data,i); error_containor[i] = PyFloat_AsDouble(PyList_GetItem(error_data,i)); } for ( int i = 0; i < file_num; i++){ for ( int j = 0 ; j < PyList_Size(peak_containor[i]) ; j++){ dict_containor = PyList_GetItem(peak_containor[i], j); PyArg_Parse(PyDict_GetItemString(dict_containor,"region_s"), "s", &chr_start); PyArg_Parse(PyDict_GetItemString(dict_containor,"region_e"), "s", &chr_end); PyArg_Parse(PyDict_GetItemString(dict_containor,"chr"), "s", &chr); PyArg_Parse(PyDict_GetItemString(dict_containor,"score"), "s", &score); PyArg_Parse(PyDict_GetItemString(dict_containor,"signalValue"), "s", &signal); PyArg_Parse(PyDict_GetItemString(dict_containor,"qValue"),"s",&q_value); peak_element = new peak; peak_element->chr = chr; peak_element->chr_start = atoi(chr_start); peak_element->chr_end = atoi(chr_end); peak_element->score = atof(score); peak_element->signal = atof(signal); peak_element->q_value = atof(q_value); peak_element->error_rate = error_containor[i]; peak_vec[i].push_back(*peak_element); // printf("now parse %d`s of peak , signal = %f\n", peak_vec[i].size(), peak_element->signal); } } cout <<"==============================================="<<endl; vector<peak>::iterator it[file_num]; for(int i=0; i <file_num; i++) it[i] = peak_vec[i].begin(); double smallest_value, pct; int cnt=0; int chr_check = 0; char current_chr = it[0]->chr[3]; cout <<it[0]->chr<< " " <<it[1]->chr<<endl; smallest_value = it[0]->chr_start < it[1]->chr_start? it[0]->chr_start : it[1]->chr_start; while(1){ for(int i=0; i <file_num; i++){ if(abs(smallest_value - it[i]->chr_start) <allowable_difference){ cnt++; } } pct = cnt / file_num; // how many files are matched if(pct > threshhold){ cout <<"=========="<<file_num << " of " <<cnt<<" files are match"<<"=========="<<endl; cout<< it[0]->chr <<endl; cout << it[0]->chr_start<<endl; cout << it[1]->chr_start<<endl; cout <<"===================="<<endl; } cnt = 0; for(int i=0; i <file_num; i++){ if(abs(smallest_value - it[i]->chr_start) <allowable_difference && current_chr == it[i]->chr[3] ){// move to next peak element it[i]++; if(it[i]==peak_vec[i].end()){ it[i]--; it[i]->chr[3] = 'D';// prevent vector out of idx } } } chr_check=0; for(int i=0; i <file_num; i++){ if(it[i]!= peak_vec[i].end() && current_chr == it[i]->chr[3]) chr_check++; //should i move to next chromosome? } if(double(chr_check) / double(file_num) < threshhold){ cout <<" -----------------======================================="; for(int i=0; i< file_num; i++){ if(it[i]->chr[3]=='D') return Py_BuildValue("i",1); while(it[i]->chr[3] == current_chr){ it[i]++; } } current_chr = it[0]->chr[3]; } smallest_value = it[0]->chr_start < it[1]->chr_start? it[0]->chr_start : it[1]->chr_start; } //////// C++ value to Python Object ///////////////// return Py_BuildValue("i",1); } static PyMethodDef ensembleMethods[] = { {"ensembler", ens_main, METH_VARARGS, "main flow of ensembler."}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initensemble(void){ (void) Py_InitModule("ensemble",ensembleMethods); } int main(int argc, char *argv[]){ Py_SetProgramName(argv[0]); Py_Initialize(); initensemble(); return 0; } <|endoftext|>
<commit_before>/** * Copyright (c) 2017 DeepCortex GmbH <legal@eventql.io> * Authors: * - Paul Asmuth <paul@eventql.io> * - Laura Schlimmer <laura@eventql.io> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * 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 license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include "eventql/util/stringutil.h" #include "test_runner.h" namespace eventql { namespace test { TestRunner::TestRunner(TestRepository* test_repo) : test_repo_(test_repo) {} bool TestRunner::runTest(const std::string& test_id, TestOutputFormat format) { return runTests(std::set<std::string>{test_id}, format); } static void expandTestList( TestRepository* test_repo, std::set<std::string>* test_ids) { } bool TestRunner::runTests( std::set<std::string> test_ids, TestOutputFormat format) { expandTestList(test_repo_, &test_ids); size_t tests_count = test_ids.size(); switch (format) { case TestOutputFormat::ASCII: fprintf( stderr, "\033[1;97mRunning %i/%i tests\e[0m\n\n", (int) tests_count, (int) test_repo_->getTestCount()); break; case TestOutputFormat::TAP: fprintf(stdout, "1..%i\n", (int) tests_count); break; } size_t tests_passed = 0; size_t test_num = 0; for (const auto& bundle : test_repo_->getTestBundles()) { for (const auto& test : bundle) { if (test_ids.count(test.test_id) == 0) { break; } ++test_num; bool test_result = false; std::string test_message; try { test_result = test.fun(); } catch (const std::exception& e) { test_message = e.what(); } StringUtil::replaceAll(&test_message, "\n", "\\n"); StringUtil::replaceAll(&test_message, "\r", ""); if (test_result) { ++tests_passed; switch (format) { case TestOutputFormat::ASCII: fprintf( stderr, " * %s \033[1;32m[PASS]\e[0m\n", test.test_id.c_str()); break; case TestOutputFormat::TAP: fprintf( stdout, "ok %i - %s\n", (int) test_num, test.test_id.c_str()); break; } } else { switch (format) { case TestOutputFormat::ASCII: fprintf( stderr, " * %s \033[1;31m[FAIL]\e[0m\n", test.test_id.c_str()); break; case TestOutputFormat::TAP: fprintf( stdout, "not ok %i - %s # %s\n", (int) test_num, test.test_id.c_str(), test_message.c_str()); break; } } } } if (tests_count == 0 || tests_passed < tests_count) { switch (format) { case TestOutputFormat::ASCII: fprintf( stderr, "\n\033[1;31m[FAIL] %i/%i tests failed :(\e[0m\n", (int) (tests_count - tests_passed), (int) tests_count); break; case TestOutputFormat::TAP: break; } return false; } else { switch (format) { case TestOutputFormat::ASCII: fprintf( stderr, "\n\033[1;32m[PASS] %i tests passed :)\e[0m\n", (int) tests_count); break; case TestOutputFormat::TAP: break; } return true; } } bool TestRunner::runTestSuite(const std::string& suite, TestOutputFormat format) { if (suite == "world") { return runTestSuite(TestSuite::WORLD, format); } if (suite == "smoke") { return runTestSuite(TestSuite::WORLD, format); } std::cerr << "ERROR: invalid test suite" << std::endl; return false; } bool TestRunner::runTestSuite(TestSuite suite, TestOutputFormat format) { std::set<std::string> test_ids; for (const auto& bundle : test_repo_->getTestBundles()) { for (const auto& test : bundle) { if (test.suites.count(suite) > 0) { test_ids.insert(test.test_id); } } } return runTests(test_ids, format); } void TestRunner::printTestList() { } } // namespace test } // namespace eventql <commit_msg>print failing test messages in ascii mode<commit_after>/** * Copyright (c) 2017 DeepCortex GmbH <legal@eventql.io> * Authors: * - Paul Asmuth <paul@eventql.io> * - Laura Schlimmer <laura@eventql.io> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * 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 license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include "eventql/util/stringutil.h" #include "test_runner.h" namespace eventql { namespace test { TestRunner::TestRunner(TestRepository* test_repo) : test_repo_(test_repo) {} bool TestRunner::runTest(const std::string& test_id, TestOutputFormat format) { return runTests(std::set<std::string>{test_id}, format); } static void expandTestList( TestRepository* test_repo, std::set<std::string>* test_ids) { } bool TestRunner::runTests( std::set<std::string> test_ids, TestOutputFormat format) { expandTestList(test_repo_, &test_ids); size_t tests_count = test_ids.size(); switch (format) { case TestOutputFormat::ASCII: fprintf( stderr, "\033[1;97mRunning %i/%i tests\e[0m\n\n", (int) tests_count, (int) test_repo_->getTestCount()); break; case TestOutputFormat::TAP: fprintf(stdout, "1..%i\n", (int) tests_count); break; } std::vector<std::pair<std::string, std::string>> test_failures; size_t tests_passed = 0; size_t test_num = 0; for (const auto& bundle : test_repo_->getTestBundles()) { for (const auto& test : bundle) { if (test_ids.count(test.test_id) == 0) { break; } ++test_num; bool test_result = false; std::string test_message; try { test_result = test.fun(); } catch (const std::exception& e) { test_message = e.what(); } StringUtil::replaceAll(&test_message, "\n", "\\n"); StringUtil::replaceAll(&test_message, "\r", ""); if (test_result) { ++tests_passed; switch (format) { case TestOutputFormat::ASCII: fprintf( stderr, " * %s \033[1;32m[PASS]\e[0m\n", test.test_id.c_str()); break; case TestOutputFormat::TAP: fprintf( stdout, "ok %i - %s\n", (int) test_num, test.test_id.c_str()); break; } } else { test_failures.emplace_back(test.test_id, test_message); switch (format) { case TestOutputFormat::ASCII: fprintf( stderr, " * %s \033[1;31m[FAIL]\e[0m\n", test.test_id.c_str()); break; case TestOutputFormat::TAP: fprintf( stdout, "not ok %i - %s # %s\n", (int) test_num, test.test_id.c_str(), test_message.c_str()); break; } } } } if (tests_count == 0 || tests_passed < tests_count) { switch (format) { case TestOutputFormat::ASCII: for (const auto& fail : test_failures) { fprintf( stderr, "\n\033[1;31m[FAIL] %s\e[0m\n %s\n", fail.first.c_str(), fail.second.c_str()); } fprintf( stderr, "\n\033[1;31m[FAIL] %i/%i tests failed :(\e[0m\n", (int) (tests_count - tests_passed), (int) tests_count); break; case TestOutputFormat::TAP: break; } return false; } else { switch (format) { case TestOutputFormat::ASCII: fprintf( stderr, "\n\033[1;32m[PASS] %i tests passed :)\e[0m\n", (int) tests_count); break; case TestOutputFormat::TAP: break; } return true; } } bool TestRunner::runTestSuite(const std::string& suite, TestOutputFormat format) { if (suite == "world") { return runTestSuite(TestSuite::WORLD, format); } if (suite == "smoke") { return runTestSuite(TestSuite::WORLD, format); } std::cerr << "ERROR: invalid test suite" << std::endl; return false; } bool TestRunner::runTestSuite(TestSuite suite, TestOutputFormat format) { std::set<std::string> test_ids; for (const auto& bundle : test_repo_->getTestBundles()) { for (const auto& test : bundle) { if (test.suites.count(suite) > 0) { test_ids.insert(test.test_id); } } } return runTests(test_ids, format); } void TestRunner::printTestList() { } } // namespace test } // namespace eventql <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <Semaphore.hpp> #include <Error.hpp> ////////////////////////////////////////////////////////////////// TEST(Semaphore, test_01) { using namespace linux::posix; Name n("/ARTA"); OpenOptions f; Semaphore s1(n, false, f, 4); Semaphore s2(n, false); try { s2.close(); } catch (linux::posix::NullPointer& d) { ASSERT_TRUE(true); return; } ASSERT_TRUE(false); } TEST(Semaphore, test_02) { using namespace linux::posix; Name n("/AA"); Semaphore s2(n, true); s2.open(); ASSERT_EQ(1, s2.get()); s2.close(); } TEST(Semaphore, test_03) { using namespace linux::posix; Name n("/A2"); OpenOptions f; Semaphore s1(n, true, f, 4); s1.open(); s1.close(); Semaphore s2(n, true, f, 10); s2.open(); auto a2 = s2.get(); ASSERT_EQ(4, a2); } TEST(Semaphore, test_04) { using namespace linux::posix; Name n("/A3"); OpenOptions f; Semaphore s1(n, true); s1.open(); s1.post(); auto a2 = s1.get(); ASSERT_EQ(2, a2); s1.close(); } TEST(Semaphore, test_05) { using namespace linux::posix; Name n("/A3"); OpenOptions f; Semaphore s1(n, true); s1.open(); s1.post(); auto a2 = s1.get(); ASSERT_EQ(2, a2); s1.wait(); a2 = s1.get(); ASSERT_EQ(1, a2); s1.wait(); a2 = s1.get(); ASSERT_EQ(0, a2); s1.close(); } TEST(Semaphore, test_06) { using namespace linux::posix; Name n("/A3"); OpenOptions f; Semaphore s1(n, true); s1.open(); s1.post(); auto a2 = s1.get(); ASSERT_EQ(2, a2); ASSERT_TRUE(s1.trywait()); a2 = s1.get(); ASSERT_EQ(1, a2); ASSERT_TRUE(s1.trywait()); a2 = s1.get(); ASSERT_EQ(0, a2); ASSERT_FALSE(s1.trywait()); s1.close(); } ////////////////////////////////////////////////////////////////// <commit_msg>add unit test for Semaphore::unlink<commit_after>#include <gtest/gtest.h> #include <Semaphore.hpp> #include <Error.hpp> ////////////////////////////////////////////////////////////////// TEST(Semaphore, test_01) { using namespace linux::posix; Name n("/ARTA"); OpenOptions f; Semaphore s1(n, false, f, 4); Semaphore s2(n, false); try { s2.close(); } catch (linux::posix::NullPointer& d) { ASSERT_TRUE(true); return; } ASSERT_TRUE(false); } TEST(Semaphore, test_02) { using namespace linux::posix; Name n("/AA"); Semaphore s2(n, true); s2.open(); ASSERT_EQ(1, s2.get()); s2.close(); } TEST(Semaphore, test_03) { using namespace linux::posix; Name n("/A2"); OpenOptions f; Semaphore s1(n, true, f, 4); s1.open(); s1.close(); Semaphore s2(n, true, f, 10); s2.open(); auto a2 = s2.get(); ASSERT_EQ(4, a2); } TEST(Semaphore, test_04) { using namespace linux::posix; Name n("/A3"); OpenOptions f; Semaphore s1(n, true); s1.open(); s1.post(); auto a2 = s1.get(); ASSERT_EQ(2, a2); s1.close(); } TEST(Semaphore, test_05) { using namespace linux::posix; Name n("/A3"); OpenOptions f; Semaphore s1(n, true); s1.open(); s1.post(); auto a2 = s1.get(); ASSERT_EQ(2, a2); s1.wait(); a2 = s1.get(); ASSERT_EQ(1, a2); s1.wait(); a2 = s1.get(); ASSERT_EQ(0, a2); s1.close(); } TEST(Semaphore, test_06) { using namespace linux::posix; Name n("/A3"); OpenOptions f; Semaphore s1(n, true); s1.open(); s1.post(); auto a2 = s1.get(); ASSERT_EQ(2, a2); ASSERT_TRUE(s1.trywait()); a2 = s1.get(); ASSERT_EQ(1, a2); ASSERT_TRUE(s1.trywait()); a2 = s1.get(); ASSERT_EQ(0, a2); ASSERT_FALSE(s1.trywait()); s1.close(); } TEST(Semaphore, test_07) { using namespace linux::posix; Name n("/FORUNLINK"); Semaphore s2(n); s2.unlink(); s2.open(); ASSERT_EQ(1, s2.get()); s2.close(); s2.unlink(); } ////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/* * Copyright 2012-2013 BrewPi/Elco Jacobs. * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "Brewpi.h" #include "Version.h" #include "Integration.h" #include "Ticks.h" #include "Comms.h" #include "Commands.h" #include "Values.h" #include "ValuesEeprom.h" #include "ValuesProgmem.h" #include "GenericContainer.h" #include "ValueModels.h" #include "ValueTicks.h" #include "ValueActuator.h" #include "SystemProfile.h" #include "Profile.h" #include "BangBangController.h" #include "ValueDisplay.h" #if defined(ARDUINO) || defined(SPARK) #include "OneWireBus.h" #include "OneWireTempSensor.h" #endif #if BREWPI_SIMULATE && 0 // disable simulator for time being #include "Simulator.h" #endif // global class objects static and defined in class cpp and h files // instantiate and configure the sensors, actuators and controllers we want to use EepromAccess eepromAccess; void setup(void); void loop (void); Container* createRootContainer() { DynamicContainer* d = new DynamicContainer(); return d; } #if 0 class BuildInfoValues : public FactoryContainer { private: public: BuildInfoValues() {} container_id size() { return 1; } virtual Object* item(container_id id) { return new_object(ProgmemStringValue((PSTR(BUILD_NAME)))); } }; #endif bool logValuesFlag = false; const uint8_t loadProfileDelay = 10; // seconds class GlobalSettings { uint8_t settings[10]; Object* externalValueHandler(container_id id) { if (id==-1) return (Object*)10; // size if (id>9) return NULL; return new ExternalValue(settings+id, 1); } }; void setup() { eepromAccess.init(); SystemProfile::initialize(); Comms::init(); #if 0 uint8_t start = ticks.seconds(); while (ticks.timeSince(start) < loadProfileDelay) { Comms::receive(); } #endif SystemProfile::activateDefaultProfile(); } bool prepareCallback(Object* o, void* data, container_id* id, bool enter) { if (enter) { uint32_t& waitUntil = *(uint32_t*)data; prepare_t millisToWait = o->prepare(); if (millisToWait) waitUntil = ticks.millis()+millisToWait; } return false; // continue enumerating } /** * Updates each object in the container hierarchy. */ bool updateCallback(Object* o, void* data, container_id* id, bool enter) { if (enter) o->update(); return false; } /** * Logs all values in the system. */ void logValues(container_id* ids) { DataOut& out = Comms::dataOut(); out.write(CMD_LOG_VALUES_AUTO); logValuesImpl(ids, out); out.close(); } void process() { container_id ids[MAX_CONTAINER_DEPTH]; prepare_t d = 0; Container* root = SystemProfile::rootContainer(); if (root) d = root->prepare(); #if BREWPI_VIRTUAL d = min(prepare_t(1000), d); // just for testing to stop busy waiting #endif uint32_t end = ticks.millis()+d; while (ticks.millis() < end) { Comms::receive(); #if BREWPI_VIRTUAL // avoid busy waiting on a desktop PC since this hogs the cpu wait.millis(10); #endif } Container* root2 = SystemProfile::rootContainer(); // root may have been changed by commands, so original prepare may not be valid // should watch out for newly created objects, since these will then also need preparing if (root == root2 && root) { root->update(); // todo - should brewpi always log, or only log when requested? if (logValuesFlag) { logValuesFlag = false; logValues(ids); } } } /* * Lifecycle for components: * * - prepare: start of a new control loop and determine how long any asynchronous operations will take. * - update: fetch data from the environment, read sensor values, compute settings etc.. */ void brewpiLoop(void) { process(); Comms::receive(); } void loop() { #if 0 && BREWPI_SIMULATE simulateLoop(); #else brewpiLoop(); #endif } /** * ARDUINO_OBJECT - used to declare object factories that are only suitable on * an arduino-compatible device */ #if defined(ARDUINO) || defined(SPARK) #define ARDUINO_OBJECT(x) x #else #define ARDUINO_OBJECT(x) nullFactory #endif #if BREWPI_LCD && 0 #define DISPLAY_OBJECT(x) x #else #define DISPLAY_OBJECT(x) nullFactory #endif /** * Include objects that have not been tested. */ #define BREWPI_EXPERIMENTAL 1 #if BREWPI_EXPERIMENTAL #define EXPERIMENTAL(x) x #else #define EXPERIMENTAL(x) nullFactory #endif ObjectFactory createObjectHandlers[] = { nullFactory, // type 0 ARDUINO_OBJECT(OneWireBus::create), // type 1 ARDUINO_OBJECT(OneWireTempSensor::create), // type 2 CurrentTicksValue::create, // type 3 DynamicContainer::create, // type 4 EepromValue::create, // type 5 Profile::create, // type 6 EXPERIMENTAL(LogicActuator::create), // type 7 EXPERIMENTAL(BangBangController2::create), // type 8 PersistChangeValue::create, // type 9 DISPLAY_OBJECT(DisplayValue::create), // type A DISPLAY_OBJECT(DisplayTemplate::create), // type B // ARDUINO_OBJECT(DigitalPinActuator::create), // type C IndirectValue::create, // type D NULL // When defining a new object type, add the handler above the last NULL value (it's just there to make // editing the code easier). // The Object definition passed to the create handler contains the stream and the block length. // it's critical that the create code reads len bytes from the stream so that the data is // spooled to eeprom to the persisted object definition. }; /** * The application supplied object factory. * Fetches the object type from the stream and looks this up against an array of object factories. */ Object* createApplicationObject(ObjectDefinition& def, bool dryRun) { uint8_t type = def.type; if (dryRun || type>=sizeof(createObjectHandlers)/sizeof(createObjectHandlers[0])) type = 0; // null object creator. Ensures stream is properly consumed even for invalid type values. Object* result = createObjectHandlers[type](def); return result; } #define VERSION /* 0 */ "[\"s\":0,"\ /* 7 */ "\"y\":0,"\ /* 13 */ "\"b\":\" \",\"v\":\"" VERSION_STRING "\",\"c\":\"" stringify(BUILD_NAME) "\"]\n" void printVersion(DataOut& out) { char buf[64]; strcpy_P(buf, PSTR(VERSION)); buf[5] = BREWPI_STATIC_CONFIG+'0'; buf[11] = BREWPI_SIMULATE+'0'; buf[18] = BREWPI_BOARD; out.writeBuffer(buf, strlen(buf)); }<commit_msg>Start WiFi if credentials are given.<commit_after>/* * Copyright 2012-2013 BrewPi/Elco Jacobs. * * This file is part of BrewPi. * * BrewPi is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * BrewPi is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BrewPi. If not, see <http://www.gnu.org/licenses/>. */ #include "Brewpi.h" #include "Version.h" #include "Integration.h" #include "Ticks.h" #include "Comms.h" #include "Commands.h" #include "Values.h" #include "ValuesEeprom.h" #include "ValuesProgmem.h" #include "GenericContainer.h" #include "ValueModels.h" #include "ValueTicks.h" #include "ValueActuator.h" #include "SystemProfile.h" #include "Profile.h" #include "BangBangController.h" #include "ValueDisplay.h" #if defined(ARDUINO) || defined(SPARK) #include "OneWireBus.h" #include "OneWireTempSensor.h" #endif #if BREWPI_SIMULATE && 0 // disable simulator for time being #include "Simulator.h" #endif // global class objects static and defined in class cpp and h files // instantiate and configure the sensors, actuators and controllers we want to use EepromAccess eepromAccess; void setup(void); void loop (void); Container* createRootContainer() { DynamicContainer* d = new DynamicContainer(); return d; } #if 0 class BuildInfoValues : public FactoryContainer { private: public: BuildInfoValues() {} container_id size() { return 1; } virtual Object* item(container_id id) { return new_object(ProgmemStringValue((PSTR(BUILD_NAME)))); } }; #endif bool logValuesFlag = false; const uint8_t loadProfileDelay = 10; // seconds class GlobalSettings { uint8_t settings[10]; Object* externalValueHandler(container_id id) { if (id==-1) return (Object*)10; // size if (id>9) return NULL; return new ExternalValue(settings+id, 1); } }; void setup() { eepromAccess.init(); SystemProfile::initialize(); Comms::init(); #ifdef SPARK WiFi.connect(WIFI_CONNECT_NO_LISTEN); #endif #if 0 uint8_t start = ticks.seconds(); while (ticks.timeSince(start) < loadProfileDelay) { Comms::receive(); } #endif SystemProfile::activateDefaultProfile(); } bool prepareCallback(Object* o, void* data, container_id* id, bool enter) { if (enter) { uint32_t& waitUntil = *(uint32_t*)data; prepare_t millisToWait = o->prepare(); if (millisToWait) waitUntil = ticks.millis()+millisToWait; } return false; // continue enumerating } /** * Updates each object in the container hierarchy. */ bool updateCallback(Object* o, void* data, container_id* id, bool enter) { if (enter) o->update(); return false; } /** * Logs all values in the system. */ void logValues(container_id* ids) { DataOut& out = Comms::dataOut(); out.write(CMD_LOG_VALUES_AUTO); logValuesImpl(ids, out); out.close(); } void process() { container_id ids[MAX_CONTAINER_DEPTH]; prepare_t d = 0; Container* root = SystemProfile::rootContainer(); if (root) d = root->prepare(); #if BREWPI_VIRTUAL d = min(prepare_t(1000), d); // just for testing to stop busy waiting #endif uint32_t end = ticks.millis()+d; while (ticks.millis() < end) { Comms::receive(); #if BREWPI_VIRTUAL // avoid busy waiting on a desktop PC since this hogs the cpu wait.millis(10); #endif } Container* root2 = SystemProfile::rootContainer(); // root may have been changed by commands, so original prepare may not be valid // should watch out for newly created objects, since these will then also need preparing if (root == root2 && root) { root->update(); // todo - should brewpi always log, or only log when requested? if (logValuesFlag) { logValuesFlag = false; logValues(ids); } } } /* * Lifecycle for components: * * - prepare: start of a new control loop and determine how long any asynchronous operations will take. * - update: fetch data from the environment, read sensor values, compute settings etc.. */ void brewpiLoop(void) { process(); Comms::receive(); } void loop() { #if 0 && BREWPI_SIMULATE simulateLoop(); #else brewpiLoop(); #endif } /** * ARDUINO_OBJECT - used to declare object factories that are only suitable on * an arduino-compatible device */ #if defined(ARDUINO) || defined(SPARK) #define ARDUINO_OBJECT(x) x #else #define ARDUINO_OBJECT(x) nullFactory #endif #if BREWPI_LCD && 0 #define DISPLAY_OBJECT(x) x #else #define DISPLAY_OBJECT(x) nullFactory #endif /** * Include objects that have not been tested. */ #define BREWPI_EXPERIMENTAL 1 #if BREWPI_EXPERIMENTAL #define EXPERIMENTAL(x) x #else #define EXPERIMENTAL(x) nullFactory #endif ObjectFactory createObjectHandlers[] = { nullFactory, // type 0 ARDUINO_OBJECT(OneWireBus::create), // type 1 ARDUINO_OBJECT(OneWireTempSensor::create), // type 2 CurrentTicksValue::create, // type 3 DynamicContainer::create, // type 4 EepromValue::create, // type 5 Profile::create, // type 6 EXPERIMENTAL(LogicActuator::create), // type 7 EXPERIMENTAL(BangBangController2::create), // type 8 PersistChangeValue::create, // type 9 DISPLAY_OBJECT(DisplayValue::create), // type A DISPLAY_OBJECT(DisplayTemplate::create), // type B // ARDUINO_OBJECT(DigitalPinActuator::create), // type C IndirectValue::create, // type D NULL // When defining a new object type, add the handler above the last NULL value (it's just there to make // editing the code easier). // The Object definition passed to the create handler contains the stream and the block length. // it's critical that the create code reads len bytes from the stream so that the data is // spooled to eeprom to the persisted object definition. }; /** * The application supplied object factory. * Fetches the object type from the stream and looks this up against an array of object factories. */ Object* createApplicationObject(ObjectDefinition& def, bool dryRun) { uint8_t type = def.type; if (dryRun || type>=sizeof(createObjectHandlers)/sizeof(createObjectHandlers[0])) type = 0; // null object creator. Ensures stream is properly consumed even for invalid type values. Object* result = createObjectHandlers[type](def); return result; } #define VERSION /* 0 */ "[\"s\":0,"\ /* 7 */ "\"y\":0,"\ /* 13 */ "\"b\":\" \",\"v\":\"" VERSION_STRING "\",\"c\":\"" stringify(BUILD_NAME) "\"]\n" void printVersion(DataOut& out) { char buf[64]; strcpy_P(buf, PSTR(VERSION)); buf[5] = BREWPI_STATIC_CONFIG+'0'; buf[11] = BREWPI_SIMULATE+'0'; buf[18] = BREWPI_BOARD; out.writeBuffer(buf, strlen(buf)); }<|endoftext|>
<commit_before>#include "ofAppRunner.h" //======================================================================== // static variables: ofBaseApp * OFSAptr; bool bMousePressed; bool bRightButton; int width, height; ofAppBaseWindow * window = NULL; //======================================================================== // core events instance & arguments #ifdef OF_USING_POCO ofCoreEvents ofEvents; ofEventArgs voidEventArgs; #endif //======================================================================== // callbacks: #ifdef TARGET_OF_IPHONE #include "ofAppiPhoneWindow.h" #else #include "ofAppGlutWindow.h" #endif //-------------------------------------- void ofSetupOpenGL(ofAppBaseWindow * windowPtr, int w, int h, int screenMode){ window = windowPtr; window->setupOpenGL(w, h, screenMode); } //-------------------------------------- void ofSetupOpenGL(int w, int h, int screenMode){ #ifdef TARGET_OF_IPHONE window = new ofAppiPhoneWindow(); #else window = new ofAppGlutWindow(); #endif window->setupOpenGL(w, h, screenMode); } //----------------------- gets called when the app exits // currently looking at who to turn off // at the end of the application void ofExitCallback(); void ofExitCallback(){ //------------------------ // try to close FMOD: ofSoundPlayer::closeFmod(); //------------------------ // try to close quicktime, for non-linux systems: #if defined( TARGET_OSX ) || defined( TARGET_WIN32 ) closeQuicktime(); #endif //------------------------ // try to close freeImage: ofCloseFreeImage(); //------------------------ // try to close free type: // .... #ifdef WIN32_HIGH_RES_TIMING timeEndPeriod(1); #endif if(OFSAptr)OFSAptr->exit(); #ifdef OF_USING_POCO ofNotifyEvent( ofEvents.exit, voidEventArgs ); #endif } //-------------------------------------- void ofRunApp(ofBaseApp * OFSA){ OFSAptr = OFSA; if(OFSAptr){ OFSAptr->mouseX = 0; OFSAptr->mouseY = 0; } atexit(ofExitCallback); #ifdef WIN32_HIGH_RES_TIMING timeBeginPeriod(1); // ! experimental, sets high res time // you need to call timeEndPeriod. // if you quit the app other than "esc" // (ie, close the console, kill the process, etc) // at exit wont get called, and the time will // remain high res, that could mess things // up on your system. // info here:http://www.geisswerks.com/ryan/FAQS/timing.html #endif window->initializeWindow(); ofSeedRandom(); ofResetElapsedTimeCounter(); window->runAppViaInfiniteLoop(OFSAptr); } //-------------------------------------- int ofGetFrameNum(){ return window->getFrameNum(); } //-------------------------------------- float ofGetFrameRate(){ return window->getFrameRate(); } //-------------------------------------- void ofSetFrameRate(int targetRate){ window->setFrameRate(targetRate); } //-------------------------------------- void ofSleepMillis(int millis){ #ifdef TARGET_WIN32 Sleep(millis); //windows sleep in milliseconds #else usleep(millis * 1000); //mac sleep in microseconds - cooler :) #endif } //-------------------------------------- void ofHideCursor(){ window->hideCursor(); } //-------------------------------------- void ofShowCursor(){ window->showCursor(); } //-------------------------------------- void ofSetWindowPosition(int x, int y){ window->setWindowPosition(x,y); } //-------------------------------------- void ofSetWindowShape(int width, int height){ window->setWindowShape(width, height); } //-------------------------------------- int ofGetWindowPositionX(){ return (int)window->getWindowPosition().x; } //-------------------------------------- int ofGetWindowPositionY(){ return (int)window->getWindowPosition().y; } //-------------------------------------- int ofGetScreenWidth(){ return (int)window->getScreenSize().x; } //-------------------------------------- int ofGetScreenHeight(){ return (int)window->getScreenSize().y; } //-------------------------------------------------- int ofGetWidth(){ return (int)window->getWindowSize().x; } //-------------------------------------------------- int ofGetHeight(){ return (int)window->getWindowSize().y; } //-------------------------------------- void ofSetWindowTitle(string title){ window->setWindowTitle(title); } //---------------------------------------------------------- void ofEnableSetupScreen(){ window->enableSetupScreen(); } //---------------------------------------------------------- void ofDisableSetupScreen(){ window->disableSetupScreen(); } //-------------------------------------- void ofToggleFullscreen(){ window->toggleFullscreen(); } //-------------------------------------- void ofSetFullscreen(bool fullscreen){ window->setFullscreen(fullscreen); } //-------------------------------------- int ofGetWindowMode(){ return window->getWindowMode(); } //-------------------------------------- void ofSetVerticalSync(bool bSync){ //---------------------------- #ifdef TARGET_WIN32 //---------------------------- if (bSync) { if (GLEE_WGL_EXT_swap_control) wglSwapIntervalEXT (1); } else { if (GLEE_WGL_EXT_swap_control) wglSwapIntervalEXT (0); } //---------------------------- #endif //---------------------------- //-------------------------------------- #ifdef TARGET_OSX //-------------------------------------- long sync = bSync == true ? 1 : 0; CGLSetParameter (CGLGetCurrentContext(), kCGLCPSwapInterval, &sync); //-------------------------------------- #endif //-------------------------------------- // linux ofSetVerticalSync needed -- anyone want to help w/ this? // http://www.inb.uni-luebeck.de/~boehme/xvideo_sync.html // glXGetVideoSyncSGI(&count); // but needs to be at the end of every "draw? // also, see this: // glXWaitVideoSyncSGI(2,0,&count); } <commit_msg>delete testApp on exit<commit_after>#include "ofAppRunner.h" //======================================================================== // static variables: ofBaseApp * OFSAptr; bool bMousePressed; bool bRightButton; int width, height; ofAppBaseWindow * window = NULL; //======================================================================== // core events instance & arguments #ifdef OF_USING_POCO ofCoreEvents ofEvents; ofEventArgs voidEventArgs; #endif //======================================================================== // callbacks: #ifdef TARGET_OF_IPHONE #include "ofAppiPhoneWindow.h" #else #include "ofAppGlutWindow.h" #endif //-------------------------------------- void ofSetupOpenGL(ofAppBaseWindow * windowPtr, int w, int h, int screenMode){ window = windowPtr; window->setupOpenGL(w, h, screenMode); } //-------------------------------------- void ofSetupOpenGL(int w, int h, int screenMode){ #ifdef TARGET_OF_IPHONE window = new ofAppiPhoneWindow(); #else window = new ofAppGlutWindow(); #endif window->setupOpenGL(w, h, screenMode); } //----------------------- gets called when the app exits // currently looking at who to turn off // at the end of the application void ofExitCallback(); void ofExitCallback(){ //------------------------ // try to close FMOD: ofSoundPlayer::closeFmod(); //------------------------ // try to close quicktime, for non-linux systems: #if defined( TARGET_OSX ) || defined( TARGET_WIN32 ) closeQuicktime(); #endif //------------------------ // try to close freeImage: ofCloseFreeImage(); //------------------------ // try to close free type: // .... #ifdef WIN32_HIGH_RES_TIMING timeEndPeriod(1); #endif if(OFSAptr)OFSAptr->exit(); #ifdef OF_USING_POCO ofNotifyEvent( ofEvents.exit, voidEventArgs ); #endif if(OFSAptr)delete OFSAptr; } //-------------------------------------- void ofRunApp(ofBaseApp * OFSA){ OFSAptr = OFSA; if(OFSAptr){ OFSAptr->mouseX = 0; OFSAptr->mouseY = 0; } atexit(ofExitCallback); #ifdef WIN32_HIGH_RES_TIMING timeBeginPeriod(1); // ! experimental, sets high res time // you need to call timeEndPeriod. // if you quit the app other than "esc" // (ie, close the console, kill the process, etc) // at exit wont get called, and the time will // remain high res, that could mess things // up on your system. // info here:http://www.geisswerks.com/ryan/FAQS/timing.html #endif window->initializeWindow(); ofSeedRandom(); ofResetElapsedTimeCounter(); window->runAppViaInfiniteLoop(OFSAptr); } //-------------------------------------- int ofGetFrameNum(){ return window->getFrameNum(); } //-------------------------------------- float ofGetFrameRate(){ return window->getFrameRate(); } //-------------------------------------- void ofSetFrameRate(int targetRate){ window->setFrameRate(targetRate); } //-------------------------------------- void ofSleepMillis(int millis){ #ifdef TARGET_WIN32 Sleep(millis); //windows sleep in milliseconds #else usleep(millis * 1000); //mac sleep in microseconds - cooler :) #endif } //-------------------------------------- void ofHideCursor(){ window->hideCursor(); } //-------------------------------------- void ofShowCursor(){ window->showCursor(); } //-------------------------------------- void ofSetWindowPosition(int x, int y){ window->setWindowPosition(x,y); } //-------------------------------------- void ofSetWindowShape(int width, int height){ window->setWindowShape(width, height); } //-------------------------------------- int ofGetWindowPositionX(){ return (int)window->getWindowPosition().x; } //-------------------------------------- int ofGetWindowPositionY(){ return (int)window->getWindowPosition().y; } //-------------------------------------- int ofGetScreenWidth(){ return (int)window->getScreenSize().x; } //-------------------------------------- int ofGetScreenHeight(){ return (int)window->getScreenSize().y; } //-------------------------------------------------- int ofGetWidth(){ return (int)window->getWindowSize().x; } //-------------------------------------------------- int ofGetHeight(){ return (int)window->getWindowSize().y; } //-------------------------------------- void ofSetWindowTitle(string title){ window->setWindowTitle(title); } //---------------------------------------------------------- void ofEnableSetupScreen(){ window->enableSetupScreen(); } //---------------------------------------------------------- void ofDisableSetupScreen(){ window->disableSetupScreen(); } //-------------------------------------- void ofToggleFullscreen(){ window->toggleFullscreen(); } //-------------------------------------- void ofSetFullscreen(bool fullscreen){ window->setFullscreen(fullscreen); } //-------------------------------------- int ofGetWindowMode(){ return window->getWindowMode(); } //-------------------------------------- void ofSetVerticalSync(bool bSync){ //---------------------------- #ifdef TARGET_WIN32 //---------------------------- if (bSync) { if (GLEE_WGL_EXT_swap_control) wglSwapIntervalEXT (1); } else { if (GLEE_WGL_EXT_swap_control) wglSwapIntervalEXT (0); } //---------------------------- #endif //---------------------------- //-------------------------------------- #ifdef TARGET_OSX //-------------------------------------- long sync = bSync == true ? 1 : 0; CGLSetParameter (CGLGetCurrentContext(), kCGLCPSwapInterval, &sync); //-------------------------------------- #endif //-------------------------------------- // linux ofSetVerticalSync needed -- anyone want to help w/ this? // http://www.inb.uni-luebeck.de/~boehme/xvideo_sync.html // glXGetVideoSyncSGI(&count); // but needs to be at the end of every "draw? // also, see this: // glXWaitVideoSyncSGI(2,0,&count); } <|endoftext|>
<commit_before>#include <stdexcept> #include <QClipboard> #include <QMessageBox> #include <QSettings> #include <QSharedPointer> #include <QWidget> #include <CorpusWidget.hh> #include <DactMacrosModel.hh> #include <DactTreeScene.hh> #include <DactTreeView.hh> #include <DependencyTreeWidget.hh> #include <FilterModel.hh> #include <ValidityColor.hh> #include <XPathValidator.hh> #include "ui_DependencyTreeWidget.h" DependencyTreeWidget::DependencyTreeWidget(QWidget *parent) : CorpusWidget(parent), d_ui(QSharedPointer<Ui::DependencyTreeWidget>(new Ui::DependencyTreeWidget)), d_macrosModel(QSharedPointer<DactMacrosModel>(new DactMacrosModel())), d_xpathValidator(QSharedPointer<XPathValidator>(new XPathValidator(d_macrosModel))) { d_ui->setupUi(this); addConnections(); d_ui->highlightLineEdit->setValidator(d_xpathValidator.data()); d_ui->hitsDescLabel->hide(); d_ui->hitsLabel->hide(); d_ui->statisticsLayout->setVerticalSpacing(0); } void DependencyTreeWidget::addConnections() { connect(d_ui->highlightLineEdit, SIGNAL(textChanged(QString const &)), SLOT(applyValidityColor(QString const &))); connect(d_ui->highlightLineEdit, SIGNAL(returnPressed()), SLOT(highlightChanged())); connect(d_ui->treeGraphicsView, SIGNAL(sceneChanged(DactTreeScene*)), SIGNAL(sceneChanged(DactTreeScene*))); } void DependencyTreeWidget::applyValidityColor(QString const &) { ::applyValidityColor(sender()); } void DependencyTreeWidget::cancelQuery() { if (d_model) d_model->cancelQuery(); } void DependencyTreeWidget::copy() { if (!d_model) return; QStringList filenames; QModelIndexList indices = d_ui->fileListWidget->selectionModel()->selectedIndexes(); for (QModelIndexList::const_iterator iter = indices.begin(); iter != indices.end(); ++iter) { QVariant v = d_model->data(*iter, Qt::DisplayRole); if (v.type() == QVariant::String) filenames.push_back(v.toString()); } QApplication::clipboard()->setText(filenames.join("\n")); // XXX - Good enough for Windows? } void DependencyTreeWidget::nEntriesFound(int entries, int hits) { d_ui->entriesLabel->setText(QString("%L1").arg(entries)); d_ui->hitsLabel->setText(QString("%L1").arg(hits)); if (!d_treeShown) { d_ui->fileListWidget->selectionModel()->clear(); QModelIndex idx(d_model->index(0, 0)); d_ui->fileListWidget->selectionModel()->setCurrentIndex(idx, QItemSelectionModel::ClearAndSelect); d_treeShown = true; } } void DependencyTreeWidget::entrySelected(QModelIndex const &current, QModelIndex const &prev) { Q_UNUSED(prev); if (!current.isValid()) { d_ui->treeGraphicsView->setScene(0); d_ui->sentenceWidget->clear(); return; } showFile(current.data(Qt::UserRole).toString()); //focusFitTree(); focusFirstMatch(); } void DependencyTreeWidget::fitTree() { d_ui->treeGraphicsView->fitTree(); } void DependencyTreeWidget::focusFirstMatch() { if (d_ui->treeGraphicsView->scene() && d_ui->treeGraphicsView->scene()->activeNodes().length() > 0) d_ui->treeGraphicsView->focusTreeNode(1); } void DependencyTreeWidget::focusFitTree() { if (d_ui->treeGraphicsView->scene() && d_ui->treeGraphicsView->scene()->activeNodes().length()) { d_ui->treeGraphicsView->resetZoom(); d_ui->treeGraphicsView->focusTreeNode(1); } else d_ui->treeGraphicsView->fitTree(); } void DependencyTreeWidget::focusHighlight() { d_ui->highlightLineEdit->setFocus(); } void DependencyTreeWidget::focusNextTreeNode() { d_ui->treeGraphicsView->focusNextTreeNode(); } void DependencyTreeWidget::focusPreviousTreeNode() { d_ui->treeGraphicsView->focusPreviousTreeNode(); } void DependencyTreeWidget::highlightChanged() { setHighlight(d_ui->highlightLineEdit->text().trimmed()); } void DependencyTreeWidget::mapperStarted(int totalEntries) { d_ui->entriesLabel->setText(QString::number(0)); d_ui->hitsLabel->setText(QString::number(0)); d_ui->filterProgressBar->setMinimum(0); d_ui->filterProgressBar->setMaximum(totalEntries); d_ui->filterProgressBar->setValue(0); d_ui->filterProgressBar->setVisible(true); } void DependencyTreeWidget::mapperFailed(QString error) { d_ui->filterProgressBar->setVisible(false); QMessageBox::critical(this, tr("Error processing query"), tr("Could not process query: ") + error, QMessageBox::Ok); } void DependencyTreeWidget::mapperFinished(int processedEntries, int totalEntries, bool cached) { if (cached) { d_ui->fileListWidget->selectionModel()->clear(); QModelIndex idx(d_model->index(0, 0)); d_ui->fileListWidget->selectionModel()->setCurrentIndex(idx, QItemSelectionModel::ClearAndSelect); } mapperStopped(processedEntries, totalEntries); } void DependencyTreeWidget::mapperStopped(int processedEntries, int totalEntries) { d_ui->filterProgressBar->setVisible(false); // Final counts. Doing this again is necessary, because the query may // have been cached. If so, it doesn't emit a signal for every entry. int entries = d_model->rowCount(QModelIndex()); int hits = d_model->hits(); d_ui->entriesLabel->setText(QString("%L1").arg(entries)); d_ui->hitsLabel->setText(QString("%L1").arg(hits)); if (!d_file.isNull()) { QModelIndex current = d_model->indexOfFile(d_file); d_ui->fileListWidget->setCurrentIndex(current); } } /* Next- and prev entry buttons */ void DependencyTreeWidget::nextEntry(bool) { QModelIndex current(d_ui->fileListWidget->currentIndex()); d_ui->fileListWidget->setCurrentIndex( current.sibling(current.row() + 1, current.column())); } void DependencyTreeWidget::previousEntry(bool) { QModelIndex current(d_ui->fileListWidget->currentIndex()); d_ui->fileListWidget->setCurrentIndex( current.sibling(current.row() - 1, current.column())); } void DependencyTreeWidget::readSettings() { QSettings settings; // Splitter. d_ui->splitter->restoreState( settings.value("splitterSizes").toByteArray()); } void DependencyTreeWidget::renderTree(QPainter *painter) { if (d_ui->treeGraphicsView->scene()) d_ui->treeGraphicsView->scene()->render(painter); } DactTreeScene *DependencyTreeWidget::scene() { return d_ui->treeGraphicsView->scene(); } QItemSelectionModel *DependencyTreeWidget::selectionModel() { return d_ui->fileListWidget->selectionModel(); } void DependencyTreeWidget::setFilter(QString const &filter) { d_filter = filter; d_treeShown = false; if (d_filter.isEmpty()) { d_ui->hitsDescLabel->hide(); d_ui->hitsLabel->hide(); d_ui->statisticsLayout->setVerticalSpacing(0); } else { d_ui->statisticsLayout->setVerticalSpacing(-1); d_ui->hitsDescLabel->show(); d_ui->hitsLabel->show(); } setHighlight(d_filter); d_model->runQuery(d_filter); } void DependencyTreeWidget::setModel(FilterModel *model) { d_model = QSharedPointer<FilterModel>(model); d_ui->fileListWidget->setModel(d_model.data()); connect(model, SIGNAL(queryFailed(QString)), SLOT(mapperFailed(QString))); connect(model, SIGNAL(queryStarted(int)), SLOT(mapperStarted(int))); connect(model, SIGNAL(queryStopped(int, int)), SLOT(mapperStopped(int, int))); connect(model, SIGNAL(queryFinished(int, int, bool)), SLOT(mapperFinished(int, int, bool))); connect(model, SIGNAL(nEntriesFound(int, int)), SLOT(nEntriesFound(int, int))); connect(d_ui->fileListWidget->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), SLOT(entrySelected(QModelIndex,QModelIndex))); } void DependencyTreeWidget::setHighlight(QString const &query) { d_highlight = query; d_ui->highlightLineEdit->setText(query); showFile(); // to force-reload the tree and bracketed sentence } void DependencyTreeWidget::showFile() { if (!d_file.isNull()) showFile(d_file); } void DependencyTreeWidget::showFile(QString const &entry) { // Read XML data. if (d_corpusReader.isNull()) return; try { QString xml; if (d_highlight.trimmed().isEmpty()) xml = QString::fromUtf8(d_corpusReader->read(entry.toUtf8().constData()).c_str()); else { ac::CorpusReader::MarkerQuery query(d_macrosModel->expand(d_highlight).toUtf8().constData(), "active", "1"); std::list<ac::CorpusReader::MarkerQuery> queries; queries.push_back(query); xml = QString::fromUtf8(d_corpusReader->read(entry.toUtf8().constData(), queries).c_str()); } if (xml.size() == 0) { qWarning() << "MainWindow::writeSettings: empty XML data!"; d_ui->treeGraphicsView->setScene(0); return; } // Remember file for when we need to redraw the tree d_file = entry; // Parameters QString valStr = d_highlight.trimmed().isEmpty() ? "'/..'" : QString("'") + d_macrosModel->expand(d_highlight) + QString("'"); QHash<QString, QString> params; params["expr"] = valStr; try { showTree(xml); showSentence(xml, params); // I try to find my file back in the file list to keep the list // in sync with the treegraph since showFile can be called from // the child dialogs. QModelIndexList matches = d_ui->fileListWidget->model()->match( d_ui->fileListWidget->model()->index(0, 0), Qt::DisplayRole, entry, 1, Qt::MatchFixedString | Qt::MatchCaseSensitive); if (matches.size() > 0) { d_ui->fileListWidget->selectionModel()->select(matches.at(0), QItemSelectionModel::ClearAndSelect); d_ui->fileListWidget->scrollTo(matches.at(0)); } } catch (std::runtime_error const &e) { QMessageBox::critical(this, QString("Tranformation error"), QString("A transformation error occured: %1\n\nCorpus data is probably corrupt.").arg(e.what())); } } catch(std::runtime_error const &e) { QMessageBox::critical(this, QString("Read error"), QString("An error occured while trying to read a corpus file: %1").arg(e.what())); } } void DependencyTreeWidget::showSentence(QString const &xml, QHash<QString, QString> const &params) { d_ui->sentenceWidget->setParse(xml); } void DependencyTreeWidget::showTree(QString const &xml) { d_ui->treeGraphicsView->showTree(xml); } void DependencyTreeWidget::switchCorpus(QSharedPointer<alpinocorpus::CorpusReader> corpusReader) { d_corpusReader = corpusReader; d_xpathValidator->setCorpusReader(d_corpusReader); setModel(new FilterModel(d_corpusReader)); QString query = d_ui->highlightLineEdit->text(); d_ui->highlightLineEdit->clear(); d_ui->highlightLineEdit->insert(query); d_model->runQuery(d_macrosModel->expand(d_filter)); } void DependencyTreeWidget::writeSettings() { QSettings settings; // Splitter settings.setValue("splitterSizes", d_ui->splitter->saveState()); } void DependencyTreeWidget::zoomIn() { d_ui->treeGraphicsView->zoomIn(); } void DependencyTreeWidget::zoomOut() { d_ui->treeGraphicsView->zoomOut(); } <commit_msg>DependencyTreeWidget: Clear the current file when running a query.<commit_after>#include <stdexcept> #include <QClipboard> #include <QMessageBox> #include <QSettings> #include <QSharedPointer> #include <QWidget> #include <CorpusWidget.hh> #include <DactMacrosModel.hh> #include <DactTreeScene.hh> #include <DactTreeView.hh> #include <DependencyTreeWidget.hh> #include <FilterModel.hh> #include <ValidityColor.hh> #include <XPathValidator.hh> #include "ui_DependencyTreeWidget.h" DependencyTreeWidget::DependencyTreeWidget(QWidget *parent) : CorpusWidget(parent), d_ui(QSharedPointer<Ui::DependencyTreeWidget>(new Ui::DependencyTreeWidget)), d_macrosModel(QSharedPointer<DactMacrosModel>(new DactMacrosModel())), d_xpathValidator(QSharedPointer<XPathValidator>(new XPathValidator(d_macrosModel))) { d_ui->setupUi(this); addConnections(); d_ui->highlightLineEdit->setValidator(d_xpathValidator.data()); d_ui->hitsDescLabel->hide(); d_ui->hitsLabel->hide(); d_ui->statisticsLayout->setVerticalSpacing(0); } void DependencyTreeWidget::addConnections() { connect(d_ui->highlightLineEdit, SIGNAL(textChanged(QString const &)), SLOT(applyValidityColor(QString const &))); connect(d_ui->highlightLineEdit, SIGNAL(returnPressed()), SLOT(highlightChanged())); connect(d_ui->treeGraphicsView, SIGNAL(sceneChanged(DactTreeScene*)), SIGNAL(sceneChanged(DactTreeScene*))); } void DependencyTreeWidget::applyValidityColor(QString const &) { ::applyValidityColor(sender()); } void DependencyTreeWidget::cancelQuery() { if (d_model) d_model->cancelQuery(); } void DependencyTreeWidget::copy() { if (!d_model) return; QStringList filenames; QModelIndexList indices = d_ui->fileListWidget->selectionModel()->selectedIndexes(); for (QModelIndexList::const_iterator iter = indices.begin(); iter != indices.end(); ++iter) { QVariant v = d_model->data(*iter, Qt::DisplayRole); if (v.type() == QVariant::String) filenames.push_back(v.toString()); } QApplication::clipboard()->setText(filenames.join("\n")); // XXX - Good enough for Windows? } void DependencyTreeWidget::nEntriesFound(int entries, int hits) { d_ui->entriesLabel->setText(QString("%L1").arg(entries)); d_ui->hitsLabel->setText(QString("%L1").arg(hits)); if (!d_treeShown) { d_ui->fileListWidget->selectionModel()->clear(); QModelIndex idx(d_model->index(0, 0)); d_ui->fileListWidget->selectionModel()->setCurrentIndex(idx, QItemSelectionModel::ClearAndSelect); d_treeShown = true; } } void DependencyTreeWidget::entrySelected(QModelIndex const &current, QModelIndex const &prev) { Q_UNUSED(prev); if (!current.isValid()) { d_ui->treeGraphicsView->setScene(0); d_ui->sentenceWidget->clear(); return; } showFile(current.data(Qt::UserRole).toString()); //focusFitTree(); focusFirstMatch(); } void DependencyTreeWidget::fitTree() { d_ui->treeGraphicsView->fitTree(); } void DependencyTreeWidget::focusFirstMatch() { if (d_ui->treeGraphicsView->scene() && d_ui->treeGraphicsView->scene()->activeNodes().length() > 0) d_ui->treeGraphicsView->focusTreeNode(1); } void DependencyTreeWidget::focusFitTree() { if (d_ui->treeGraphicsView->scene() && d_ui->treeGraphicsView->scene()->activeNodes().length()) { d_ui->treeGraphicsView->resetZoom(); d_ui->treeGraphicsView->focusTreeNode(1); } else d_ui->treeGraphicsView->fitTree(); } void DependencyTreeWidget::focusHighlight() { d_ui->highlightLineEdit->setFocus(); } void DependencyTreeWidget::focusNextTreeNode() { d_ui->treeGraphicsView->focusNextTreeNode(); } void DependencyTreeWidget::focusPreviousTreeNode() { d_ui->treeGraphicsView->focusPreviousTreeNode(); } void DependencyTreeWidget::highlightChanged() { setHighlight(d_ui->highlightLineEdit->text().trimmed()); } void DependencyTreeWidget::mapperStarted(int totalEntries) { d_ui->entriesLabel->setText(QString::number(0)); d_ui->hitsLabel->setText(QString::number(0)); d_ui->filterProgressBar->setMinimum(0); d_ui->filterProgressBar->setMaximum(totalEntries); d_ui->filterProgressBar->setValue(0); d_ui->filterProgressBar->setVisible(true); } void DependencyTreeWidget::mapperFailed(QString error) { d_ui->filterProgressBar->setVisible(false); QMessageBox::critical(this, tr("Error processing query"), tr("Could not process query: ") + error, QMessageBox::Ok); } void DependencyTreeWidget::mapperFinished(int processedEntries, int totalEntries, bool cached) { if (cached) { d_ui->fileListWidget->selectionModel()->clear(); QModelIndex idx(d_model->index(0, 0)); d_ui->fileListWidget->selectionModel()->setCurrentIndex(idx, QItemSelectionModel::ClearAndSelect); } mapperStopped(processedEntries, totalEntries); } void DependencyTreeWidget::mapperStopped(int processedEntries, int totalEntries) { d_ui->filterProgressBar->setVisible(false); // Final counts. Doing this again is necessary, because the query may // have been cached. If so, it doesn't emit a signal for every entry. int entries = d_model->rowCount(QModelIndex()); int hits = d_model->hits(); d_ui->entriesLabel->setText(QString("%L1").arg(entries)); d_ui->hitsLabel->setText(QString("%L1").arg(hits)); if (!d_file.isNull()) { QModelIndex current = d_model->indexOfFile(d_file); d_ui->fileListWidget->setCurrentIndex(current); } } /* Next- and prev entry buttons */ void DependencyTreeWidget::nextEntry(bool) { QModelIndex current(d_ui->fileListWidget->currentIndex()); d_ui->fileListWidget->setCurrentIndex( current.sibling(current.row() + 1, current.column())); } void DependencyTreeWidget::previousEntry(bool) { QModelIndex current(d_ui->fileListWidget->currentIndex()); d_ui->fileListWidget->setCurrentIndex( current.sibling(current.row() - 1, current.column())); } void DependencyTreeWidget::readSettings() { QSettings settings; // Splitter. d_ui->splitter->restoreState( settings.value("splitterSizes").toByteArray()); } void DependencyTreeWidget::renderTree(QPainter *painter) { if (d_ui->treeGraphicsView->scene()) d_ui->treeGraphicsView->scene()->render(painter); } DactTreeScene *DependencyTreeWidget::scene() { return d_ui->treeGraphicsView->scene(); } QItemSelectionModel *DependencyTreeWidget::selectionModel() { return d_ui->fileListWidget->selectionModel(); } void DependencyTreeWidget::setFilter(QString const &filter) { d_filter = filter; d_treeShown = false; d_file = QString(); if (d_filter.isEmpty()) { d_ui->hitsDescLabel->hide(); d_ui->hitsLabel->hide(); d_ui->statisticsLayout->setVerticalSpacing(0); } else { d_ui->statisticsLayout->setVerticalSpacing(-1); d_ui->hitsDescLabel->show(); d_ui->hitsLabel->show(); } setHighlight(d_filter); d_model->runQuery(d_filter); } void DependencyTreeWidget::setModel(FilterModel *model) { d_model = QSharedPointer<FilterModel>(model); d_ui->fileListWidget->setModel(d_model.data()); connect(model, SIGNAL(queryFailed(QString)), SLOT(mapperFailed(QString))); connect(model, SIGNAL(queryStarted(int)), SLOT(mapperStarted(int))); connect(model, SIGNAL(queryStopped(int, int)), SLOT(mapperStopped(int, int))); connect(model, SIGNAL(queryFinished(int, int, bool)), SLOT(mapperFinished(int, int, bool))); connect(model, SIGNAL(nEntriesFound(int, int)), SLOT(nEntriesFound(int, int))); connect(d_ui->fileListWidget->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), SLOT(entrySelected(QModelIndex,QModelIndex))); } void DependencyTreeWidget::setHighlight(QString const &query) { d_highlight = query; d_ui->highlightLineEdit->setText(query); showFile(); // to force-reload the tree and bracketed sentence } void DependencyTreeWidget::showFile() { if (!d_file.isNull()) showFile(d_file); } void DependencyTreeWidget::showFile(QString const &entry) { // Read XML data. if (d_corpusReader.isNull()) return; try { QString xml; if (d_highlight.trimmed().isEmpty()) xml = QString::fromUtf8(d_corpusReader->read(entry.toUtf8().constData()).c_str()); else { ac::CorpusReader::MarkerQuery query(d_macrosModel->expand(d_highlight).toUtf8().constData(), "active", "1"); std::list<ac::CorpusReader::MarkerQuery> queries; queries.push_back(query); xml = QString::fromUtf8(d_corpusReader->read(entry.toUtf8().constData(), queries).c_str()); } if (xml.size() == 0) { qWarning() << "MainWindow::writeSettings: empty XML data!"; d_ui->treeGraphicsView->setScene(0); return; } // Remember file for when we need to redraw the tree d_file = entry; // Parameters QString valStr = d_highlight.trimmed().isEmpty() ? "'/..'" : QString("'") + d_macrosModel->expand(d_highlight) + QString("'"); QHash<QString, QString> params; params["expr"] = valStr; try { showTree(xml); showSentence(xml, params); // I try to find my file back in the file list to keep the list // in sync with the treegraph since showFile can be called from // the child dialogs. QModelIndexList matches = d_ui->fileListWidget->model()->match( d_ui->fileListWidget->model()->index(0, 0), Qt::DisplayRole, entry, 1, Qt::MatchFixedString | Qt::MatchCaseSensitive); if (matches.size() > 0) { d_ui->fileListWidget->selectionModel()->select(matches.at(0), QItemSelectionModel::ClearAndSelect); d_ui->fileListWidget->scrollTo(matches.at(0)); } } catch (std::runtime_error const &e) { QMessageBox::critical(this, QString("Tranformation error"), QString("A transformation error occured: %1\n\nCorpus data is probably corrupt.").arg(e.what())); } } catch(std::runtime_error const &e) { QMessageBox::critical(this, QString("Read error"), QString("An error occured while trying to read a corpus file: %1").arg(e.what())); } } void DependencyTreeWidget::showSentence(QString const &xml, QHash<QString, QString> const &params) { d_ui->sentenceWidget->setParse(xml); } void DependencyTreeWidget::showTree(QString const &xml) { d_ui->treeGraphicsView->showTree(xml); } void DependencyTreeWidget::switchCorpus(QSharedPointer<alpinocorpus::CorpusReader> corpusReader) { d_corpusReader = corpusReader; d_xpathValidator->setCorpusReader(d_corpusReader); setModel(new FilterModel(d_corpusReader)); QString query = d_ui->highlightLineEdit->text(); d_ui->highlightLineEdit->clear(); d_ui->highlightLineEdit->insert(query); d_model->runQuery(d_macrosModel->expand(d_filter)); } void DependencyTreeWidget::writeSettings() { QSettings settings; // Splitter settings.setValue("splitterSizes", d_ui->splitter->saveState()); } void DependencyTreeWidget::zoomIn() { d_ui->treeGraphicsView->zoomIn(); } void DependencyTreeWidget::zoomOut() { d_ui->treeGraphicsView->zoomOut(); } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2016 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "OSPCommon.h" #ifdef OSPRAY_USE_INTERNAL_TASKING # include "ospray/common/tasking/TaskSys.h" #endif #include "ospray/common/tasking/async.h" // embree #include "embree2/rtcore.h" #include "common/sysinfo.h" //stl #include <thread> namespace ospray { /*! 64-bit malloc. allows for alloc'ing memory larger than 64 bits */ extern "C" void *malloc64(size_t size) { return ospcommon::alignedMalloc(size); } /*! 64-bit malloc. allows for alloc'ing memory larger than 64 bits */ extern "C" void free64(void *ptr) { return ospcommon::alignedFree(ptr); } /*! logging level - '0' means 'no logging at all', increasing numbers mean increasing verbosity of log messages */ uint32_t logLevel = 0; bool debugMode = false; int32_t numThreads = -1; //!< for default (==maximum) number of OSPRay/Embree threads WarnOnce::WarnOnce(const std::string &s) : s(s) { std::cout << "Warning: " << s << " (only reporting first occurrence)" << std::endl; } /*! for debugging. compute a checksum for given area range... */ void *computeCheckSum(const void *ptr, size_t numBytes) { long *end = (long *)((char *)ptr + (numBytes - (numBytes%8))); long *mem = (long *)ptr; long sum = 0; long i = 0; int nextPing = 1; while (mem < end) { sum += (i+13) * *mem; ++i; ++mem; // if (i==nextPing) { // std::cout << "checksum after " << (i*8) << " bytes: " << (int*)sum << std::endl; // nextPing += nextPing; // } } return (void *)sum; } void doAssertion(const char *file, int line, const char *expr, const char *expl) { if (expl) fprintf(stderr,"%s:%i: Assertion failed: \"%s\":\nAdditional Info: %s\n", file, line, expr, expl); else fprintf(stderr,"%s:%i: Assertion failed: \"%s\".\n", file, line, expr); abort(); } void removeArgs(int &ac, char **&av, int where, int howMany) { for (int i=where+howMany;i<ac;i++) av[i-howMany] = av[i]; ac -= howMany; } void init(int *_ac, const char ***_av) { #ifndef OSPRAY_TARGET_MIC // If we're not on a MIC, check for SSE4.1 as minimum supported ISA. Will be increased to SSE4.2 in future. int cpuFeatures = ospcommon::getCPUFeatures(); if ((cpuFeatures & ospcommon::CPU_FEATURE_SSE41) == 0) throw std::runtime_error("Error. OSPRay only runs on CPUs that support at least SSE4.1."); #endif if (_ac && _av) { int &ac = *_ac; char ** &av = *(char ***)_av; for (int i=1;i<ac;) { std::string parm = av[i]; if (parm == "--osp:debug") { debugMode = true; numThreads = 1; removeArgs(ac,av,i,1); } else if (parm == "--osp:verbose") { logLevel = 1; removeArgs(ac,av,i,1); } else if (parm == "--osp:vv") { logLevel = 2; removeArgs(ac,av,i,1); } else if (parm == "--osp:loglevel") { logLevel = atoi(av[i+1]); removeArgs(ac,av,i,2); } else if (parm == "--osp:numthreads" || parm == "--osp:num-threads") { numThreads = atoi(av[i+1]); removeArgs(ac,av,i,2); } else { ++i; } } } #ifdef OSPRAY_USE_INTERNAL_TASKING try { ospray::Task::initTaskSystem(debugMode ? 0 : numThreads); } catch (const std::runtime_error &e) { std::cerr << "WARNING: " << e.what() << std::endl; } #endif // NOTE(jda) - Make sure that each thread (both calling application thread // and OSPRay worker threads) has the correct denormals flags // set. _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); const int NTASKS = std::min((uint32_t)numThreads, std::thread::hardware_concurrency()) - 1; AtomicInt counter; counter = 0; // Force each worker thread to pickup exactly one task which sets denormals // flags, where each thread spins until they are all done. for (int i = 0; i < NTASKS; ++i) { async([&]() { _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); counter++; while(counter < NTASKS); }); } } void error_handler(const RTCError code, const char *str) { printf("Embree: "); switch (code) { case RTC_UNKNOWN_ERROR : printf("RTC_UNKNOWN_ERROR"); break; case RTC_INVALID_ARGUMENT : printf("RTC_INVALID_ARGUMENT"); break; case RTC_INVALID_OPERATION: printf("RTC_INVALID_OPERATION"); break; case RTC_OUT_OF_MEMORY : printf("RTC_OUT_OF_MEMORY"); break; case RTC_UNSUPPORTED_CPU : printf("RTC_UNSUPPORTED_CPU"); break; default : printf("invalid error code"); break; } if (str) { printf(" ("); while (*str) putchar(*str++); printf(")\n"); } abort(); } size_t sizeOf(const OSPDataType type) { switch (type) { case OSP_VOID_PTR: return sizeof(void *); case OSP_OBJECT: return sizeof(void *); case OSP_DATA: return sizeof(void *); case OSP_CHAR: return sizeof(int8); case OSP_UCHAR: return sizeof(uint8); case OSP_UCHAR2: return sizeof(vec2uc); case OSP_UCHAR3: return sizeof(vec3uc); case OSP_UCHAR4: return sizeof(vec4uc); case OSP_INT: return sizeof(int32); case OSP_INT2: return sizeof(vec2i); case OSP_INT3: return sizeof(vec3i); case OSP_INT4: return sizeof(vec4i); case OSP_UINT: return sizeof(uint32); case OSP_UINT2: return sizeof(vec2ui); case OSP_UINT3: return sizeof(vec3ui); case OSP_UINT4: return sizeof(vec4ui); case OSP_LONG: return sizeof(int64); case OSP_LONG2: return sizeof(vec2l); case OSP_LONG3: return sizeof(vec3l); case OSP_LONG4: return sizeof(vec4l); case OSP_ULONG: return sizeof(uint64); case OSP_ULONG2: return sizeof(vec2ul); case OSP_ULONG3: return sizeof(vec3ul); case OSP_ULONG4: return sizeof(vec4ul); case OSP_FLOAT: return sizeof(float); case OSP_FLOAT2: return sizeof(vec2f); case OSP_FLOAT3: return sizeof(vec3f); case OSP_FLOAT4: return sizeof(vec4f); case OSP_FLOAT3A: return sizeof(vec3fa); case OSP_DOUBLE: return sizeof(double); default: break; }; std::stringstream error; error << __FILE__ << ":" << __LINE__ << ": unknown OSPDataType " << (int)type; throw std::runtime_error(error.str()); } OSPDataType typeForString(const char *string) { if (string == NULL) return(OSP_UNKNOWN); if (strcmp(string, "char" ) == 0) return(OSP_CHAR); if (strcmp(string, "double") == 0) return(OSP_DOUBLE); if (strcmp(string, "float" ) == 0) return(OSP_FLOAT); if (strcmp(string, "float2") == 0) return(OSP_FLOAT2); if (strcmp(string, "float3") == 0) return(OSP_FLOAT2); if (strcmp(string, "float4") == 0) return(OSP_FLOAT2); if (strcmp(string, "int" ) == 0) return(OSP_INT); if (strcmp(string, "int2" ) == 0) return(OSP_INT2); if (strcmp(string, "int3" ) == 0) return(OSP_INT3); if (strcmp(string, "int4" ) == 0) return(OSP_INT4); if (strcmp(string, "uchar" ) == 0) return(OSP_UCHAR); if (strcmp(string, "uchar2") == 0) return(OSP_UCHAR2); if (strcmp(string, "uchar3") == 0) return(OSP_UCHAR3); if (strcmp(string, "uchar4") == 0) return(OSP_UCHAR4); if (strcmp(string, "uint" ) == 0) return(OSP_UINT); if (strcmp(string, "uint2" ) == 0) return(OSP_UINT2); if (strcmp(string, "uint3" ) == 0) return(OSP_UINT3); if (strcmp(string, "uint4" ) == 0) return(OSP_UINT4); return(OSP_UNKNOWN); } size_t sizeOf(const OSPTextureFormat type) { switch (type) { case OSP_TEXTURE_RGBA8: case OSP_TEXTURE_SRGBA: return sizeof(uint32); case OSP_TEXTURE_RGBA32F: return sizeof(vec4f); case OSP_TEXTURE_RGB8: case OSP_TEXTURE_SRGB: return sizeof(vec3uc); case OSP_TEXTURE_RGB32F: return sizeof(vec3f); case OSP_TEXTURE_R8: return sizeof(uint8); case OSP_TEXTURE_R32F: return sizeof(float); } std::stringstream error; error << __FILE__ << ":" << __LINE__ << ": unknown OSPTextureFormat " << (int)type; throw std::runtime_error(error.str()); } } // ::ospray <commit_msg>disable denormals config code which casuses issues in icc builds<commit_after>// ======================================================================== // // Copyright 2009-2016 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "OSPCommon.h" #ifdef OSPRAY_USE_INTERNAL_TASKING # include "ospray/common/tasking/TaskSys.h" #endif #include "ospray/common/tasking/async.h" // embree #include "embree2/rtcore.h" #include "common/sysinfo.h" //stl #include <thread> namespace ospray { /*! 64-bit malloc. allows for alloc'ing memory larger than 64 bits */ extern "C" void *malloc64(size_t size) { return ospcommon::alignedMalloc(size); } /*! 64-bit malloc. allows for alloc'ing memory larger than 64 bits */ extern "C" void free64(void *ptr) { return ospcommon::alignedFree(ptr); } /*! logging level - '0' means 'no logging at all', increasing numbers mean increasing verbosity of log messages */ uint32_t logLevel = 0; bool debugMode = false; int32_t numThreads = -1; //!< for default (==maximum) number of OSPRay/Embree threads WarnOnce::WarnOnce(const std::string &s) : s(s) { std::cout << "Warning: " << s << " (only reporting first occurrence)" << std::endl; } /*! for debugging. compute a checksum for given area range... */ void *computeCheckSum(const void *ptr, size_t numBytes) { long *end = (long *)((char *)ptr + (numBytes - (numBytes%8))); long *mem = (long *)ptr; long sum = 0; long i = 0; int nextPing = 1; while (mem < end) { sum += (i+13) * *mem; ++i; ++mem; // if (i==nextPing) { // std::cout << "checksum after " << (i*8) << " bytes: " << (int*)sum << std::endl; // nextPing += nextPing; // } } return (void *)sum; } void doAssertion(const char *file, int line, const char *expr, const char *expl) { if (expl) fprintf(stderr,"%s:%i: Assertion failed: \"%s\":\nAdditional Info: %s\n", file, line, expr, expl); else fprintf(stderr,"%s:%i: Assertion failed: \"%s\".\n", file, line, expr); abort(); } void removeArgs(int &ac, char **&av, int where, int howMany) { for (int i=where+howMany;i<ac;i++) av[i-howMany] = av[i]; ac -= howMany; } void init(int *_ac, const char ***_av) { #ifndef OSPRAY_TARGET_MIC // If we're not on a MIC, check for SSE4.1 as minimum supported ISA. Will be increased to SSE4.2 in future. int cpuFeatures = ospcommon::getCPUFeatures(); if ((cpuFeatures & ospcommon::CPU_FEATURE_SSE41) == 0) throw std::runtime_error("Error. OSPRay only runs on CPUs that support at least SSE4.1."); #endif if (_ac && _av) { int &ac = *_ac; char ** &av = *(char ***)_av; for (int i=1;i<ac;) { std::string parm = av[i]; if (parm == "--osp:debug") { debugMode = true; numThreads = 1; removeArgs(ac,av,i,1); } else if (parm == "--osp:verbose") { logLevel = 1; removeArgs(ac,av,i,1); } else if (parm == "--osp:vv") { logLevel = 2; removeArgs(ac,av,i,1); } else if (parm == "--osp:loglevel") { logLevel = atoi(av[i+1]); removeArgs(ac,av,i,2); } else if (parm == "--osp:numthreads" || parm == "--osp:num-threads") { numThreads = atoi(av[i+1]); removeArgs(ac,av,i,2); } else { ++i; } } } #ifdef OSPRAY_USE_INTERNAL_TASKING try { ospray::Task::initTaskSystem(debugMode ? 0 : numThreads); } catch (const std::runtime_error &e) { std::cerr << "WARNING: " << e.what() << std::endl; } #endif // NOTE(jda) - This doesn't seem to be the right solution, needs further // investigation before enabling again....temporarily disable #if 0 // NOTE(jda) - Make sure that each thread (both calling application thread // and OSPRay worker threads) has the correct denormals flags // set. _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); const int NTASKS = std::min((uint32_t)numThreads, std::thread::hardware_concurrency()) - 1; AtomicInt counter; counter = 0; // Force each worker thread to pickup exactly one task which sets denormals // flags, where each thread spins until they are all done. for (int i = 0; i < NTASKS; ++i) { async([&]() { _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); counter++; while(counter < NTASKS); }); } #endif } void error_handler(const RTCError code, const char *str) { printf("Embree: "); switch (code) { case RTC_UNKNOWN_ERROR : printf("RTC_UNKNOWN_ERROR"); break; case RTC_INVALID_ARGUMENT : printf("RTC_INVALID_ARGUMENT"); break; case RTC_INVALID_OPERATION: printf("RTC_INVALID_OPERATION"); break; case RTC_OUT_OF_MEMORY : printf("RTC_OUT_OF_MEMORY"); break; case RTC_UNSUPPORTED_CPU : printf("RTC_UNSUPPORTED_CPU"); break; default : printf("invalid error code"); break; } if (str) { printf(" ("); while (*str) putchar(*str++); printf(")\n"); } abort(); } size_t sizeOf(const OSPDataType type) { switch (type) { case OSP_VOID_PTR: return sizeof(void *); case OSP_OBJECT: return sizeof(void *); case OSP_DATA: return sizeof(void *); case OSP_CHAR: return sizeof(int8); case OSP_UCHAR: return sizeof(uint8); case OSP_UCHAR2: return sizeof(vec2uc); case OSP_UCHAR3: return sizeof(vec3uc); case OSP_UCHAR4: return sizeof(vec4uc); case OSP_INT: return sizeof(int32); case OSP_INT2: return sizeof(vec2i); case OSP_INT3: return sizeof(vec3i); case OSP_INT4: return sizeof(vec4i); case OSP_UINT: return sizeof(uint32); case OSP_UINT2: return sizeof(vec2ui); case OSP_UINT3: return sizeof(vec3ui); case OSP_UINT4: return sizeof(vec4ui); case OSP_LONG: return sizeof(int64); case OSP_LONG2: return sizeof(vec2l); case OSP_LONG3: return sizeof(vec3l); case OSP_LONG4: return sizeof(vec4l); case OSP_ULONG: return sizeof(uint64); case OSP_ULONG2: return sizeof(vec2ul); case OSP_ULONG3: return sizeof(vec3ul); case OSP_ULONG4: return sizeof(vec4ul); case OSP_FLOAT: return sizeof(float); case OSP_FLOAT2: return sizeof(vec2f); case OSP_FLOAT3: return sizeof(vec3f); case OSP_FLOAT4: return sizeof(vec4f); case OSP_FLOAT3A: return sizeof(vec3fa); case OSP_DOUBLE: return sizeof(double); default: break; }; std::stringstream error; error << __FILE__ << ":" << __LINE__ << ": unknown OSPDataType " << (int)type; throw std::runtime_error(error.str()); } OSPDataType typeForString(const char *string) { if (string == NULL) return(OSP_UNKNOWN); if (strcmp(string, "char" ) == 0) return(OSP_CHAR); if (strcmp(string, "double") == 0) return(OSP_DOUBLE); if (strcmp(string, "float" ) == 0) return(OSP_FLOAT); if (strcmp(string, "float2") == 0) return(OSP_FLOAT2); if (strcmp(string, "float3") == 0) return(OSP_FLOAT2); if (strcmp(string, "float4") == 0) return(OSP_FLOAT2); if (strcmp(string, "int" ) == 0) return(OSP_INT); if (strcmp(string, "int2" ) == 0) return(OSP_INT2); if (strcmp(string, "int3" ) == 0) return(OSP_INT3); if (strcmp(string, "int4" ) == 0) return(OSP_INT4); if (strcmp(string, "uchar" ) == 0) return(OSP_UCHAR); if (strcmp(string, "uchar2") == 0) return(OSP_UCHAR2); if (strcmp(string, "uchar3") == 0) return(OSP_UCHAR3); if (strcmp(string, "uchar4") == 0) return(OSP_UCHAR4); if (strcmp(string, "uint" ) == 0) return(OSP_UINT); if (strcmp(string, "uint2" ) == 0) return(OSP_UINT2); if (strcmp(string, "uint3" ) == 0) return(OSP_UINT3); if (strcmp(string, "uint4" ) == 0) return(OSP_UINT4); return(OSP_UNKNOWN); } size_t sizeOf(const OSPTextureFormat type) { switch (type) { case OSP_TEXTURE_RGBA8: case OSP_TEXTURE_SRGBA: return sizeof(uint32); case OSP_TEXTURE_RGBA32F: return sizeof(vec4f); case OSP_TEXTURE_RGB8: case OSP_TEXTURE_SRGB: return sizeof(vec3uc); case OSP_TEXTURE_RGB32F: return sizeof(vec3f); case OSP_TEXTURE_R8: return sizeof(uint8); case OSP_TEXTURE_R32F: return sizeof(float); } std::stringstream error; error << __FILE__ << ":" << __LINE__ << ": unknown OSPTextureFormat " << (int)type; throw std::runtime_error(error.str()); } } // ::ospray <|endoftext|>
<commit_before>#include "TextField.hpp" #include <Engine/Geometry/Rectangle.hpp> #include <Engine/Font/Font.hpp> #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/ResourceManager.hpp> #include <Engine/Util/Input.hpp> #include <Engine/Physics/Rectangle.hpp> using namespace GUI; TextField::TextField(Widget *parent, Font* font) : Widget(parent) { rectangle = Managers().resourceManager->CreateRectangle(); this->font = font; } TextField::~TextField() { Managers().resourceManager->FreeRectangle(); } void TextField::Update() { if (Input()->Triggered(InputHandler::CLICK)) { glm::vec2 mousePosition(Input()->CursorX(), Input()->CursorY()); Physics::Rectangle rect(GetPosition(), size); focus = rect.Collide(mousePosition); markerPosition = text.length(); } if (focus) { bool textUpdated = !Input()->Text().empty(); text = text.insert(markerPosition, Input()->Text()); markerPosition += Input()->Text().length(); // Erase previous character when BACK pressed. if (Input()->Triggered(InputHandler::BACK) && markerPosition > 0U) { text = text.erase(markerPosition-1, 1); --markerPosition; textUpdated = true; } // Erase next character when ERASE pressed. if (Input()->Triggered(InputHandler::ERASE) && markerPosition < text.length()) { text = text.erase(markerPosition, 1); textUpdated = true; } // Move marker. if (Input()->Triggered(InputHandler::LEFT) && markerPosition > 0U) --markerPosition; if (Input()->Triggered(InputHandler::RIGHT) && markerPosition < text.length()) ++markerPosition; if (Input()->Triggered(InputHandler::HOME)) markerPosition = 0U; if (Input()->Triggered(InputHandler::END)) markerPosition = text.length(); if (textUpdated) TextUpdated(); } } void TextField::Render(const glm::vec2& screenSize) { glm::vec3 color(0.16078431372f, 0.15686274509f, 0.17647058823f); rectangle->Render(GetPosition(), size, color, screenSize); font->SetColor(glm::vec3(1.f, 1.f, 1.f)); font->RenderText(text.c_str(), GetPosition(), size.x, screenSize); if (focus) rectangle->Render(GetPosition() + glm::vec2(font->GetWidth(text.substr(0, markerPosition).c_str()), 0.f), glm::vec2(1, size.y), glm::vec3(1.f, 1.f, 1.f), screenSize); } glm::vec2 TextField::GetSize() const { return size; } void TextField::SetSize(const glm::vec2& size) { this->size = size; } std::string TextField::GetText() const { return text; } void TextField::SetText(const std::string& text) { this->text = text; } void TextField::TextUpdated() { } <commit_msg>Click to select position in text.<commit_after>#include "TextField.hpp" #include <Engine/Geometry/Rectangle.hpp> #include <Engine/Font/Font.hpp> #include <Engine/Manager/Managers.hpp> #include <Engine/Manager/ResourceManager.hpp> #include <Engine/Util/Input.hpp> #include <Engine/Physics/Rectangle.hpp> using namespace GUI; TextField::TextField(Widget *parent, Font* font) : Widget(parent) { rectangle = Managers().resourceManager->CreateRectangle(); this->font = font; } TextField::~TextField() { Managers().resourceManager->FreeRectangle(); } void TextField::Update() { if (Input()->Triggered(InputHandler::CLICK)) { glm::vec2 mousePosition(Input()->CursorX(), Input()->CursorY()); Physics::Rectangle rect(GetPosition(), size); focus = rect.Collide(mousePosition); if (focus) { markerPosition = text.length(); for (std::size_t i = markerPosition; i > 0U; --i) { if (mousePosition.x < GetPosition().x + font->GetWidth(text.substr(0, i).c_str())) markerPosition = i - 1U; } } } if (focus) { bool textUpdated = !Input()->Text().empty(); text = text.insert(markerPosition, Input()->Text()); markerPosition += Input()->Text().length(); // Erase previous character when BACK pressed. if (Input()->Triggered(InputHandler::BACK) && markerPosition > 0U) { text = text.erase(markerPosition-1, 1); --markerPosition; textUpdated = true; } // Erase next character when ERASE pressed. if (Input()->Triggered(InputHandler::ERASE) && markerPosition < text.length()) { text = text.erase(markerPosition, 1); textUpdated = true; } // Move marker. if (Input()->Triggered(InputHandler::LEFT) && markerPosition > 0U) --markerPosition; if (Input()->Triggered(InputHandler::RIGHT) && markerPosition < text.length()) ++markerPosition; if (Input()->Triggered(InputHandler::HOME)) markerPosition = 0U; if (Input()->Triggered(InputHandler::END)) markerPosition = text.length(); if (textUpdated) TextUpdated(); } } void TextField::Render(const glm::vec2& screenSize) { glm::vec3 color(0.16078431372f, 0.15686274509f, 0.17647058823f); rectangle->Render(GetPosition(), size, color, screenSize); font->SetColor(glm::vec3(1.f, 1.f, 1.f)); font->RenderText(text.c_str(), GetPosition(), size.x, screenSize); if (focus) rectangle->Render(GetPosition() + glm::vec2(font->GetWidth(text.substr(0, markerPosition).c_str()), 0.f), glm::vec2(1, size.y), glm::vec3(1.f, 1.f, 1.f), screenSize); } glm::vec2 TextField::GetSize() const { return size; } void TextField::SetSize(const glm::vec2& size) { this->size = size; } std::string TextField::GetText() const { return text; } void TextField::SetText(const std::string& text) { this->text = text; } void TextField::TextUpdated() { } <|endoftext|>
<commit_before>#ifndef TESTS_SAMPLE_PROBLEM_HPP #define TESTS_SAMPLE_PROBLEM_HPP // Generates matrix for poisson problem in a unit cube. template <typename real, typename index> int sample_problem( ptrdiff_t n, std::vector<real> &val, std::vector<index> &col, std::vector<index> &ptr, std::vector<real> &rhs ) { ptrdiff_t n3 = n * n * n; ptr.clear(); col.clear(); val.clear(); rhs.clear(); ptr.reserve(n3 + 1); col.reserve(n3 * 7); val.reserve(n3 * 7); rhs.reserve(n3); ptr.push_back(0); for(ptrdiff_t k = 0, idx = 0; k < n; ++k) { for(ptrdiff_t j = 0; j < n; ++j) { for (ptrdiff_t i = 0; i < n; ++i, ++idx) { if (k > 0) { col.push_back(idx - n * n); val.push_back(-1.0/6.0); } if (j > 0) { col.push_back(idx - n); val.push_back(-1.0/6.0); } if (i > 0) { col.push_back(idx - 1); val.push_back(-1.0/6.0); } col.push_back(idx); val.push_back(1.0); if (i + 1 < n) { col.push_back(idx + 1); val.push_back(-1.0/6.0); } if (j + 1 < n) { col.push_back(idx + n); val.push_back(-1.0/6.0); } if (k + 1 < n) { col.push_back(idx + n * n); val.push_back(-1.0/6.0); } rhs.push_back(1); ptr.push_back( static_cast<index>(col.size()) ); } } } return n3; } #endif <commit_msg>Allow generation of complex-valued sample problems<commit_after>#ifndef TESTS_SAMPLE_PROBLEM_HPP #define TESTS_SAMPLE_PROBLEM_HPP #include <complex> #include <boost/type_traits.hpp> template <typename real> struct make_one { static real get() { return static_cast<real>(1); } }; template <typename real> struct make_one< std::complex<real> > { static std::complex<real> get() { return std::complex<real>(make_one<real>::get(), make_one<real>::get()); } }; // Generates matrix for poisson problem in a unit cube. template <typename real, typename index> int sample_problem( ptrdiff_t n, std::vector<real> &val, std::vector<index> &col, std::vector<index> &ptr, std::vector<real> &rhs ) { ptrdiff_t n3 = n * n * n; ptr.clear(); col.clear(); val.clear(); rhs.clear(); ptr.reserve(n3 + 1); col.reserve(n3 * 7); val.reserve(n3 * 7); rhs.reserve(n3); real one = make_one<real>::get(); ptr.push_back(0); for(ptrdiff_t k = 0, idx = 0; k < n; ++k) { for(ptrdiff_t j = 0; j < n; ++j) { for (ptrdiff_t i = 0; i < n; ++i, ++idx) { if (k > 0) { col.push_back(idx - n * n); val.push_back(-1.0/6.0 * one); } if (j > 0) { col.push_back(idx - n); val.push_back(-1.0/6.0 * one); } if (i > 0) { col.push_back(idx - 1); val.push_back(-1.0/6.0 * one); } col.push_back(idx); val.push_back(1.0); if (i + 1 < n) { col.push_back(idx + 1); val.push_back(-1.0/6.0 * one); } if (j + 1 < n) { col.push_back(idx + n); val.push_back(-1.0/6.0 * one); } if (k + 1 < n) { col.push_back(idx + n * n); val.push_back(-1.0/6.0 * one); } rhs.push_back( one ); ptr.push_back( static_cast<index>(col.size()) ); } } } return n3; } #endif <|endoftext|>
<commit_before>#pragma once #include <glm/vec3.hpp> #include <memory> #include "../linking.hpp" class btCollisionShape; class PhysicsManager; namespace Physics { class Trigger; /// Represents a shape for physics objects and facilitates creation of /// underlying types. class Shape { friend class ::PhysicsManager; friend class Trigger; public: /// Parameters used to create a sphere shape. struct Sphere { Sphere(float radius) : radius(radius) {} float radius; }; /// Parameters used to create a plane shape. struct Plane { Plane(const glm::vec3& normal, float planeCoeff) : normal(normal), planeCoeff(planeCoeff) {} glm::vec3 normal; float planeCoeff; }; /// Parameters used to create a box shape. struct Box { Box(float width, float height, float depth) : width(width), height(height), depth(depth) {} float width; float height; float depth; }; /// Parameters used to create a cylinder shape. struct Cylinder { Cylinder(float radius, float length) : radius(radius), length(length) {} float radius; float length; }; /// Parameters used to create a cone shape. struct Cone { Cone(float radius, float height) : radius(radius), height(height) {} float radius; float height; }; /// Parameters used to create a capsule shape. struct Capsule { Capsule(float radius, float height) : radius(radius), height(height) {} float radius; float height; }; /// The various kinds of shapes that are wrapped by %Shape. enum class Kind { Sphere, Plane, Box, Cylinder, Cone, Capsule, }; /// Construct a sphere shape. /** * @param params Sphere specific parameters. */ ENGINE_API explicit Shape(const Sphere& params); /// Construct a plane shape. /** * @param params Plane specific parameters. */ ENGINE_API explicit Shape(const Plane& params); /// Construct a box shape. /** * @param params Box specific parameters. */ ENGINE_API explicit Shape(const Box& params); /// Construct a cylinder shape. /** * @param params Cylinder specific parameters. */ ENGINE_API explicit Shape(const Cylinder& params); /// Construct a cone shape. /** * @param params Cone specific parameters. */ ENGINE_API explicit Shape(const Cone& params); /// Construct a capsule shape. /** * @param params Capsule specific parameters. */ ENGINE_API explicit Shape(const Capsule& params); /// Destructor ENGINE_API ~Shape(); /// Get the type of wrapped shape. /** * @return The type of shape. */ ENGINE_API Kind GetKind() const; /// Get sphere data of the shape. /** * @return Sphere data, or nullptr if the shape is not a sphere. */ ENGINE_API const Sphere* GetSphereData() const; /// Get plane data of the shape. /** * @return Plane data, or nullptr if the shape is not a plane. */ ENGINE_API const Plane* GetPlaneData() const; /// Get box data of the shape. /** * @return Box data, or nullptr if the shape is not a box. */ ENGINE_API const Box* GetBoxData() const; /// Get cylinder data of the shape. /** * @return Cylinder data, or nullptr if the shape is not a cylinder. */ ENGINE_API const Cylinder* GetCylinderData() const; /// Get cone data of the shape. /** * @return Cone data, or nullptr if the shape is not a cone. */ ENGINE_API const Cone* GetConeData() const; /// Get capsule data of the shape. /** * @return Capsule data, or nullptr if the shape is not a capsule. */ ENGINE_API const Capsule* GetCapsuleData() const; private: /// Get the wrapped Bullet shape. /** * @return The Bullet shape. */ btCollisionShape* GetShape() const; Shape(const Shape& other) = delete; std::unique_ptr<btCollisionShape> shape; Kind kind; union { Sphere sphere; Plane plane; Box box; Cylinder cylinder; Cone cone; Capsule capsule; }; }; } <commit_msg>Code Sniffing, major<commit_after>#pragma once #include <glm/vec3.hpp> #include <memory> #include "../linking.hpp" class btCollisionShape; class PhysicsManager; namespace Physics { class Trigger; /// Represents a shape for physics objects and facilitates creation of /// underlying types. class Shape { friend class ::PhysicsManager; friend class Trigger; public: /// Parameters used to create a sphere shape. struct Sphere { explicit Sphere(float radius) : radius(radius) {} float radius; }; /// Parameters used to create a plane shape. struct Plane { Plane(const glm::vec3& normal, float planeCoeff) : normal(normal), planeCoeff(planeCoeff) {} glm::vec3 normal; float planeCoeff; }; /// Parameters used to create a box shape. struct Box { Box(float width, float height, float depth) : width(width), height(height), depth(depth) {} float width; float height; float depth; }; /// Parameters used to create a cylinder shape. struct Cylinder { Cylinder(float radius, float length) : radius(radius), length(length) {} float radius; float length; }; /// Parameters used to create a cone shape. struct Cone { Cone(float radius, float height) : radius(radius), height(height) {} float radius; float height; }; /// Parameters used to create a capsule shape. struct Capsule { Capsule(float radius, float height) : radius(radius), height(height) {} float radius; float height; }; /// The various kinds of shapes that are wrapped by %Shape. enum class Kind { Sphere, Plane, Box, Cylinder, Cone, Capsule, }; /// Construct a sphere shape. /** * @param params Sphere specific parameters. */ ENGINE_API explicit Shape(const Sphere& params); /// Construct a plane shape. /** * @param params Plane specific parameters. */ ENGINE_API explicit Shape(const Plane& params); /// Construct a box shape. /** * @param params Box specific parameters. */ ENGINE_API explicit Shape(const Box& params); /// Construct a cylinder shape. /** * @param params Cylinder specific parameters. */ ENGINE_API explicit Shape(const Cylinder& params); /// Construct a cone shape. /** * @param params Cone specific parameters. */ ENGINE_API explicit Shape(const Cone& params); /// Construct a capsule shape. /** * @param params Capsule specific parameters. */ ENGINE_API explicit Shape(const Capsule& params); /// Destructor ENGINE_API ~Shape(); /// Get the type of wrapped shape. /** * @return The type of shape. */ ENGINE_API Kind GetKind() const; /// Get sphere data of the shape. /** * @return Sphere data, or nullptr if the shape is not a sphere. */ ENGINE_API const Sphere* GetSphereData() const; /// Get plane data of the shape. /** * @return Plane data, or nullptr if the shape is not a plane. */ ENGINE_API const Plane* GetPlaneData() const; /// Get box data of the shape. /** * @return Box data, or nullptr if the shape is not a box. */ ENGINE_API const Box* GetBoxData() const; /// Get cylinder data of the shape. /** * @return Cylinder data, or nullptr if the shape is not a cylinder. */ ENGINE_API const Cylinder* GetCylinderData() const; /// Get cone data of the shape. /** * @return Cone data, or nullptr if the shape is not a cone. */ ENGINE_API const Cone* GetConeData() const; /// Get capsule data of the shape. /** * @return Capsule data, or nullptr if the shape is not a capsule. */ ENGINE_API const Capsule* GetCapsuleData() const; private: /// Get the wrapped Bullet shape. /** * @return The Bullet shape. */ btCollisionShape* GetShape() const; Shape(const Shape& other) = delete; std::unique_ptr<btCollisionShape> shape; Kind kind; union { Sphere sphere; Plane plane; Box box; Cylinder cylinder; Cone cone; Capsule capsule; }; }; } <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2019, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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 "GafferScene/Deformer.h" #include "GafferScene/SceneAlgo.h" using namespace Imath; using namespace IECore; using namespace Gaffer; using namespace GafferScene; GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( Deformer ); size_t Deformer::g_firstPlugIndex = 0; Deformer::Deformer( const std::string &name ) : ObjectProcessor( name ) { init(); } Deformer::Deformer( const std::string &name, size_t minInputs, size_t maxInputs ) : ObjectProcessor( name, minInputs, maxInputs ) { init(); } Deformer::Deformer( const std::string &name, IECore::PathMatcher::Result filterDefault ) : ObjectProcessor( name, filterDefault ) { init(); } void Deformer::init() { storeIndexOfNextChild( g_firstPlugIndex ); addChild( new BoolPlug( "adjustBounds", Plug::In, true ) ); // Remove pass-through created by base class outPlug()->boundPlug()->setInput( nullptr ); } Deformer::~Deformer() { } Gaffer::BoolPlug *Deformer::adjustBoundsPlug() { return getChild<BoolPlug>( g_firstPlugIndex ); } const Gaffer::BoolPlug *Deformer::adjustBoundsPlug() const { return getChild<BoolPlug>( g_firstPlugIndex ); } void Deformer::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const { ObjectProcessor::affects( input, outputs ); if( input == outPlug()->objectPlug() || input == inPlug()->boundPlug() || input == adjustBoundsPlug() ) { outputs.push_back( outPlug()->boundPlug() ); } } bool Deformer::adjustBounds() const { return adjustBoundsPlug()->getValue(); } void Deformer::hashBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const { if( adjustBounds() ) { const PathMatcher::Result m = filterValue( context ); if( m & ( PathMatcher::ExactMatch | PathMatcher::DescendantMatch ) ) { ObjectProcessor::hashBound( path, context, parent, h ); if( m & PathMatcher::ExactMatch ) { outPlug()->objectPlug()->hash( h ); } else { inPlug()->objectPlug()->hash( h ); } if( m & PathMatcher::DescendantMatch ) { h.append( hashOfTransformedChildBounds( path, outPlug() ) ); } else { h.append( hashOfTransformedChildBounds( path, inPlug() ) ); } return; } // Fall through to pass-through } h = inPlug()->boundPlug()->hash(); } Imath::Box3f Deformer::computeBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const { if( adjustBounds() ) { const PathMatcher::Result m = filterValue( context ); if( m & ( PathMatcher::ExactMatch | PathMatcher::DescendantMatch ) ) { // Need to compute new bounds. This consists of the bounds of // the (potentially deformed) object at this location and the // (potentially deformed) bounds of our children. Box3f result; if( m & PathMatcher::ExactMatch ) { // Get bounds from deformed output object. /// \todo Some derived classes may be able to compute an output bound /// for the object without computing the full deformation. We could add /// virtual methods to allow that. result.extendBy( SceneAlgo::bound( outPlug()->objectPlug()->getValue().get() ) ); } else { result.extendBy( SceneAlgo::bound( inPlug()->objectPlug()->getValue().get() ) ); } if( m & PathMatcher::DescendantMatch ) { result.extendBy( unionOfTransformedChildBounds( path, outPlug() ) ); } else { result.extendBy( unionOfTransformedChildBounds( path, inPlug() ) ); } return result; } // Fall through to pass-through } return inPlug()->boundPlug()->getValue(); } <commit_msg>Deformer : Use GlobalScope to evaluate `adjustBounds()`<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2019, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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 "GafferScene/Deformer.h" #include "GafferScene/SceneAlgo.h" using namespace Imath; using namespace IECore; using namespace Gaffer; using namespace GafferScene; GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( Deformer ); size_t Deformer::g_firstPlugIndex = 0; Deformer::Deformer( const std::string &name ) : ObjectProcessor( name ) { init(); } Deformer::Deformer( const std::string &name, size_t minInputs, size_t maxInputs ) : ObjectProcessor( name, minInputs, maxInputs ) { init(); } Deformer::Deformer( const std::string &name, IECore::PathMatcher::Result filterDefault ) : ObjectProcessor( name, filterDefault ) { init(); } void Deformer::init() { storeIndexOfNextChild( g_firstPlugIndex ); addChild( new BoolPlug( "adjustBounds", Plug::In, true ) ); // Remove pass-through created by base class outPlug()->boundPlug()->setInput( nullptr ); } Deformer::~Deformer() { } Gaffer::BoolPlug *Deformer::adjustBoundsPlug() { return getChild<BoolPlug>( g_firstPlugIndex ); } const Gaffer::BoolPlug *Deformer::adjustBoundsPlug() const { return getChild<BoolPlug>( g_firstPlugIndex ); } void Deformer::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const { ObjectProcessor::affects( input, outputs ); if( input == outPlug()->objectPlug() || input == inPlug()->boundPlug() || input == adjustBoundsPlug() ) { outputs.push_back( outPlug()->boundPlug() ); } } bool Deformer::adjustBounds() const { return adjustBoundsPlug()->getValue(); } void Deformer::hashBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent, IECore::MurmurHash &h ) const { bool adjustBounds; { ScenePlug::GlobalScope globalScope( context ); adjustBounds = this->adjustBounds(); } if( adjustBounds ) { const PathMatcher::Result m = filterValue( context ); if( m & ( PathMatcher::ExactMatch | PathMatcher::DescendantMatch ) ) { ObjectProcessor::hashBound( path, context, parent, h ); if( m & PathMatcher::ExactMatch ) { outPlug()->objectPlug()->hash( h ); } else { inPlug()->objectPlug()->hash( h ); } if( m & PathMatcher::DescendantMatch ) { h.append( hashOfTransformedChildBounds( path, outPlug() ) ); } else { h.append( hashOfTransformedChildBounds( path, inPlug() ) ); } return; } // Fall through to pass-through } h = inPlug()->boundPlug()->hash(); } Imath::Box3f Deformer::computeBound( const ScenePath &path, const Gaffer::Context *context, const ScenePlug *parent ) const { bool adjustBounds; { // We can't allow the result of `adjustBounds()` to vary per location, // because that would prevent us from successfully propagating bounds // changes up to ancestor locations. To enforce this, we evaluate // `adjustBounds()` in a global scope. ScenePlug::GlobalScope globalScope( context ); adjustBounds = this->adjustBounds(); } if( adjustBounds ) { const PathMatcher::Result m = filterValue( context ); if( m & ( PathMatcher::ExactMatch | PathMatcher::DescendantMatch ) ) { // Need to compute new bounds. This consists of the bounds of // the (potentially deformed) object at this location and the // (potentially deformed) bounds of our children. Box3f result; if( m & PathMatcher::ExactMatch ) { // Get bounds from deformed output object. /// \todo Some derived classes may be able to compute an output bound /// for the object without computing the full deformation. We could add /// virtual methods to allow that. result.extendBy( SceneAlgo::bound( outPlug()->objectPlug()->getValue().get() ) ); } else { result.extendBy( SceneAlgo::bound( inPlug()->objectPlug()->getValue().get() ) ); } if( m & PathMatcher::DescendantMatch ) { result.extendBy( unionOfTransformedChildBounds( path, outPlug() ) ); } else { result.extendBy( unionOfTransformedChildBounds( path, inPlug() ) ); } return result; } // Fall through to pass-through } return inPlug()->boundPlug()->getValue(); } <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "PlatformWin.h" #include "Framework.h" #if defined(_WINDOWS) namespace Foundation { std::string PlatformWin::GetApplicationDataDirectory() { LPITEMIDLIST pidl; if (SHGetFolderLocation(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, &pidl) == S_OK) { char cpath[MAX_PATH]; SHGetPathFromIDListA( pidl, cpath ); CoTaskMemFree(pidl); return std::string(cpath) + "\\" + framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "application_name"); } throw Core::Exception("Failed to access application data directory."); } std::wstring PlatformWin::GetApplicationDataDirectoryW() { LPITEMIDLIST pidl; if (SHGetFolderLocation(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, &pidl) == S_OK) { wchar_t cpath[MAX_PATH]; SHGetPathFromIDListW( pidl, cpath ); CoTaskMemFree(pidl); return std::wstring(cpath) + L"\\" + Core::ToWString(framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "application_name")); } throw Core::Exception("Failed to access application data directory."); } std::string PlatformWin::GetUserDocumentsDirectory() { LPITEMIDLIST pidl; if (SHGetFolderLocation(NULL, CSIDL_PERSONAL | CSIDL_FLAG_CREATE, NULL, 0, &pidl) == S_OK) { char cpath[MAX_PATH]; SHGetPathFromIDListA( pidl, cpath ); CoTaskMemFree(pidl); return std::string(cpath) + "\\" + framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "application_name"); } throw Core::Exception("Failed to access user documents directory."); } std::wstring PlatformWin::GetUserDocumentsDirectoryW() { LPITEMIDLIST pidl; int res = SHGetFolderLocation(NULL, CSIDL_PERSONAL | CSIDL_FLAG_CREATE, NULL, 0, &pidl); if (res == S_OK) { wchar_t cpath[MAX_PATH]; SHGetPathFromIDListW( pidl, cpath ); CoTaskMemFree(pidl); return std::wstring(cpath) + L"\\" + Core::ToWString(framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "application_name")); } if (res == E_INVALIDARG) throw Core::Exception("Failed to access user documents directory."); else throw Core::Exception("Failed to access user documents directory."); } } #endif <commit_msg>Cleaned up code.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "PlatformWin.h" #include "Framework.h" #if defined(_WINDOWS) namespace Foundation { std::string PlatformWin::GetApplicationDataDirectory() { LPITEMIDLIST pidl; if (SHGetFolderLocation(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, &pidl) == S_OK) { char cpath[MAX_PATH]; SHGetPathFromIDListA( pidl, cpath ); CoTaskMemFree(pidl); return std::string(cpath) + "\\" + framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "application_name"); } throw Core::Exception("Failed to access application data directory."); } std::wstring PlatformWin::GetApplicationDataDirectoryW() { LPITEMIDLIST pidl; if (SHGetFolderLocation(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, &pidl) == S_OK) { wchar_t cpath[MAX_PATH]; SHGetPathFromIDListW( pidl, cpath ); CoTaskMemFree(pidl); return std::wstring(cpath) + L"\\" + Core::ToWString(framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "application_name")); } throw Core::Exception("Failed to access application data directory."); } std::string PlatformWin::GetUserDocumentsDirectory() { LPITEMIDLIST pidl; if (SHGetFolderLocation(NULL, CSIDL_PERSONAL | CSIDL_FLAG_CREATE, NULL, 0, &pidl) == S_OK) { char cpath[MAX_PATH]; SHGetPathFromIDListA( pidl, cpath ); CoTaskMemFree(pidl); return std::string(cpath) + "\\" + framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "application_name"); } throw Core::Exception("Failed to access user documents directory."); } std::wstring PlatformWin::GetUserDocumentsDirectoryW() { LPITEMIDLIST pidl; if (SHGetFolderLocation(NULL, CSIDL_PERSONAL | CSIDL_FLAG_CREATE, NULL, 0, &pidl) == S_OK) { wchar_t cpath[MAX_PATH]; SHGetPathFromIDListW( pidl, cpath ); CoTaskMemFree(pidl); return std::wstring(cpath) + L"\\" + Core::ToWString(framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "application_name")); } throw Core::Exception("Failed to access user documents directory."); } } #endif <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include <sys/stat.h> #include "CompileConfig.h" #if defined(OUZEL_PLATFORM_OSX) #include <sys/types.h> #include <pwd.h> #include <CoreServices/CoreServices.h> #elif defined(OUZEL_PLATFORM_WINDOWS) #include <Shlobj.h> #include <Windows.h> #elif defined(OUZEL_PLATFORM_LINUX) #include <unistd.h> #endif #include "FileSystem.h" #include "Utils.h" #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) #include <CoreFoundation/CoreFoundation.h> #endif namespace ouzel { #ifdef OUZEL_PLATFORM_WINDOWS const std::string FileSystem::DIRECTORY_SEPARATOR = "\\"; #else const std::string FileSystem::DIRECTORY_SEPARATOR = "/"; #endif FileSystem::FileSystem() { } FileSystem::~FileSystem() { } std::string FileSystem::getHomeDirectory() { #if defined(OUZEL_PLATFORM_OSX) struct passwd* pw = getpwuid(getuid()); if (pw) { return pw->pw_dir; } #elif defined(OUZEL_PLATFORM_WINDOWS) WCHAR szBuffer[MAX_PATH]; if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, szBuffer))) { WideCharToMultiByte(CP_UTF8, 0, szBuffer, -1, TEMP_BUFFER, sizeof(TEMP_BUFFER), nullptr, nullptr); return TEMP_BUFFER; } #elif defined(OUZEL_PLATFORM_LINUX) //TODO: implement #endif return ""; } std::string FileSystem::getStorageDirectory(const std::string& developer, const std::string& app) { std::string path; #if defined(OUZEL_PLATFORM_OSX) OUZEL_UNUSED(developer); OUZEL_UNUSED(app); FSRef ref; OSType folderType = kApplicationSupportFolderType; FSFindFolder( kUserDomain, folderType, kCreateFolder, &ref ); FSRefMakePath(&ref, reinterpret_cast<UInt8*>(&TEMP_BUFFER), sizeof(TEMP_BUFFER)); path = TEMP_BUFFER; CFStringRef bundleIdentifier = CFBundleGetIdentifier(CFBundleGetMainBundle()); CFStringGetCString(bundleIdentifier, TEMP_BUFFER, sizeof(TEMP_BUFFER), kCFStringEncodingUTF8); path += DIRECTORY_SEPARATOR + TEMP_BUFFER; if (!directoryExists(path)) { mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); } #elif defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) OUZEL_UNUSED(developer); OUZEL_UNUSED(app); //TODO: implement #elif defined(OUZEL_PLATFORM_WINDOWS) WCHAR szBuffer[MAX_PATH]; if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szBuffer))) { WideCharToMultiByte(CP_UTF8, 0, szBuffer, -1, TEMP_BUFFER, sizeof(TEMP_BUFFER), nullptr, nullptr); path = TEMP_BUFFER; } path += DIRECTORY_SEPARATOR + developer; if (!directoryExists(path)) { MultiByteToWideChar(CP_ACP, 0, path.c_str(), -1, szBuffer, MAX_PATH); CreateDirectory(szBuffer, NULL); } path += DIRECTORY_SEPARATOR + app; if (!directoryExists(path)) { MultiByteToWideChar(CP_ACP, 0, path.c_str(), -1, szBuffer, MAX_PATH); CreateDirectory(szBuffer, NULL); } #elif defined(OUZEL_PLATFORM_ANDROID) OUZEL_UNUSED(developer); OUZEL_UNUSED(app); //TODO: implement #elif defined(OUZEL_PLATFORM_LINUX) OUZEL_UNUSED(developer); OUZEL_UNUSED(app); //TODO: implement #endif return path; } bool FileSystem::directoryExists(const std::string& filename) const { struct stat buf; if (stat(filename.c_str(), &buf) != 0) { return false; } return (buf.st_mode & S_IFMT) == S_IFDIR; } bool FileSystem::fileExists(const std::string& filename) const { struct stat buf; if (stat(filename.c_str(), &buf) != 0) { return false; } return (buf.st_mode & S_IFMT) == S_IFREG; } std::string FileSystem::getPath(const std::string& filename) const { std::string appPath; #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) CFURLRef resourcesUrlRef = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle()); CFURLRef absoluteURL = CFURLCopyAbsoluteURL(resourcesUrlRef); CFStringRef urlString = CFURLCopyFileSystemPath(absoluteURL, kCFURLPOSIXPathStyle); CFStringGetCString(urlString, TEMP_BUFFER, sizeof(TEMP_BUFFER), kCFStringEncodingUTF8); CFRelease(resourcesUrlRef); CFRelease(absoluteURL); CFRelease(urlString); appPath = std::string(TEMP_BUFFER); #elif defined(OUZEL_PLATFORM_WINDOWS) wchar_t szBuffer[MAX_PATH]; if (!GetCurrentDirectoryW(MAX_PATH, szBuffer)) { log("Failed to get current directory"); return false; } WideCharToMultiByte(CP_ACP, 0, szBuffer, -1, TEMP_BUFFER, sizeof(TEMP_BUFFER), nullptr, nullptr); appPath = std::string(TEMP_BUFFER); #elif defined(OUZEL_PLATFORM_LINUX) if (!getcwd(TEMP_BUFFER, sizeof(TEMP_BUFFER))) { log("Failed to get current directory"); return false; } appPath = std::string(TEMP_BUFFER); #endif std::string str = appPath + DIRECTORY_SEPARATOR + filename; if (fileExists(str)) { return str; } else { for (const std::string& path : resourcePaths) { str = appPath + DIRECTORY_SEPARATOR + path + DIRECTORY_SEPARATOR + filename; if (fileExists(str)) { return str; } } } return ""; } void FileSystem::addResourcePath(const std::string& path) { std::vector<std::string>::iterator i = std::find(resourcePaths.begin(), resourcePaths.end(), path); if (i == resourcePaths.end()) { resourcePaths.push_back(path); } } std::string FileSystem::getExtension(const std::string& path) const { std::string result; size_t pos = path.find_last_of('.'); if (pos != std::string::npos) { result = path.substr(pos + 1); } return result; } } <commit_msg>Return empty string from getPath instead of false<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include <sys/stat.h> #include "CompileConfig.h" #if defined(OUZEL_PLATFORM_OSX) #include <sys/types.h> #include <pwd.h> #include <CoreServices/CoreServices.h> #elif defined(OUZEL_PLATFORM_WINDOWS) #include <Shlobj.h> #include <Windows.h> #elif defined(OUZEL_PLATFORM_LINUX) #include <unistd.h> #endif #include "FileSystem.h" #include "Utils.h" #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) #include <CoreFoundation/CoreFoundation.h> #endif namespace ouzel { #ifdef OUZEL_PLATFORM_WINDOWS const std::string FileSystem::DIRECTORY_SEPARATOR = "\\"; #else const std::string FileSystem::DIRECTORY_SEPARATOR = "/"; #endif FileSystem::FileSystem() { } FileSystem::~FileSystem() { } std::string FileSystem::getHomeDirectory() { #if defined(OUZEL_PLATFORM_OSX) struct passwd* pw = getpwuid(getuid()); if (pw) { return pw->pw_dir; } #elif defined(OUZEL_PLATFORM_WINDOWS) WCHAR szBuffer[MAX_PATH]; if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, szBuffer))) { WideCharToMultiByte(CP_UTF8, 0, szBuffer, -1, TEMP_BUFFER, sizeof(TEMP_BUFFER), nullptr, nullptr); return TEMP_BUFFER; } #elif defined(OUZEL_PLATFORM_LINUX) //TODO: implement #endif return ""; } std::string FileSystem::getStorageDirectory(const std::string& developer, const std::string& app) { std::string path; #if defined(OUZEL_PLATFORM_OSX) OUZEL_UNUSED(developer); OUZEL_UNUSED(app); FSRef ref; OSType folderType = kApplicationSupportFolderType; FSFindFolder( kUserDomain, folderType, kCreateFolder, &ref ); FSRefMakePath(&ref, reinterpret_cast<UInt8*>(&TEMP_BUFFER), sizeof(TEMP_BUFFER)); path = TEMP_BUFFER; CFStringRef bundleIdentifier = CFBundleGetIdentifier(CFBundleGetMainBundle()); CFStringGetCString(bundleIdentifier, TEMP_BUFFER, sizeof(TEMP_BUFFER), kCFStringEncodingUTF8); path += DIRECTORY_SEPARATOR + TEMP_BUFFER; if (!directoryExists(path)) { mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); } #elif defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) OUZEL_UNUSED(developer); OUZEL_UNUSED(app); //TODO: implement #elif defined(OUZEL_PLATFORM_WINDOWS) WCHAR szBuffer[MAX_PATH]; if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_COMMON_APPDATA, NULL, 0, szBuffer))) { WideCharToMultiByte(CP_UTF8, 0, szBuffer, -1, TEMP_BUFFER, sizeof(TEMP_BUFFER), nullptr, nullptr); path = TEMP_BUFFER; } path += DIRECTORY_SEPARATOR + developer; if (!directoryExists(path)) { MultiByteToWideChar(CP_ACP, 0, path.c_str(), -1, szBuffer, MAX_PATH); CreateDirectory(szBuffer, NULL); } path += DIRECTORY_SEPARATOR + app; if (!directoryExists(path)) { MultiByteToWideChar(CP_ACP, 0, path.c_str(), -1, szBuffer, MAX_PATH); CreateDirectory(szBuffer, NULL); } #elif defined(OUZEL_PLATFORM_ANDROID) OUZEL_UNUSED(developer); OUZEL_UNUSED(app); //TODO: implement #elif defined(OUZEL_PLATFORM_LINUX) OUZEL_UNUSED(developer); OUZEL_UNUSED(app); //TODO: implement #endif return path; } bool FileSystem::directoryExists(const std::string& filename) const { struct stat buf; if (stat(filename.c_str(), &buf) != 0) { return false; } return (buf.st_mode & S_IFMT) == S_IFDIR; } bool FileSystem::fileExists(const std::string& filename) const { struct stat buf; if (stat(filename.c_str(), &buf) != 0) { return false; } return (buf.st_mode & S_IFMT) == S_IFREG; } std::string FileSystem::getPath(const std::string& filename) const { std::string appPath; #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) || defined(OUZEL_PLATFORM_TVOS) CFURLRef resourcesUrlRef = CFBundleCopyResourcesDirectoryURL(CFBundleGetMainBundle()); CFURLRef absoluteURL = CFURLCopyAbsoluteURL(resourcesUrlRef); CFStringRef urlString = CFURLCopyFileSystemPath(absoluteURL, kCFURLPOSIXPathStyle); CFStringGetCString(urlString, TEMP_BUFFER, sizeof(TEMP_BUFFER), kCFStringEncodingUTF8); CFRelease(resourcesUrlRef); CFRelease(absoluteURL); CFRelease(urlString); appPath = std::string(TEMP_BUFFER); #elif defined(OUZEL_PLATFORM_WINDOWS) wchar_t szBuffer[MAX_PATH]; if (!GetCurrentDirectoryW(MAX_PATH, szBuffer)) { log("Failed to get current directory"); return ""; } WideCharToMultiByte(CP_ACP, 0, szBuffer, -1, TEMP_BUFFER, sizeof(TEMP_BUFFER), nullptr, nullptr); appPath = std::string(TEMP_BUFFER); #elif defined(OUZEL_PLATFORM_LINUX) if (!getcwd(TEMP_BUFFER, sizeof(TEMP_BUFFER))) { log("Failed to get current directory"); return ""; } appPath = std::string(TEMP_BUFFER); #endif std::string str = appPath + DIRECTORY_SEPARATOR + filename; if (fileExists(str)) { return str; } else { for (const std::string& path : resourcePaths) { str = appPath + DIRECTORY_SEPARATOR + path + DIRECTORY_SEPARATOR + filename; if (fileExists(str)) { return str; } } } return ""; } void FileSystem::addResourcePath(const std::string& path) { std::vector<std::string>::iterator i = std::find(resourcePaths.begin(), resourcePaths.end(), path); if (i == resourcePaths.end()) { resourcePaths.push_back(path); } } std::string FileSystem::getExtension(const std::string& path) const { std::string result; size_t pos = path.find_last_of('.'); if (pos != std::string::npos) { result = path.substr(pos + 1); } return result; } } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_LINEAR_BVH_DECL_HPP #define DTK_LINEAR_BVH_DECL_HPP #include <Kokkos_ArithTraits.hpp> #include <Kokkos_Array.hpp> #include <Kokkos_View.hpp> #include <DTK_Box.hpp> #include <DTK_DetailsAlgorithms.hpp> #include <DTK_DetailsNode.hpp> #include <DTK_DetailsTreeTraversal.hpp> #include <DTK_DetailsUtils.hpp> #include <DTK_Predicates.hpp> #include "DTK_ConfigDefs.hpp" namespace DataTransferKit { template <typename DeviceType> class BoundingVolumeHierarchy { public: using TreeType = BoundingVolumeHierarchy; BoundingVolumeHierarchy() = default; // build an empty tree BoundingVolumeHierarchy( Kokkos::View<Box const *, DeviceType> bounding_boxes ); // Views are passed by reference here because internally Kokkos::realloc() // is called. template <typename Query> void query( Kokkos::View<Query *, DeviceType> queries, Kokkos::View<int *, DeviceType> &indices, Kokkos::View<int *, DeviceType> &offset ) const; template <typename Query> typename std::enable_if< std::is_same<typename Query::Tag, Details::NearestPredicateTag>::value, void>::type query( Kokkos::View<Query *, DeviceType> queries, Kokkos::View<int *, DeviceType> &indices, Kokkos::View<int *, DeviceType> &offset, Kokkos::View<double *, DeviceType> &distances ) const; KOKKOS_INLINE_FUNCTION Box bounds() const { if ( empty() ) return Box(); return ( size() > 1 ? _internal_nodes : _leaf_nodes )[0].bounding_box; } using SizeType = typename Kokkos::View<int *, DeviceType>::size_type; KOKKOS_INLINE_FUNCTION SizeType size() const { return _leaf_nodes.extent( 0 ); } KOKKOS_INLINE_FUNCTION bool empty() const { return size() == 0; } private: friend struct Details::TreeTraversal<DeviceType>; Kokkos::View<Node *, DeviceType> _leaf_nodes; Kokkos::View<Node *, DeviceType> _internal_nodes; /** * Array of indices that sort the boxes used to construct the hierarchy. * The leaf nodes are ordered so we need these to identify objects that * meet a predicate. */ Kokkos::View<int *, DeviceType> _indices; }; template <typename DeviceType> using BVH = typename BoundingVolumeHierarchy<DeviceType>::TreeType; template <typename DeviceType, typename Query> void queryDispatch( BoundingVolumeHierarchy<DeviceType> const bvh, Kokkos::View<Query *, DeviceType> queries, Kokkos::View<int *, DeviceType> &indices, Kokkos::View<int *, DeviceType> &offset, Details::NearestPredicateTag, Kokkos::View<double *, DeviceType> *distances_ptr = nullptr ) { using ExecutionSpace = typename DeviceType::execution_space; int const n_queries = queries.extent( 0 ); Kokkos::realloc( offset, n_queries + 1 ); Kokkos::deep_copy( offset, 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "scan_queries_for_numbers_of_nearest_neighbors" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int i ) { offset( i ) = queries( i )._k; } ); Kokkos::fence(); exclusivePrefixSum( offset ); int const n_results = lastElement( offset ); Kokkos::realloc( indices, n_results ); int const invalid_index = -1; Kokkos::deep_copy( indices, invalid_index ); if ( distances_ptr ) { Kokkos::View<double *, DeviceType> &distances = *distances_ptr; Kokkos::realloc( distances, n_results ); double const invalid_distance = -Kokkos::ArithTraits<double>::max(); Kokkos::deep_copy( distances, invalid_distance ); Kokkos::parallel_for( DTK_MARK_REGION( "perform_nearest_queries_and_return_distances" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int i ) { int count = 0; Details::TreeTraversal<DeviceType>::query( bvh, queries( i ), [indices, offset, distances, i, &count]( int index, double distance ) { indices( offset( i ) + count ) = index; distances( offset( i ) + count ) = distance; count++; } ); } ); Kokkos::fence(); } else { Kokkos::parallel_for( DTK_MARK_REGION( "perform_nearest_queries" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int i ) { int count = 0; Details::TreeTraversal<DeviceType>::query( bvh, queries( i ), [indices, offset, i, &count]( int index, double ) { indices( offset( i ) + count++ ) = index; } ); } ); Kokkos::fence(); } // Find out if they are any invalid entries in the indices (i.e. at least // one query asked for more neighbors that they are leaves in the tree) and // eliminate them if necessary. auto tmp_offset = Kokkos::create_mirror( DeviceType(), offset ); Kokkos::deep_copy( tmp_offset, 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "count_invalid_indices" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int q ) { for ( int i = offset( q ); i < offset( q + 1 ); ++i ) if ( indices( i ) == invalid_index ) { tmp_offset( q ) = offset( q + 1 ) - i; break; } } ); Kokkos::fence(); exclusivePrefixSum( tmp_offset ); int const n_invalid_indices = lastElement( tmp_offset ); if ( n_invalid_indices > 0 ) { Kokkos::parallel_for( DTK_MARK_REGION( "subtract_invalid_entries_from_offset" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries + 1 ), KOKKOS_LAMBDA( int q ) { tmp_offset( q ) = offset( q ) - tmp_offset( q ); } ); Kokkos::fence(); int const n_valid_indices = n_results - n_invalid_indices; Kokkos::View<int *, DeviceType> tmp_indices( indices.label(), n_valid_indices ); Kokkos::parallel_for( DTK_MARK_REGION( "copy_valid_indices" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int q ) { for ( int i = 0; i < tmp_offset( q + 1 ) - tmp_offset( q ); ++i ) { tmp_indices( tmp_offset( q ) + i ) = indices( offset( q ) + i ); } } ); Kokkos::fence(); indices = tmp_indices; if ( distances_ptr ) { Kokkos::View<double *, DeviceType> &distances = *distances_ptr; Kokkos::View<double *, DeviceType> tmp_distances( distances.label(), n_valid_indices ); Kokkos::parallel_for( DTK_MARK_REGION( "copy_valid_distances" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int q ) { for ( int i = 0; i < tmp_offset( q + 1 ) - tmp_offset( q ); ++i ) { tmp_distances( tmp_offset( q ) + i ) = distances( offset( q ) + i ); } } ); Kokkos::fence(); distances = tmp_distances; } offset = tmp_offset; } } template <typename DeviceType, typename Query> void queryDispatch( BoundingVolumeHierarchy<DeviceType> const bvh, Kokkos::View<Query *, DeviceType> queries, Kokkos::View<int *, DeviceType> &indices, Kokkos::View<int *, DeviceType> &offset, Details::SpatialPredicateTag ) { using ExecutionSpace = typename DeviceType::execution_space; int const n_queries = queries.extent( 0 ); // Initialize view // [ 0 0 0 .... 0 0 ] // ^ // N Kokkos::realloc( offset, n_queries + 1 ); Kokkos::deep_copy( offset, 0 ); // Say we found exactly two object for each query: // [ 2 2 2 .... 2 0 ] // ^ ^ // 0th Nth element in the view Kokkos::parallel_for( DTK_MARK_REGION( "first_pass_at_the_search_count_the_number_of_indices" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int i ) { offset( i ) = Details::TreeTraversal<DeviceType>::query( bvh, queries( i ), []( int ) {} ); } ); Kokkos::fence(); // Then we would get: // [ 0 2 4 .... 2N-2 2N ] // ^ // N exclusivePrefixSum( offset ); // Let us extract the last element in the view which is the total count of // objects which where found to meet the query predicates: // // [ 2N ] int const n_results = lastElement( offset ); // We allocate the memory and fill // // [ A0 A1 B0 B1 C0 C1 ... X0 X1 ] // ^ ^ ^ ^ ^ // 0 2 4 2N-2 2N Kokkos::realloc( indices, n_results ); Kokkos::parallel_for( DTK_MARK_REGION( "second_pass" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int i ) { int count = 0; Details::TreeTraversal<DeviceType>::query( bvh, queries( i ), [indices, offset, i, &count]( int index ) { indices( offset( i ) + count++ ) = index; } ); } ); Kokkos::fence(); } template <typename DeviceType> template <typename Query> void BoundingVolumeHierarchy<DeviceType>::query( Kokkos::View<Query *, DeviceType> queries, Kokkos::View<int *, DeviceType> &indices, Kokkos::View<int *, DeviceType> &offset ) const { using Tag = typename Query::Tag; queryDispatch( *this, queries, indices, offset, Tag{} ); } template <typename DeviceType> template <typename Query> typename std::enable_if< std::is_same<typename Query::Tag, Details::NearestPredicateTag>::value, void>::type BoundingVolumeHierarchy<DeviceType>::query( Kokkos::View<Query *, DeviceType> queries, Kokkos::View<int *, DeviceType> &indices, Kokkos::View<int *, DeviceType> &offset, Kokkos::View<double *, DeviceType> &distances ) const { using Tag = typename Query::Tag; queryDispatch( *this, queries, indices, offset, Tag{}, &distances ); } } // namespace DataTransferKit #endif <commit_msg>Permute order of the #includes blocks in DTK_LinearBVH_decl.hpp<commit_after>/**************************************************************************** * Copyright (c) 2012-2018 by the DataTransferKit authors * * All rights reserved. * * * * This file is part of the DataTransferKit library. DataTransferKit is * * distributed under a BSD 3-clause license. For the licensing terms see * * the LICENSE file in the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef DTK_LINEAR_BVH_DECL_HPP #define DTK_LINEAR_BVH_DECL_HPP #include "DTK_ConfigDefs.hpp" #include <DTK_Box.hpp> #include <DTK_DetailsAlgorithms.hpp> #include <DTK_DetailsNode.hpp> #include <DTK_DetailsTreeTraversal.hpp> #include <DTK_DetailsUtils.hpp> #include <DTK_Predicates.hpp> #include <Kokkos_ArithTraits.hpp> #include <Kokkos_Array.hpp> #include <Kokkos_View.hpp> namespace DataTransferKit { template <typename DeviceType> class BoundingVolumeHierarchy { public: using TreeType = BoundingVolumeHierarchy; BoundingVolumeHierarchy() = default; // build an empty tree BoundingVolumeHierarchy( Kokkos::View<Box const *, DeviceType> bounding_boxes ); // Views are passed by reference here because internally Kokkos::realloc() // is called. template <typename Query> void query( Kokkos::View<Query *, DeviceType> queries, Kokkos::View<int *, DeviceType> &indices, Kokkos::View<int *, DeviceType> &offset ) const; template <typename Query> typename std::enable_if< std::is_same<typename Query::Tag, Details::NearestPredicateTag>::value, void>::type query( Kokkos::View<Query *, DeviceType> queries, Kokkos::View<int *, DeviceType> &indices, Kokkos::View<int *, DeviceType> &offset, Kokkos::View<double *, DeviceType> &distances ) const; KOKKOS_INLINE_FUNCTION Box bounds() const { if ( empty() ) return Box(); return ( size() > 1 ? _internal_nodes : _leaf_nodes )[0].bounding_box; } using SizeType = typename Kokkos::View<int *, DeviceType>::size_type; KOKKOS_INLINE_FUNCTION SizeType size() const { return _leaf_nodes.extent( 0 ); } KOKKOS_INLINE_FUNCTION bool empty() const { return size() == 0; } private: friend struct Details::TreeTraversal<DeviceType>; Kokkos::View<Node *, DeviceType> _leaf_nodes; Kokkos::View<Node *, DeviceType> _internal_nodes; /** * Array of indices that sort the boxes used to construct the hierarchy. * The leaf nodes are ordered so we need these to identify objects that * meet a predicate. */ Kokkos::View<int *, DeviceType> _indices; }; template <typename DeviceType> using BVH = typename BoundingVolumeHierarchy<DeviceType>::TreeType; template <typename DeviceType, typename Query> void queryDispatch( BoundingVolumeHierarchy<DeviceType> const bvh, Kokkos::View<Query *, DeviceType> queries, Kokkos::View<int *, DeviceType> &indices, Kokkos::View<int *, DeviceType> &offset, Details::NearestPredicateTag, Kokkos::View<double *, DeviceType> *distances_ptr = nullptr ) { using ExecutionSpace = typename DeviceType::execution_space; int const n_queries = queries.extent( 0 ); Kokkos::realloc( offset, n_queries + 1 ); Kokkos::deep_copy( offset, 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "scan_queries_for_numbers_of_nearest_neighbors" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int i ) { offset( i ) = queries( i )._k; } ); Kokkos::fence(); exclusivePrefixSum( offset ); int const n_results = lastElement( offset ); Kokkos::realloc( indices, n_results ); int const invalid_index = -1; Kokkos::deep_copy( indices, invalid_index ); if ( distances_ptr ) { Kokkos::View<double *, DeviceType> &distances = *distances_ptr; Kokkos::realloc( distances, n_results ); double const invalid_distance = -Kokkos::ArithTraits<double>::max(); Kokkos::deep_copy( distances, invalid_distance ); Kokkos::parallel_for( DTK_MARK_REGION( "perform_nearest_queries_and_return_distances" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int i ) { int count = 0; Details::TreeTraversal<DeviceType>::query( bvh, queries( i ), [indices, offset, distances, i, &count]( int index, double distance ) { indices( offset( i ) + count ) = index; distances( offset( i ) + count ) = distance; count++; } ); } ); Kokkos::fence(); } else { Kokkos::parallel_for( DTK_MARK_REGION( "perform_nearest_queries" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int i ) { int count = 0; Details::TreeTraversal<DeviceType>::query( bvh, queries( i ), [indices, offset, i, &count]( int index, double ) { indices( offset( i ) + count++ ) = index; } ); } ); Kokkos::fence(); } // Find out if they are any invalid entries in the indices (i.e. at least // one query asked for more neighbors that they are leaves in the tree) and // eliminate them if necessary. auto tmp_offset = Kokkos::create_mirror( DeviceType(), offset ); Kokkos::deep_copy( tmp_offset, 0 ); Kokkos::parallel_for( DTK_MARK_REGION( "count_invalid_indices" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int q ) { for ( int i = offset( q ); i < offset( q + 1 ); ++i ) if ( indices( i ) == invalid_index ) { tmp_offset( q ) = offset( q + 1 ) - i; break; } } ); Kokkos::fence(); exclusivePrefixSum( tmp_offset ); int const n_invalid_indices = lastElement( tmp_offset ); if ( n_invalid_indices > 0 ) { Kokkos::parallel_for( DTK_MARK_REGION( "subtract_invalid_entries_from_offset" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries + 1 ), KOKKOS_LAMBDA( int q ) { tmp_offset( q ) = offset( q ) - tmp_offset( q ); } ); Kokkos::fence(); int const n_valid_indices = n_results - n_invalid_indices; Kokkos::View<int *, DeviceType> tmp_indices( indices.label(), n_valid_indices ); Kokkos::parallel_for( DTK_MARK_REGION( "copy_valid_indices" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int q ) { for ( int i = 0; i < tmp_offset( q + 1 ) - tmp_offset( q ); ++i ) { tmp_indices( tmp_offset( q ) + i ) = indices( offset( q ) + i ); } } ); Kokkos::fence(); indices = tmp_indices; if ( distances_ptr ) { Kokkos::View<double *, DeviceType> &distances = *distances_ptr; Kokkos::View<double *, DeviceType> tmp_distances( distances.label(), n_valid_indices ); Kokkos::parallel_for( DTK_MARK_REGION( "copy_valid_distances" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int q ) { for ( int i = 0; i < tmp_offset( q + 1 ) - tmp_offset( q ); ++i ) { tmp_distances( tmp_offset( q ) + i ) = distances( offset( q ) + i ); } } ); Kokkos::fence(); distances = tmp_distances; } offset = tmp_offset; } } template <typename DeviceType, typename Query> void queryDispatch( BoundingVolumeHierarchy<DeviceType> const bvh, Kokkos::View<Query *, DeviceType> queries, Kokkos::View<int *, DeviceType> &indices, Kokkos::View<int *, DeviceType> &offset, Details::SpatialPredicateTag ) { using ExecutionSpace = typename DeviceType::execution_space; int const n_queries = queries.extent( 0 ); // Initialize view // [ 0 0 0 .... 0 0 ] // ^ // N Kokkos::realloc( offset, n_queries + 1 ); Kokkos::deep_copy( offset, 0 ); // Say we found exactly two object for each query: // [ 2 2 2 .... 2 0 ] // ^ ^ // 0th Nth element in the view Kokkos::parallel_for( DTK_MARK_REGION( "first_pass_at_the_search_count_the_number_of_indices" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int i ) { offset( i ) = Details::TreeTraversal<DeviceType>::query( bvh, queries( i ), []( int ) {} ); } ); Kokkos::fence(); // Then we would get: // [ 0 2 4 .... 2N-2 2N ] // ^ // N exclusivePrefixSum( offset ); // Let us extract the last element in the view which is the total count of // objects which where found to meet the query predicates: // // [ 2N ] int const n_results = lastElement( offset ); // We allocate the memory and fill // // [ A0 A1 B0 B1 C0 C1 ... X0 X1 ] // ^ ^ ^ ^ ^ // 0 2 4 2N-2 2N Kokkos::realloc( indices, n_results ); Kokkos::parallel_for( DTK_MARK_REGION( "second_pass" ), Kokkos::RangePolicy<ExecutionSpace>( 0, n_queries ), KOKKOS_LAMBDA( int i ) { int count = 0; Details::TreeTraversal<DeviceType>::query( bvh, queries( i ), [indices, offset, i, &count]( int index ) { indices( offset( i ) + count++ ) = index; } ); } ); Kokkos::fence(); } template <typename DeviceType> template <typename Query> void BoundingVolumeHierarchy<DeviceType>::query( Kokkos::View<Query *, DeviceType> queries, Kokkos::View<int *, DeviceType> &indices, Kokkos::View<int *, DeviceType> &offset ) const { using Tag = typename Query::Tag; queryDispatch( *this, queries, indices, offset, Tag{} ); } template <typename DeviceType> template <typename Query> typename std::enable_if< std::is_same<typename Query::Tag, Details::NearestPredicateTag>::value, void>::type BoundingVolumeHierarchy<DeviceType>::query( Kokkos::View<Query *, DeviceType> queries, Kokkos::View<int *, DeviceType> &indices, Kokkos::View<int *, DeviceType> &offset, Kokkos::View<double *, DeviceType> &distances ) const { using Tag = typename Query::Tag; queryDispatch( *this, queries, indices, offset, Tag{}, &distances ); } } // namespace DataTransferKit #endif <|endoftext|>
<commit_before>// Copyright 2017 Adam Smith // 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 "asmith/serial/xml.hpp" namespace asmith { namespace serial { class xml_parser { public: virtual ~xml_parser(){} virtual void begin_element(const char*) = 0; virtual void end_element(const char*) = 0; virtual void begin_comment() = 0; virtual void end_comment() = 0; virtual void add_attribute(const char*, const char*) = 0; virtual void add_body(const char*) = 0; }; static const std::string XML_ILLEGAL[5][2] = { {"&", "&amp;"}, {"<", "&lt;"}, {">", "&gt;"}, {"\"", "&quot;"}, {"'", "&apos;"} }; static void xml_string_replace(std::string& aStr, const std::string& aTarget, const std::string& aReplacement) { size_t i = aStr.find(aTarget); while(i != std::string::npos) { aStr.replace(i, aTarget.size(), aReplacement); i = aStr.find(aTarget, i+aReplacement.size()); } } static void xml_encode_string(std::string& aStr) { for(const std::string i[2] : XML_ILLEGAL) { xml_string_replace(aStr, i[0], i[1]); } } static void xml_decode_string(std::string& aStr) { for(const std::string i[2] : XML_ILLEGAL) { xml_string_replace(aStr, i[1], i[0]); } } //! \todo Remove illegal characters in xml static void xml_write_internal(const value& aType, std::ostream& aStream) { const value::type tBuf = aType.get_type(); switch(tBuf) { case value::NULL_T: aStream << "null"; break; case value::BOOl_T: aStream << (aType.get_bool() ? "true" : "false"); break; case value::CHAR_T: aStream << aType.get_char() ; break; case value::NUMBER_T: aStream << aType.get_number(); break; case value::STRING_T: { std::string str = aType.get_string(); xml_encode_string(str); aStream << str; } break; case value::ARRAY_T: throw std::runtime_error("xml_format : Cannot write array as internal value"); break; case value::OBJECT_T: throw std::runtime_error("xml_format : Cannot write object as internal value"); break; default: throw std::runtime_error("xml_format : Invalid serial type"); break; } } static void xml_write_element(const char* const aName, const value& aType, std::ostream& aStream) { bool closeTag = true; aStream << "<" << aName; const value::type tBuf = aType.get_type(); switch(tBuf) { case value::NULL_T: aStream << "/>"; closeTag = false; break; case value::BOOl_T: aStream << ">"; aStream << (aType.get_bool() ? "true" : "false"); break; case value::CHAR_T: aStream << ">"; aStream << aType.get_char(); break; case value::NUMBER_T: aStream << ">"; aStream << aType.get_number(); break; case value::STRING_T: aStream << ">"; { std::string str = aType.get_string(); xml_encode_string(str); aStream << str; } break; case value::ARRAY_T: aStream << ">"; { const value::array_t tmp = aType.get_array(); const size_t s = tmp.size(); for(size_t i = 0; i < s; ++i) { xml_write_element(std::to_string(i).c_str(), tmp[i], aStream); } } break; case value::OBJECT_T: { const value::object_t tmp = aType.get_object(); const size_t s = tmp.size(); for(const auto& v : tmp) { const value::type t = v.second.get_type(); if(t != value::ARRAY_T && t != value::OBJECT_T) { aStream << ' ' << v.first << '=' << '"'; xml_write_internal(v.second, aStream); aStream << '"'; } } aStream << ">"; for (const auto& v : tmp) { const value::type t = v.second.get_type(); if(t == value::ARRAY_T || t == value::OBJECT_T) { xml_write_element(v.first.c_str(), v.second, aStream); } } } break; default: throw std::runtime_error("xml_format : Invalid serial type"); break; } if(closeTag) aStream << "</" << aName << ">"; } void xml_format::write_serial(const value& aType, std::ostream& aStream) { xml_write_element("xml", aType, aStream); } value xml_format::read_serial(std::istream& aStream) { //! \todo Implement return value(); } }} <commit_msg>Partial implementation of XML parser<commit_after>// Copyright 2017 Adam Smith // 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 "asmith/serial/xml.hpp" namespace asmith { namespace serial { class xml_parser { public: virtual ~xml_parser(){} virtual void begin_element(const char*) = 0; virtual void end_element(const char*) = 0; virtual void begin_comment() = 0; virtual void end_comment() = 0; virtual void add_attribute(const char*, const char*) = 0; virtual void add_body(const char*) = 0; }; static const std::string XML_ILLEGAL[5][2] = { {"&", "&amp;"}, {"<", "&lt;"}, {">", "&gt;"}, {"\"", "&quot;"}, {"'", "&apos;"} }; static void xml_string_replace(std::string& aStr, const std::string& aTarget, const std::string& aReplacement) { size_t i = aStr.find(aTarget); while(i != std::string::npos) { aStr.replace(i, aTarget.size(), aReplacement); i = aStr.find(aTarget, i+aReplacement.size()); } } static void xml_encode_string(std::string& aStr) { for(const std::string i[2] : XML_ILLEGAL) { xml_string_replace(aStr, i[0], i[1]); } } static void xml_decode_string(std::string& aStr) { for(const std::string i[2] : XML_ILLEGAL) { xml_string_replace(aStr, i[1], i[0]); } } //! \todo Remove illegal characters in xml static void xml_write_internal(const value& aType, std::ostream& aStream) { const value::type tBuf = aType.get_type(); switch(tBuf) { case value::NULL_T: aStream << "null"; break; case value::BOOl_T: aStream << (aType.get_bool() ? "true" : "false"); break; case value::CHAR_T: aStream << aType.get_char() ; break; case value::NUMBER_T: aStream << aType.get_number(); break; case value::STRING_T: { std::string str = aType.get_string(); xml_encode_string(str); aStream << str; } break; case value::ARRAY_T: throw std::runtime_error("xml_format : Cannot write array as internal value"); break; case value::OBJECT_T: throw std::runtime_error("xml_format : Cannot write object as internal value"); break; default: throw std::runtime_error("xml_format : Invalid serial type"); break; } } static void xml_write_element(const char* const aName, const value& aType, std::ostream& aStream) { bool closeTag = true; aStream << "<" << aName; const value::type tBuf = aType.get_type(); switch(tBuf) { case value::NULL_T: aStream << "/>"; closeTag = false; break; case value::BOOl_T: aStream << ">"; aStream << (aType.get_bool() ? "true" : "false"); break; case value::CHAR_T: aStream << ">"; aStream << aType.get_char(); break; case value::NUMBER_T: aStream << ">"; aStream << aType.get_number(); break; case value::STRING_T: aStream << ">"; { std::string str = aType.get_string(); xml_encode_string(str); aStream << str; } break; case value::ARRAY_T: aStream << ">"; { const value::array_t tmp = aType.get_array(); const size_t s = tmp.size(); for(size_t i = 0; i < s; ++i) { xml_write_element(std::to_string(i).c_str(), tmp[i], aStream); } } break; case value::OBJECT_T: { const value::object_t tmp = aType.get_object(); const size_t s = tmp.size(); for(const auto& v : tmp) { const value::type t = v.second.get_type(); if(t != value::ARRAY_T && t != value::OBJECT_T) { aStream << ' ' << v.first << '=' << '"'; xml_write_internal(v.second, aStream); aStream << '"'; } } aStream << ">"; for (const auto& v : tmp) { const value::type t = v.second.get_type(); if(t == value::ARRAY_T || t == value::OBJECT_T) { xml_write_element(v.first.c_str(), v.second, aStream); } } } break; default: throw std::runtime_error("xml_format : Invalid serial type"); break; } if(closeTag) aStream << "</" << aName << ">"; } void xml_format::write_serial(const value& aType, std::ostream& aStream) { xml_write_element("xml", aType, aStream); } value xml_format::read_serial(std::istream& aStream) { class serial_xml_parser : public xml_parser { private: std::vector<value*> mValueStack; std::vector<std::string> mElementName; public: value root; serial_xml_parser() { mValueStack.push_back(&root); } // Inherited from xml_parser void begin_element(const char* aName) override { mElementName.push_back(aName); } void end_element(const char*) override { mElementName.pop_back(); } void begin_comment() override { } void end_comment() override { } void add_attribute(const char* aName, const char* aValue) override { value::object_t& object = mValueStack.back()->get_object(); object.emplace(aName, value(aValue)); } void add_body(const char*) override { } }; //! \todo Implement return value(); } }} <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Dmitry Marakasov <amdmi3@amdmi3.ru> * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. */ #ifndef DANGLINGPTR_HH #define DANGLINGPTR_HH #include <memory> #include <cassert> #include <exception> #if defined(DANGLINGPTR_USE_LIST) && !defined(DANGLINGPTR_USE_SET) #include <algorithm> #include <list> #else #include <set> #endif namespace dangling { class bad_access : public std::exception { public: bad_access() { } virtual ~bad_access() noexcept { } virtual const char* what() const noexcept { return "bad dangling::ptr access"; } }; template <class T> class target { private: #if defined(DANGLINGPTR_USE_LIST) std::list<T**> dangling_ptrs_; #else std::set<T**> dangling_ptrs_; #endif public: target() { } virtual ~target() { for (auto& ptr : dangling_ptrs_) *ptr = nullptr; } void register_ptr(T** ptr) { #if defined(DANGLINGPTR_USE_LIST) assert(std::find(dangling_ptrs_.begin(), dangling_ptrs_.end(), ptr) == dangling_ptrs_.end()); dangling_ptrs_.push_back(ptr); #else assert(dangling_ptrs_.find(ptr) == dangling_ptrs_.end()); dangling_ptrs_.insert(ptr); #endif } void unregister_ptr(T** ptr) { #if defined(DANGLINGPTR_USE_LIST) auto iter = std::find(dangling_ptrs_.begin(), dangling_ptrs_.end(), ptr); assert(iter != dangling_ptrs_.end()); dangling_ptrs_.erase(iter); #else auto iter = dangling_ptrs_.find(ptr); assert(iter != dangling_ptrs_.end()); dangling_ptrs_.erase(iter); #endif } }; template <class T> class ptr { private: std::unique_ptr<T*> target_; public: // ctor/dtor ptr(T* target = nullptr) : target_(target ? new T*(nullptr) : nullptr) { if (target != nullptr) { target->register_ptr(target_.get()); *target_ = target; } } ~ptr() { if (target_ && *target_) (*target_)->unregister_ptr(target_.get()); } // move ctor/assignment ptr(ptr<T>&&) noexcept = default; ptr<T>& operator=(ptr<T>&& other) noexcept { if (this == &other) return *this; if (target_ && *target_) (*target_)->unregister_ptr(target_.get()); target_ = std::move(other.target_); return *this; } // copy ctor/assignment ptr(const ptr<T>& other) : target_(other.get() ? new T*(other.get()) : nullptr) { if (target_) (*target_)->register_ptr(target_.get()); } ptr<T>& operator=(const ptr<T>& other) { if (this == &other) return *this; reset(other.target_ ? *other.target_ : nullptr); return *this; } // setters ptr<T>& operator=(T* target) { reset(target); return *this; } void reset(T* target = nullptr) { if (get() == target) return; if (target == nullptr) { if (target_ && *target_) { (*target_)->unregister_ptr(target_.get()); *target_ = target; } } else { if (target_ && *target_) { target->register_ptr(target_.get()); (*target_)->unregister_ptr(target_.get()); *target_ = target; } else if (target_) { target->register_ptr(target_.get()); *target_ = target; } else { target_.reset(new T*(nullptr)); target->register_ptr(target_.get()); *target_ = target; } } } // dereferencing T& operator*() const { if (!target_ || *target_ == nullptr) throw bad_access(); return **target_; } T* operator->() const { if (!target_ || *target_ == nullptr) throw bad_access(); return *target_; } T* get() const noexcept { return target_ ? *target_ : nullptr; } // operators explicit operator bool() const noexcept { return target_ && *target_ != nullptr; } bool operator==(const ptr<T>& other) const noexcept { return get() == other.get(); } bool operator!=(const ptr<T>& other) const noexcept { return get() != other.get(); } bool operator<(const ptr<T>& other) const noexcept { return get() < other.get(); } bool operator<=(const ptr<T>& other) const noexcept { return get() <= other.get(); } bool operator>(const ptr<T>& other) const noexcept { return get() > other.get(); } bool operator>=(const ptr<T>& other) const noexcept { return get() >= other.get(); } }; } #endif <commit_msg>Simplify reset logic (distributive transformation)<commit_after>/* * Copyright (c) 2015 Dmitry Marakasov <amdmi3@amdmi3.ru> * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. */ #ifndef DANGLINGPTR_HH #define DANGLINGPTR_HH #include <memory> #include <cassert> #include <exception> #if defined(DANGLINGPTR_USE_LIST) && !defined(DANGLINGPTR_USE_SET) #include <algorithm> #include <list> #else #include <set> #endif namespace dangling { class bad_access : public std::exception { public: bad_access() { } virtual ~bad_access() noexcept { } virtual const char* what() const noexcept { return "bad dangling::ptr access"; } }; template <class T> class target { private: #if defined(DANGLINGPTR_USE_LIST) std::list<T**> dangling_ptrs_; #else std::set<T**> dangling_ptrs_; #endif public: target() { } virtual ~target() { for (auto& ptr : dangling_ptrs_) *ptr = nullptr; } void register_ptr(T** ptr) { #if defined(DANGLINGPTR_USE_LIST) assert(std::find(dangling_ptrs_.begin(), dangling_ptrs_.end(), ptr) == dangling_ptrs_.end()); dangling_ptrs_.push_back(ptr); #else assert(dangling_ptrs_.find(ptr) == dangling_ptrs_.end()); dangling_ptrs_.insert(ptr); #endif } void unregister_ptr(T** ptr) { #if defined(DANGLINGPTR_USE_LIST) auto iter = std::find(dangling_ptrs_.begin(), dangling_ptrs_.end(), ptr); assert(iter != dangling_ptrs_.end()); dangling_ptrs_.erase(iter); #else auto iter = dangling_ptrs_.find(ptr); assert(iter != dangling_ptrs_.end()); dangling_ptrs_.erase(iter); #endif } }; template <class T> class ptr { private: std::unique_ptr<T*> target_; public: // ctor/dtor ptr(T* target = nullptr) : target_(target ? new T*(nullptr) : nullptr) { if (target != nullptr) { target->register_ptr(target_.get()); *target_ = target; } } ~ptr() { if (target_ && *target_) (*target_)->unregister_ptr(target_.get()); } // move ctor/assignment ptr(ptr<T>&&) noexcept = default; ptr<T>& operator=(ptr<T>&& other) noexcept { if (this == &other) return *this; if (target_ && *target_) (*target_)->unregister_ptr(target_.get()); target_ = std::move(other.target_); return *this; } // copy ctor/assignment ptr(const ptr<T>& other) : target_(other.get() ? new T*(other.get()) : nullptr) { if (target_) (*target_)->register_ptr(target_.get()); } ptr<T>& operator=(const ptr<T>& other) { if (this == &other) return *this; reset(other.target_ ? *other.target_ : nullptr); return *this; } // setters ptr<T>& operator=(T* target) { reset(target); return *this; } void reset(T* target = nullptr) { if (get() == target) return; if (target == nullptr) { if (target_ && *target_) { (*target_)->unregister_ptr(target_.get()); } } else { if (target_ && *target_) { target->register_ptr(target_.get()); (*target_)->unregister_ptr(target_.get()); } else if (target_) { target->register_ptr(target_.get()); } else { target_.reset(new T*(nullptr)); target->register_ptr(target_.get()); } } *target_ = target; } // dereferencing T& operator*() const { if (!target_ || *target_ == nullptr) throw bad_access(); return **target_; } T* operator->() const { if (!target_ || *target_ == nullptr) throw bad_access(); return *target_; } T* get() const noexcept { return target_ ? *target_ : nullptr; } // operators explicit operator bool() const noexcept { return target_ && *target_ != nullptr; } bool operator==(const ptr<T>& other) const noexcept { return get() == other.get(); } bool operator!=(const ptr<T>& other) const noexcept { return get() != other.get(); } bool operator<(const ptr<T>& other) const noexcept { return get() < other.get(); } bool operator<=(const ptr<T>& other) const noexcept { return get() <= other.get(); } bool operator>(const ptr<T>& other) const noexcept { return get() > other.get(); } bool operator>=(const ptr<T>& other) const noexcept { return get() >= other.get(); } }; } #endif <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" // // Main network // // Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xbf; pchMessageStart[1] = 0xf4; pchMessageStart[2] = 0x1a; pchMessageStart[3] = 0xb6; vAlertPubKey = ParseHex(""); nDefaultPort = 58273; nRPCPort = 59273; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); const char* pszTimestamp = "ISIS terror attacks in Brussels"; std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].SetEmpty(); CTransaction txNew(1, 1458750507, vin, vout, 0); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1458750507; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 468977; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000001a7bb3214e3e1d2e4c256082b817a3c5dff5def37456ae16d7edaa508be")); assert(genesis.hashMerkleRoot == uint256("0xa1de9df44936bd1dd483e217fa17ec1881d2caf741ca67a33f6cd6850183078c")); vSeeds.push_back(CDNSSeedData("dnsseed.ionomy.com", "45.32.211.127")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,103); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,88); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,153); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nLastPOWBlock = 2000; } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x5f; pchMessageStart[1] = 0xf2; pchMessageStart[2] = 0x15; pchMessageStart[3] = 0x30; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); vAlertPubKey = ParseHex(""); nDefaultPort = 51002; nRPCPort = 51003; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 72686; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x0000070638e1fb122fb31b4753a5311f3c8784604d9f6ce42e8fec96d94173b4")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,127); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test)); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>Added dnsseed<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" // // Main network // // Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0xbf; pchMessageStart[1] = 0xf4; pchMessageStart[2] = 0x1a; pchMessageStart[3] = 0xb6; vAlertPubKey = ParseHex(""); nDefaultPort = 58273; nRPCPort = 59273; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); const char* pszTimestamp = "ISIS terror attacks in Brussels"; std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].SetEmpty(); CTransaction txNew(1, 1458750507, vin, vout, 0); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1458750507; genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 468977; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x000001a7bb3214e3e1d2e4c256082b817a3c5dff5def37456ae16d7edaa508be")); assert(genesis.hashMerkleRoot == uint256("0xa1de9df44936bd1dd483e217fa17ec1881d2caf741ca67a33f6cd6850183078c")); vSeeds.push_back(CDNSSeedData("dnsseed.ionomy.com", "45.32.211.127")); vSeeds.push_back(CDNSSeedData("main.seed.ionomy.nl", "95.85.26.115")); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,103); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,88); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,153); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nLastPOWBlock = 2000; } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x5f; pchMessageStart[1] = 0xf2; pchMessageStart[2] = 0x15; pchMessageStart[3] = 0x30; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); vAlertPubKey = ParseHex(""); nDefaultPort = 51002; nRPCPort = 51003; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nBits = bnProofOfWorkLimit.GetCompact(); genesis.nNonce = 72686; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x0000070638e1fb122fb31b4753a5311f3c8784604d9f6ce42e8fec96d94173b4")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,127); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test)); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2016 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Developers // Copyright (c) 2015-2016 Silk Network // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include <assert.h> #include "chainparams.h" #include "chainparamsseeds.h" #include "main.h" #include "net.h" #include "random.h" #include "utilstrencodings.h" using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; // // Main network // // Convert the pnSeeds array into usable address objects. static void convertSeeds(std::vector<CAddress> &vSeedsOut, const unsigned int *data, unsigned int count, int port) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int k = 0; k < count; ++k) { struct in_addr ip; unsigned int i = data[k], t; // -- convert to big endian t = (i & 0x000000ff) << 24u | (i & 0x0000ff00) << 8u | (i & 0x00ff0000) >> 8u | (i & 0xff000000) >> 24u; memcpy(&ip, &t, sizeof(ip)); CAddress addr(CService(ip, port)); addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek; vSeedsOut.push_back(addr); } } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x1f; pchMessageStart[1] = 0x22; pchMessageStart[2] = 0x05; pchMessageStart[3] = 0x31; vAlertPubKey = ParseHex("0450e0acc669231cfe2d0a8f0d164c341547487adff89f09e1e78a5299d204bd1c9f05897cb916365c56a31377d872abddb551a12d8d8163149abfc851be7f88ba"); nDefaultPort = 31000; nRPCPort = 31500; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // PoW starting difficulty = 0.0002441 // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. const char* pszTimestamp = "2015 DarkSilk is Born"; std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].SetEmpty(); CMutableTransaction txNew(1, 1444948732, vin, vout, 0); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1444948732; //Change to current UNIX Time of generated genesis genesis.nBits = 0x1e0ffff0; genesis.nNonce = 763220; hashGenesisBlock = genesis.GetHash(); //// debug print /* printf("Gensis Hash: %s\n", genesis.GetHash().ToString().c_str()); printf("Gensis Hash Merkle: %s\n", genesis.hashMerkleRoot.ToString().c_str()); printf("Gensis nTime: %u\n", genesis.nTime); printf("Gensis nBits: %08x\n", genesis.nBits); printf("Gensis Nonce: %u\n\n\n", genesis.nNonce); */ assert(hashGenesisBlock == uint256("0xdcc5e22e275eff273799a4c06493f8364316d032813c22845602f05ff13d7ec7")); assert(genesis.hashMerkleRoot == uint256("0xfed7550a453e532c460fac58d438740235c380f9908cae2d602b705ca2c2f0a6")); vSeeds.push_back(CDNSSeedData("darksilk.org", "ds1.darksilk.org")); vSeeds.push_back(CDNSSeedData("", "")); base58Prefixes[PUBKEY_ADDRESS] = list_of(30); //DarkSilk addresses start with 'D' base58Prefixes[SCRIPT_ADDRESS] = list_of(10); //DarkSilk script addresses start with '5' base58Prefixes[SECRET_KEY] = list_of(140); //DarkSilk private keys start with 'y' base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x02)(0xFE)(0x52)(0x7D); //DarkSilk BIP32 pubkeys start with 'drks' base58Prefixes[EXT_SECRET_KEY] = list_of(0x02)(0xFE)(0x52)(0x8C); //DarkSilk BIP32 prvkeys start with 'drky' convertSeeds(vFixedSeeds, pnSeed, ARRAYLEN(pnSeed), nDefaultPort); //TODO(AA) nPoolMaxTransactions = 3; strSandstormPoolDummyAddress = "DDCxTmWLPytjnEAMd3TCGaryJStEx5caSm"; //private key = MpBeYuuA7c47bqa6ubmBnP8P7hkpmJTSUgwejC8AehSPwsXmkZHD strStormnodePaymentsPubKey = ""; nFirstPOSBlock = 101; nStormnodeCollateral = 10000; nStormnodeStartBlock = 420; nStartStormnodePayments = 1446335999; //Wed, 31 Oct 2015 23:59:59 GMT nSandstormCollateral = (0.01*COIN); nSandstormPoolMax = (9999.99*COIN); nPoWBlockSpacing = 60; nPoSBlockSpacing = 40; } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x1f; pchMessageStart[1] = 0x22; pchMessageStart[2] = 0x05; pchMessageStart[3] = 0x30; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // PoW starting difficulty = 0.0002441 vAlertPubKey = ParseHex(""); nDefaultPort = 31750; nRPCPort = 31800; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1438578972; genesis.nBits = 0; genesis.nNonce = 0; hashGenesisBlock = genesis.GetHash(); //printf("Test Genesis Hash: %s\n", genesis.GetHash().ToString().c_str()); assert(hashGenesisBlock == uint256("0xf788ac4ae46429468897b4b9758651cb8a642a6e01f16968134a75078905e24d")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = list_of(30); //DarkSilk addresses start with 'D' base58Prefixes[SCRIPT_ADDRESS] = list_of(10); //DarkSilk script addresses start with '5' base58Prefixes[SECRET_KEY] = list_of(140); //DarkSilk private keys start with 'y' base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x02)(0xFE)(0x52)(0x7D); //DarkSilk BIP32 pubkeys start with 'drks' base58Prefixes[EXT_SECRET_KEY] = list_of(0x02)(0xFE)(0x52)(0x8C); //DarkSilk BIP32 prvkeys start with 'drky' convertSeeds(vFixedSeeds, pnTestnetSeed, ARRAYLEN(pnTestnetSeed), nDefaultPort); //TODO(Amir): Change pub key and dummy address nPoolMaxTransactions = 3; strStormnodePaymentsPubKey = ""; strSandstormPoolDummyAddress = "DDCxTmWLPytjnEAMd3TCGaryJStEx5caSm"; //private key = MpBeYuuA7c47bqa6ubmBnP8P7hkpmJTSUgwejC8AehSPwsXmkZHD nFirstPOSBlock = 101; nStormnodeCollateral = 10000; nStormnodeStartBlock = 100; nStartStormnodePayments = 1446335999; //Wed, 31 Oct 2015 23:59:59 GMT nSandstormCollateral = (0.01*COIN); nSandstormPoolMax = (9999.99*COIN); nPoWBlockSpacing = 60; nPoSBlockSpacing = 40; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>Whoops... simple mistake<commit_after>// Copyright (c) 2009-2016 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Developers // Copyright (c) 2015-2016 Silk Network // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include <assert.h> #include "chainparams.h" #include "chainparamsseeds.h" #include "main.h" #include "net.h" #include "random.h" #include "utilstrencodings.h" using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; // // Main network // // Convert the pnSeeds array into usable address objects. static void convertSeeds(std::vector<CAddress> &vSeedsOut, const unsigned int *data, unsigned int count, int port) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int k = 0; k < count; ++k) { struct in_addr ip; unsigned int i = data[k], t; // -- convert to big endian t = (i & 0x000000ff) << 24u | (i & 0x0000ff00) << 8u | (i & 0x00ff0000) >> 8u | (i & 0xff000000) >> 24u; memcpy(&ip, &t, sizeof(ip)); CAddress addr(CService(ip, port)); addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek; vSeedsOut.push_back(addr); } } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x1f; pchMessageStart[1] = 0x22; pchMessageStart[2] = 0x05; pchMessageStart[3] = 0x31; vAlertPubKey = ParseHex("0450e0acc669231cfe2d0a8f0d164c341547487adff89f09e1e78a5299d204bd1c9f05897cb916365c56a31377d872abddb551a12d8d8163149abfc851be7f88ba"); nDefaultPort = 31000; nRPCPort = 31500; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // PoW starting difficulty = 0.0002441 // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. const char* pszTimestamp = "2015 DarkSilk is Born"; std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].SetEmpty(); CMutableTransaction txNew(1, 1444948732, vin, vout, 0); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1444948732; //Change to current UNIX Time of generated genesis genesis.nBits = 0x1e0ffff0; genesis.nNonce = 763220; hashGenesisBlock = genesis.GetHash(); //// debug print /* printf("Gensis Hash: %s\n", genesis.GetHash().ToString().c_str()); printf("Gensis Hash Merkle: %s\n", genesis.hashMerkleRoot.ToString().c_str()); printf("Gensis nTime: %u\n", genesis.nTime); printf("Gensis nBits: %08x\n", genesis.nBits); printf("Gensis Nonce: %u\n\n\n", genesis.nNonce); */ assert(hashGenesisBlock == uint256("0xdcc5e22e275eff273799a4c06493f8364316d032813c22845602f05ff13d7ec7")); assert(genesis.hashMerkleRoot == uint256("0xfed7550a453e532c460fac58d438740235c380f9908cae2d602b705ca2c2f0a6")); vSeeds.push_back(CDNSSeedData("darksilk.org", "ds1.darksilk.org")); vSeeds.push_back(CDNSSeedData("", "")); base58Prefixes[PUBKEY_ADDRESS] = list_of(30); //DarkSilk addresses start with 'D' base58Prefixes[SCRIPT_ADDRESS] = list_of(10); //DarkSilk script addresses start with '5' base58Prefixes[SECRET_KEY] = list_of(140); //DarkSilk private keys start with 'y' base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x02)(0xFE)(0x52)(0x7D); //DarkSilk BIP32 pubkeys start with 'drks' base58Prefixes[EXT_SECRET_KEY] = list_of(0x02)(0xFE)(0x52)(0x8C); //DarkSilk BIP32 prvkeys start with 'drky' convertSeeds(vFixedSeeds, pnSeed, ARRAYLEN(pnSeed), nDefaultPort); //TODO(AA) nPoolMaxTransactions = 3; strSandstormPoolDummyAddress = "DDCxTmWLPytjnEAMd3TCGaryJStEx5caSm"; //private key = MpBeYuuA7c47bqa6ubmBnP8P7hkpmJTSUgwejC8AehSPwsXmkZHD strStormnodePaymentsPubKey = ""; nFirstPOSBlock = 101; nStormnodeCollateral = 10000; nStormnodeStartBlock = 420; nStartStormnodePayments = 1446335999; //Wed, 31 Oct 2015 23:59:59 GMT nSandstormCollateral = (0.01*COIN); nSandstormPoolMax = (9999.99*COIN); nPoWBlockSpacing = 60; nPoSBlockSpacing = 64; } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x1f; pchMessageStart[1] = 0x22; pchMessageStart[2] = 0x05; pchMessageStart[3] = 0x30; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 20); // PoW starting difficulty = 0.0002441 vAlertPubKey = ParseHex(""); nDefaultPort = 31750; nRPCPort = 31800; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nTime = 1438578972; genesis.nBits = 0; genesis.nNonce = 0; hashGenesisBlock = genesis.GetHash(); //printf("Test Genesis Hash: %s\n", genesis.GetHash().ToString().c_str()); assert(hashGenesisBlock == uint256("0xf788ac4ae46429468897b4b9758651cb8a642a6e01f16968134a75078905e24d")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = list_of(30); //DarkSilk addresses start with 'D' base58Prefixes[SCRIPT_ADDRESS] = list_of(10); //DarkSilk script addresses start with '5' base58Prefixes[SECRET_KEY] = list_of(140); //DarkSilk private keys start with 'y' base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x02)(0xFE)(0x52)(0x7D); //DarkSilk BIP32 pubkeys start with 'drks' base58Prefixes[EXT_SECRET_KEY] = list_of(0x02)(0xFE)(0x52)(0x8C); //DarkSilk BIP32 prvkeys start with 'drky' convertSeeds(vFixedSeeds, pnTestnetSeed, ARRAYLEN(pnTestnetSeed), nDefaultPort); //TODO(Amir): Change pub key and dummy address nPoolMaxTransactions = 3; strStormnodePaymentsPubKey = ""; strSandstormPoolDummyAddress = "DDCxTmWLPytjnEAMd3TCGaryJStEx5caSm"; //private key = MpBeYuuA7c47bqa6ubmBnP8P7hkpmJTSUgwejC8AehSPwsXmkZHD nFirstPOSBlock = 101; nStormnodeCollateral = 10000; nStormnodeStartBlock = 100; nStartStormnodePayments = 1446335999; //Wed, 31 Oct 2015 23:59:59 GMT nSandstormCollateral = (0.01*COIN); nSandstormPoolMax = (9999.99*COIN); nPoWBlockSpacing = 60; nPoSBlockSpacing = 64; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>
<commit_before>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" // // Main network // // Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x1b; pchMessageStart[1] = 0xa6; pchMessageStart[2] = 0x45; pchMessageStart[3] = 0x16; vAlertPubKey = ParseHex(""); nDefaultPort = 29028; nRPCPort = 29029; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. // //CBlock(hash=000001faef25dec4fbcf906e6242621df2c183bf232f263d0ba5b101911e4563, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=12630d16a97f24b287c8c2594dda5fb98c9e6c70fc61d44191931ea2aa08dc90, nTime=1393221600, nBits=1e0fffff, nNonce=164482, vtx=1, vchBlockSig=) // Coinbase(hash=12630d16a9, nTime=1393221600, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a24323020466562203230313420426974636f696e2041544d7320636f6d6520746f20555341) // CTxOut(empty) // vMerkleTree: 12630d16a9 const char* pszTimestamp = "Today was Back to the future's date, we're pretty far off."; // CTransaction txNew; // txNew.nTime = 1426700641; // txNew.vin.resize(1); // txNew.vout.resize(1); // txNew.vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); // txNew.vout[0].SetEmpty(); std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].SetEmpty(); CTransaction txNew(1, 1445464375, vin, vout, 0); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1445464375; genesis.nBits = 520159231; genesis.nNonce = 16669; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x0000ef061040c9a2250922aa48a1787ca2f378a8b188aeb700423a0839e203e8")); assert(genesis.hashMerkleRoot == uint256("0xf3f2c3e5c6d2893aa2c81ee05993d8a9106481002dcf4be883ab145891e8d0ff")); vSeeds.push_back(CDNSSeedData("108.61.178.234", "108.61.178.234")); base58Prefixes[PUBKEY_ADDRESS] = list_of(111); base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nLastPOWBlock = 8000; } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x1f; pchMessageStart[1] = 0x22; pchMessageStart[2] = 0x05; pchMessageStart[3] = 0x30; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); vAlertPubKey = ParseHex(""); nDefaultPort = 20114; nRPCPort = 20115; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nBits = 520159231; genesis.nNonce = 16669; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x0000ef061040c9a2250922aa48a1787ca2f378a8b188aeb700423a0839e203e8")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = list_of(127); base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test)); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <commit_msg>more updates<commit_after>// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assert.h" #include "chainparams.h" #include "main.h" #include "util.h" #include <boost/assign/list_of.hpp> using namespace boost::assign; struct SeedSpec6 { uint8_t addr[16]; uint16_t port; }; #include "chainparamsseeds.h" // // Main network // // Convert the pnSeeds6 array into usable address objects. static void convertSeed6(std::vector<CAddress> &vSeedsOut, const SeedSpec6 *data, unsigned int count) { // It'll only connect to one or two seed nodes because once it connects, // it'll get a pile of addresses with newer timestamps. // Seed nodes are given a random 'last seen time' of between one and two // weeks ago. const int64_t nOneWeek = 7*24*60*60; for (unsigned int i = 0; i < count; i++) { struct in6_addr ip; memcpy(&ip, data[i].addr, sizeof(ip)); CAddress addr(CService(ip, data[i].port)); addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek; vSeedsOut.push_back(addr); } } class CMainParams : public CChainParams { public: CMainParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x1b; pchMessageStart[1] = 0xa6; pchMessageStart[2] = 0x45; pchMessageStart[3] = 0x16; vAlertPubKey = ParseHex(""); nDefaultPort = 29028; nRPCPort = 29029; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. // //CBlock(hash=000001faef25dec4fbcf906e6242621df2c183bf232f263d0ba5b101911e4563, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=12630d16a97f24b287c8c2594dda5fb98c9e6c70fc61d44191931ea2aa08dc90, nTime=1393221600, nBits=1e0fffff, nNonce=164482, vtx=1, vchBlockSig=) // Coinbase(hash=12630d16a9, nTime=1393221600, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a24323020466562203230313420426974636f696e2041544d7320636f6d6520746f20555341) // CTxOut(empty) // vMerkleTree: 12630d16a9 const char* pszTimestamp = "Today was Back to the future's date, we're pretty far off."; // CTransaction txNew; // txNew.nTime = 1426700641; // txNew.vin.resize(1); // txNew.vout.resize(1); // txNew.vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); // txNew.vout[0].SetEmpty(); std::vector<CTxIn> vin; vin.resize(1); vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); std::vector<CTxOut> vout; vout.resize(1); vout[0].SetEmpty(); CTransaction txNew(1, 1445464375, vin, vout, 0); genesis.vtx.push_back(txNew); genesis.hashPrevBlock = 0; genesis.hashMerkleRoot = genesis.BuildMerkleTree(); genesis.nVersion = 1; genesis.nTime = 1445464375; genesis.nBits = 520159231; genesis.nNonce = 16669; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x0000ef061040c9a2250922aa48a1787ca2f378a8b188aeb700423a0839e203e8")); assert(genesis.hashMerkleRoot == uint256("0xf3f2c3e5c6d2893aa2c81ee05993d8a9106481002dcf4be883ab145891e8d0ff")); vSeeds.push_back(CDNSSeedData("108.61.178.234", "108.61.178.234")); base58Prefixes[PUBKEY_ADDRESS] = list_of(63); base58Prefixes[SCRIPT_ADDRESS] = list_of(125); base58Prefixes[SECRET_KEY] = list_of(191); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x88)(0xB2)(0x1E); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x88)(0xAD)(0xE4); convertSeed6(vFixedSeeds, pnSeed6_main, ARRAYLEN(pnSeed6_main)); nLastPOWBlock = 8000; } virtual const CBlock& GenesisBlock() const { return genesis; } virtual Network NetworkID() const { return CChainParams::MAIN; } virtual const vector<CAddress>& FixedSeeds() const { return vFixedSeeds; } protected: CBlock genesis; vector<CAddress> vFixedSeeds; }; static CMainParams mainParams; // // Testnet // class CTestNetParams : public CMainParams { public: CTestNetParams() { // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. pchMessageStart[0] = 0x1f; pchMessageStart[1] = 0x22; pchMessageStart[2] = 0x05; pchMessageStart[3] = 0x30; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); vAlertPubKey = ParseHex(""); nDefaultPort = 20114; nRPCPort = 20115; strDataDir = "testnet"; // Modify the testnet genesis block so the timestamp is valid for a later start. genesis.nBits = 520159231; genesis.nNonce = 16669; hashGenesisBlock = genesis.GetHash(); assert(hashGenesisBlock == uint256("0x0000ef061040c9a2250922aa48a1787ca2f378a8b188aeb700423a0839e203e8")); vFixedSeeds.clear(); vSeeds.clear(); base58Prefixes[PUBKEY_ADDRESS] = list_of(127); base58Prefixes[SCRIPT_ADDRESS] = list_of(196); base58Prefixes[SECRET_KEY] = list_of(239); base58Prefixes[EXT_PUBLIC_KEY] = list_of(0x04)(0x35)(0x87)(0xCF); base58Prefixes[EXT_SECRET_KEY] = list_of(0x04)(0x35)(0x83)(0x94); convertSeed6(vFixedSeeds, pnSeed6_test, ARRAYLEN(pnSeed6_test)); nLastPOWBlock = 0x7fffffff; } virtual Network NetworkID() const { return CChainParams::TESTNET; } }; static CTestNetParams testNetParams; static CChainParams *pCurrentParams = &mainParams; const CChainParams &Params() { return *pCurrentParams; } void SelectParams(CChainParams::Network network) { switch (network) { case CChainParams::MAIN: pCurrentParams = &mainParams; break; case CChainParams::TESTNET: pCurrentParams = &testNetParams; break; default: assert(false && "Unimplemented network"); return; } } bool SelectParamsFromCommandLine() { bool fTestNet = GetBoolArg("-testnet", false); if (fTestNet) { SelectParams(CChainParams::TESTNET); } else { SelectParams(CChainParams::MAIN); } return true; } <|endoftext|>