text
stringlengths
54
60.6k
<commit_before>/* Copyright (c) 2008-2017 the MRtrix3 contributors. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * * MRtrix 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. * * For more details, see http://www.mrtrix.org/. */ #include "mrtrix.h" namespace MR { /************************************************************************ * Miscellaneous functions * ************************************************************************/ vector<default_type> parse_floats (const std::string& spec) { vector<default_type> V; if (!spec.size()) throw Exception ("floating-point sequence specifier is empty"); std::string::size_type start = 0, end; default_type range_spec[3]; int i = 0; try { do { end = spec.find_first_of (",:", start); std::string sub (spec.substr (start, end-start)); range_spec[i] = (sub.empty() || sub == "nan") ? NAN : to<default_type> (sub); char last_char = end < spec.size() ? spec[end] : '\0'; if (last_char == ':') { i++; if (i > 2) throw Exception ("invalid number range in number sequence \"" + spec + "\""); } else { if (i) { if (i != 2) throw Exception ("For floating-point ranges, must specify three numbers (start:step:end)"); default_type first = range_spec[0], inc = range_spec[1], last = range_spec[2]; if (!inc || (inc * (last-first) < 0.0) || !std::isfinite(first) || !std::isfinite(inc) || !std::isfinite(last)) throw Exception ("Floating-point range does not form a finite set"); default_type value = first; for (size_t mult = 0; (inc>0.0f ? value < last - 0.5f*inc : value > last + 0.5f*inc); ++mult) V.push_back ((value = first + (mult * inc))); } else { V.push_back (range_spec[0]); } i = 0; } start = end+1; } while (end < spec.size()); } catch (Exception& E) { throw Exception (E, "can't parse floating-point sequence specifier \"" + spec + "\""); } return (V); } vector<int> parse_ints (const std::string& spec, int last) { vector<int> V; if (!spec.size()) throw Exception ("integer sequence specifier is empty"); std::string::size_type start = 0, end; int num[3]; int i = 0; try { do { end = spec.find_first_of (",:", start); std::string token (strip (spec.substr (start, end-start))); if (lowercase (token) == "end") { if (last == std::numeric_limits<int>::max()) throw Exception ("value of \"end\" is not known in number sequence \"" + spec + "\""); num[i] = last; } else num[i] = to<int> (spec.substr (start, end-start)); char last_char = end < spec.size() ? spec[end] : '\0'; if (last_char == ':') { i++; if (i > 2) throw Exception ("invalid number range in number sequence \"" + spec + "\""); } else { if (i) { int inc, last; if (i == 2) { inc = num[1]; last = num[2]; } else { inc = 1; last = num[1]; } if (inc * (last - num[0]) < 0) inc = -inc; for (; (inc > 0 ? num[0] <= last : num[0] >= last) ; num[0] += inc) V.push_back (num[0]); } else V.push_back (num[0]); i = 0; } start = end+1; } while (end < spec.size()); } catch (Exception& E) { throw Exception (E, "can't parse integer sequence specifier \"" + spec + "\""); } return (V); } vector<std::string> split (const std::string& string, const char* delimiters, bool ignore_empty_fields, size_t num) { vector<std::string> V; std::string::size_type start = 0, end; try { do { end = string.find_first_of (delimiters, start); V.push_back (string.substr (start, end-start)); if (end >= string.size()) break; start = ignore_empty_fields ? string.find_first_not_of (delimiters, end+1) : end+1; if (start > string.size()) break; if (V.size()+1 >= num) { V.push_back (string.substr (start)); break; } } while (true); } catch (...) { throw Exception ("can't split string \"" + string + "\""); } return V; } } <commit_msg>split(): Ignore leading delimiters<commit_after>/* Copyright (c) 2008-2017 the MRtrix3 contributors. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * * MRtrix 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. * * For more details, see http://www.mrtrix.org/. */ #include "mrtrix.h" namespace MR { /************************************************************************ * Miscellaneous functions * ************************************************************************/ vector<default_type> parse_floats (const std::string& spec) { vector<default_type> V; if (!spec.size()) throw Exception ("floating-point sequence specifier is empty"); std::string::size_type start = 0, end; default_type range_spec[3]; int i = 0; try { do { end = spec.find_first_of (",:", start); std::string sub (spec.substr (start, end-start)); range_spec[i] = (sub.empty() || sub == "nan") ? NAN : to<default_type> (sub); char last_char = end < spec.size() ? spec[end] : '\0'; if (last_char == ':') { i++; if (i > 2) throw Exception ("invalid number range in number sequence \"" + spec + "\""); } else { if (i) { if (i != 2) throw Exception ("For floating-point ranges, must specify three numbers (start:step:end)"); default_type first = range_spec[0], inc = range_spec[1], last = range_spec[2]; if (!inc || (inc * (last-first) < 0.0) || !std::isfinite(first) || !std::isfinite(inc) || !std::isfinite(last)) throw Exception ("Floating-point range does not form a finite set"); default_type value = first; for (size_t mult = 0; (inc>0.0f ? value < last - 0.5f*inc : value > last + 0.5f*inc); ++mult) V.push_back ((value = first + (mult * inc))); } else { V.push_back (range_spec[0]); } i = 0; } start = end+1; } while (end < spec.size()); } catch (Exception& E) { throw Exception (E, "can't parse floating-point sequence specifier \"" + spec + "\""); } return (V); } vector<int> parse_ints (const std::string& spec, int last) { vector<int> V; if (!spec.size()) throw Exception ("integer sequence specifier is empty"); std::string::size_type start = 0, end; int num[3]; int i = 0; try { do { end = spec.find_first_of (",:", start); std::string token (strip (spec.substr (start, end-start))); if (lowercase (token) == "end") { if (last == std::numeric_limits<int>::max()) throw Exception ("value of \"end\" is not known in number sequence \"" + spec + "\""); num[i] = last; } else num[i] = to<int> (spec.substr (start, end-start)); char last_char = end < spec.size() ? spec[end] : '\0'; if (last_char == ':') { i++; if (i > 2) throw Exception ("invalid number range in number sequence \"" + spec + "\""); } else { if (i) { int inc, last; if (i == 2) { inc = num[1]; last = num[2]; } else { inc = 1; last = num[1]; } if (inc * (last - num[0]) < 0) inc = -inc; for (; (inc > 0 ? num[0] <= last : num[0] >= last) ; num[0] += inc) V.push_back (num[0]); } else V.push_back (num[0]); i = 0; } start = end+1; } while (end < spec.size()); } catch (Exception& E) { throw Exception (E, "can't parse integer sequence specifier \"" + spec + "\""); } return (V); } vector<std::string> split (const std::string& string, const char* delimiters, bool ignore_empty_fields, size_t num) { vector<std::string> V; std::string::size_type start = 0, end; try { if (ignore_empty_fields) start = string.find_first_not_of (delimiters); do { end = string.find_first_of (delimiters, start); V.push_back (string.substr (start, end-start)); if (end >= string.size()) break; start = ignore_empty_fields ? string.find_first_not_of (delimiters, end+1) : end+1; if (start > string.size()) break; if (V.size()+1 >= num) { V.push_back (string.substr (start)); break; } } while (true); } catch (...) { throw Exception ("can't split string \"" + string + "\""); } return V; } } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: color.hpp 39 2005-04-10 20:39:53Z pavlenko $ #ifndef COLOR_HPP #define COLOR_HPP #include "config.hpp" #include <sstream> namespace mapnik { class MAPNIK_DECL Color { private: unsigned int rgba_; public: Color() :rgba_(0xffffffff) {} Color(int red,int green,int blue,int alpha=0xff) : rgba_((alpha&0xff) << 24 | (blue&0xff) << 16 | (green&0xff) << 8 | red&0xff) {} explicit Color(int rgba) : rgba_(rgba) {} Color(const Color& rhs) : rgba_(rhs.rgba_) {} Color& operator=(const Color& rhs) { if (this==&rhs) return *this; rgba_=rhs.rgba_; return *this; } inline unsigned int blue() const { return (rgba_>>16)&0xff; } inline unsigned int green() const { return (rgba_>>8)&0xff; } inline unsigned int red() const { return rgba_&0xff; } inline void set_red(unsigned int r) { rgba_ = (rgba_ & 0xffffff00) | (r&0xff); } inline void set_green(unsigned int g) { rgba_ = (rgba_ & 0xffff00ff) | ((g&0xff) << 8); } inline void set_blue(unsigned int b) { rgba_ = (rgba_ & 0xff00ffff) | ((b&0xff) << 16); } inline unsigned int alpha() const { return (rgba_>>24)&0xff; } inline unsigned int rgba() const { return rgba_; } inline void set_bgr(unsigned bgr) { rgba_ = (rgba_ & 0xff000000) | (bgr & 0xffffff); } inline bool operator==(Color const& other) const { return rgba_ == other.rgba_; } inline std::string to_string() const { std::stringstream ss; ss << "rgb (" << red() << "," << green() << "," << blue() <<")"; return ss.str(); } }; } #endif //COLOR_HPP <commit_msg>implemented to_hex_color() method that returns #RRGGBB color representation. <commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: color.hpp 39 2005-04-10 20:39:53Z pavlenko $ #ifndef COLOR_HPP #define COLOR_HPP #include <boost/format.hpp> #include "config.hpp" #include <sstream> namespace mapnik { class MAPNIK_DECL Color { private: unsigned int rgba_; public: Color() :rgba_(0xffffffff) {} Color(int red,int green,int blue,int alpha=0xff) : rgba_((alpha&0xff) << 24 | (blue&0xff) << 16 | (green&0xff) << 8 | red&0xff) {} explicit Color(int rgba) : rgba_(rgba) {} Color(const Color& rhs) : rgba_(rhs.rgba_) {} Color& operator=(const Color& rhs) { if (this==&rhs) return *this; rgba_=rhs.rgba_; return *this; } inline unsigned int blue() const { return (rgba_>>16)&0xff; } inline unsigned int green() const { return (rgba_>>8)&0xff; } inline unsigned int red() const { return rgba_&0xff; } inline void set_red(unsigned int r) { rgba_ = (rgba_ & 0xffffff00) | (r&0xff); } inline void set_green(unsigned int g) { rgba_ = (rgba_ & 0xffff00ff) | ((g&0xff) << 8); } inline void set_blue(unsigned int b) { rgba_ = (rgba_ & 0xff00ffff) | ((b&0xff) << 16); } inline unsigned int alpha() const { return (rgba_>>24)&0xff; } inline unsigned int rgba() const { return rgba_; } inline void set_bgr(unsigned bgr) { rgba_ = (rgba_ & 0xff000000) | (bgr & 0xffffff); } inline bool operator==(Color const& other) const { return rgba_ == other.rgba_; } inline std::string to_string() const { std::stringstream ss; ss << "rgb (" << red() << "," << green() << "," << blue() <<")"; return ss.str(); } inline std::string to_hex_string() const { std::stringstream ss; ss << boost::format("#%1$02x%2$02x%3$02x") % red() % green() % blue(); return ss.str(); } }; } #endif //COLOR_HPP <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: color.hpp 39 2005-04-10 20:39:53Z pavlenko $ #ifndef COLOR_HPP #define COLOR_HPP #include "config.hpp" #include <sstream> namespace mapnik { class MAPNIK_DECL Color { private: unsigned int rgba_; public: Color() :rgba_(0xffffffff) {} Color(int red,int green,int blue,int alpha=0xff) : rgba_((alpha&0xff) << 24 | (blue&0xff) << 16 | (green&0xff) << 8 | red&0xff) {} explicit Color(int rgba) : rgba_(rgba) {} Color(const Color& rhs) : rgba_(rhs.rgba_) {} Color& operator=(const Color& rhs) { if (this==&rhs) return *this; rgba_=rhs.rgba_; return *this; } inline unsigned int blue() const { return (rgba_>>16)&0xff; } inline unsigned int green() const { return (rgba_>>8)&0xff; } inline unsigned int red() const { return rgba_&0xff; } inline void set_red(unsigned int r) { rgba_ = (rgba_ & 0xffffff00) | (r&0xff); } inline void set_green(unsigned int g) { rgba_ = (rgba_ & 0xffff00ff) | ((g&0xff) << 8); } inline void set_blue(unsigned int b) { rgba_ = (rgba_ & 0xff00ffff) | ((b&0xff) << 16); } inline unsigned int alpha() const { return (rgba_>>24)&0xff; } inline unsigned int rgba() const { return rgba_; } inline void set_bgr(unsigned bgr) { rgba_ = (rgba_ & 0xff000000) | (bgr & 0xffffff); } inline bool operator==(Color const& other) const { return rgba_ == other.rgba_; } inline std::string to_string() const { std::stringstream ss; ss << "rgb (" << red() << "," << green() << "," << blue() <<")"; return ss.str(); } }; } #endif //COLOR_HPP <commit_msg>implemented to_hex_color() method that returns #RRGGBB color representation. <commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: color.hpp 39 2005-04-10 20:39:53Z pavlenko $ #ifndef COLOR_HPP #define COLOR_HPP #include <boost/format.hpp> #include "config.hpp" #include <sstream> namespace mapnik { class MAPNIK_DECL Color { private: unsigned int rgba_; public: Color() :rgba_(0xffffffff) {} Color(int red,int green,int blue,int alpha=0xff) : rgba_((alpha&0xff) << 24 | (blue&0xff) << 16 | (green&0xff) << 8 | red&0xff) {} explicit Color(int rgba) : rgba_(rgba) {} Color(const Color& rhs) : rgba_(rhs.rgba_) {} Color& operator=(const Color& rhs) { if (this==&rhs) return *this; rgba_=rhs.rgba_; return *this; } inline unsigned int blue() const { return (rgba_>>16)&0xff; } inline unsigned int green() const { return (rgba_>>8)&0xff; } inline unsigned int red() const { return rgba_&0xff; } inline void set_red(unsigned int r) { rgba_ = (rgba_ & 0xffffff00) | (r&0xff); } inline void set_green(unsigned int g) { rgba_ = (rgba_ & 0xffff00ff) | ((g&0xff) << 8); } inline void set_blue(unsigned int b) { rgba_ = (rgba_ & 0xff00ffff) | ((b&0xff) << 16); } inline unsigned int alpha() const { return (rgba_>>24)&0xff; } inline unsigned int rgba() const { return rgba_; } inline void set_bgr(unsigned bgr) { rgba_ = (rgba_ & 0xff000000) | (bgr & 0xffffff); } inline bool operator==(Color const& other) const { return rgba_ == other.rgba_; } inline std::string to_string() const { std::stringstream ss; ss << "rgb (" << red() << "," << green() << "," << blue() <<")"; return ss.str(); } inline std::string to_hex_string() const { std::stringstream ss; ss << boost::format("#%1$02x%2$02x%3$02x") % red() % green() % blue(); return ss.str(); } }; } #endif //COLOR_HPP <|endoftext|>
<commit_before>//===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Collect the sequence of machine instructions for a basic block. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/BasicBlock.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/LeakDetector.h" #include <iostream> using namespace llvm; MachineBasicBlock::~MachineBasicBlock() { LeakDetector::removeGarbageObject(this); } // MBBs start out as #-1. When a MBB is added to a MachineFunction, it // gets the next available unique MBB number. If it is removed from a // MachineFunction, it goes back to being #-1. void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock* N) { assert(N->Parent == 0 && "machine instruction already in a basic block"); N->Parent = Parent; N->Number = Parent->addToMBBNumbering(N); LeakDetector::removeGarbageObject(N); } void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock* N) { assert(N->Parent != 0 && "machine instruction not in a basic block"); N->Parent->removeFromMBBNumbering(N->Number); N->Number = -1; N->Parent = 0; LeakDetector::addGarbageObject(N); } MachineInstr* ilist_traits<MachineInstr>::createNode() { MachineInstr* dummy = new MachineInstr(0, 0); LeakDetector::removeGarbageObject(dummy); return dummy; } void ilist_traits<MachineInstr>::addNodeToList(MachineInstr* N) { assert(N->parent == 0 && "machine instruction already in a basic block"); N->parent = parent; LeakDetector::removeGarbageObject(N); } void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr* N) { assert(N->parent != 0 && "machine instruction not in a basic block"); N->parent = 0; LeakDetector::addGarbageObject(N); } void ilist_traits<MachineInstr>::transferNodesFromList( iplist<MachineInstr, ilist_traits<MachineInstr> >& toList, ilist_iterator<MachineInstr> first, ilist_iterator<MachineInstr> last) { if (parent != toList.parent) for (; first != last; ++first) first->parent = toList.parent; } MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() { const TargetInstrInfo& TII = *getParent()->getTarget().getInstrInfo(); iterator I = end(); while (I != begin() && TII.isTerminatorInstr((--I)->getOpcode())); if (I != end() && !TII.isTerminatorInstr(I->getOpcode())) ++I; return I; } void MachineBasicBlock::dump() const { print(std::cerr); } void MachineBasicBlock::print(std::ostream &OS) const { if(!getParent()) { OS << "Can't print out MachineBasicBlock because parent MachineFunction is null\n"; return; } const BasicBlock *LBB = getBasicBlock(); if (LBB) OS << "\n" << LBB->getName() << " (" << (const void*)this << ", LLVM BB @" << (const void*) LBB << "):\n"; for (const_iterator I = begin(); I != end(); ++I) { OS << "\t"; I->print(OS, &getParent()->getTarget()); } } <commit_msg>Move method bodies that depend on <algorithm> from MBB.h to MBB.cpp<commit_after>//===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Collect the sequence of machine instructions for a basic block. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/BasicBlock.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/LeakDetector.h" #include <iostream> #include <algorithm> using namespace llvm; MachineBasicBlock::~MachineBasicBlock() { LeakDetector::removeGarbageObject(this); } // MBBs start out as #-1. When a MBB is added to a MachineFunction, it // gets the next available unique MBB number. If it is removed from a // MachineFunction, it goes back to being #-1. void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock* N) { assert(N->Parent == 0 && "machine instruction already in a basic block"); N->Parent = Parent; N->Number = Parent->addToMBBNumbering(N); LeakDetector::removeGarbageObject(N); } void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock* N) { assert(N->Parent != 0 && "machine instruction not in a basic block"); N->Parent->removeFromMBBNumbering(N->Number); N->Number = -1; N->Parent = 0; LeakDetector::addGarbageObject(N); } MachineInstr* ilist_traits<MachineInstr>::createNode() { MachineInstr* dummy = new MachineInstr(0, 0); LeakDetector::removeGarbageObject(dummy); return dummy; } void ilist_traits<MachineInstr>::addNodeToList(MachineInstr* N) { assert(N->parent == 0 && "machine instruction already in a basic block"); N->parent = parent; LeakDetector::removeGarbageObject(N); } void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr* N) { assert(N->parent != 0 && "machine instruction not in a basic block"); N->parent = 0; LeakDetector::addGarbageObject(N); } void ilist_traits<MachineInstr>::transferNodesFromList( iplist<MachineInstr, ilist_traits<MachineInstr> >& toList, ilist_iterator<MachineInstr> first, ilist_iterator<MachineInstr> last) { if (parent != toList.parent) for (; first != last; ++first) first->parent = toList.parent; } MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() { const TargetInstrInfo& TII = *getParent()->getTarget().getInstrInfo(); iterator I = end(); while (I != begin() && TII.isTerminatorInstr((--I)->getOpcode())); if (I != end() && !TII.isTerminatorInstr(I->getOpcode())) ++I; return I; } void MachineBasicBlock::dump() const { print(std::cerr); } void MachineBasicBlock::print(std::ostream &OS) const { if(!getParent()) { OS << "Can't print out MachineBasicBlock because parent MachineFunction" << " is null\n"; return; } const BasicBlock *LBB = getBasicBlock(); if (LBB) OS << "\n" << LBB->getName() << " (" << (const void*)this << ", LLVM BB @" << (const void*) LBB << "):\n"; for (const_iterator I = begin(); I != end(); ++I) { OS << "\t"; I->print(OS, &getParent()->getTarget()); } } void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ) { Successors.push_back(succ); succ->addPredecessor(this); } void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) { succ->removePredecessor(this); succ_iterator I = std::find(Successors.begin(), Successors.end(), succ); assert(I != Successors.end() && "Not a current successor!"); Successors.erase(I); } void MachineBasicBlock::removeSuccessor(succ_iterator I) { assert(I != Successors.end() && "Not a current successor!"); (*I)->removePredecessor(this); Successors.erase(I); } void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) { Predecessors.push_back(pred); } void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) { std::vector<MachineBasicBlock *>::iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred); assert(I != Predecessors.end() && "Pred is not a predecessor of this block!"); Predecessors.erase(I); } <|endoftext|>
<commit_before>//===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Collect the sequence of machine instructions for a basic block. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/BasicBlock.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/LeakDetector.h" #include <iostream> #include <algorithm> using namespace llvm; MachineBasicBlock::~MachineBasicBlock() { LeakDetector::removeGarbageObject(this); } // MBBs start out as #-1. When a MBB is added to a MachineFunction, it // gets the next available unique MBB number. If it is removed from a // MachineFunction, it goes back to being #-1. void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock* N) { assert(N->Parent == 0 && "machine instruction already in a basic block"); N->Parent = Parent; N->Number = Parent->addToMBBNumbering(N); LeakDetector::removeGarbageObject(N); } void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock* N) { assert(N->Parent != 0 && "machine instruction not in a basic block"); N->Parent->removeFromMBBNumbering(N->Number); N->Number = -1; N->Parent = 0; LeakDetector::addGarbageObject(N); } MachineInstr* ilist_traits<MachineInstr>::createSentinel() { MachineInstr* dummy = new MachineInstr(0, 0); LeakDetector::removeGarbageObject(dummy); return dummy; } void ilist_traits<MachineInstr>::addNodeToList(MachineInstr* N) { assert(N->parent == 0 && "machine instruction already in a basic block"); N->parent = parent; LeakDetector::removeGarbageObject(N); } void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr* N) { assert(N->parent != 0 && "machine instruction not in a basic block"); N->parent = 0; LeakDetector::addGarbageObject(N); } void ilist_traits<MachineInstr>::transferNodesFromList( iplist<MachineInstr, ilist_traits<MachineInstr> >& toList, ilist_iterator<MachineInstr> first, ilist_iterator<MachineInstr> last) { if (parent != toList.parent) for (; first != last; ++first) first->parent = toList.parent; } MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() { const TargetInstrInfo& TII = *getParent()->getTarget().getInstrInfo(); iterator I = end(); while (I != begin() && TII.isTerminatorInstr((--I)->getOpcode())); if (I != end() && !TII.isTerminatorInstr(I->getOpcode())) ++I; return I; } void MachineBasicBlock::dump() const { print(std::cerr); } void MachineBasicBlock::print(std::ostream &OS) const { if(!getParent()) { OS << "Can't print out MachineBasicBlock because parent MachineFunction" << " is null\n"; return; } const BasicBlock *LBB = getBasicBlock(); if (LBB) OS << "\n" << LBB->getName() << " (" << (const void*)this << ", LLVM BB @" << (const void*) LBB << "):\n"; for (const_iterator I = begin(); I != end(); ++I) { OS << "\t"; I->print(OS, &getParent()->getTarget()); } } void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ) { Successors.push_back(succ); succ->addPredecessor(this); } void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) { succ->removePredecessor(this); succ_iterator I = std::find(Successors.begin(), Successors.end(), succ); assert(I != Successors.end() && "Not a current successor!"); Successors.erase(I); } void MachineBasicBlock::removeSuccessor(succ_iterator I) { assert(I != Successors.end() && "Not a current successor!"); (*I)->removePredecessor(this); Successors.erase(I); } void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) { Predecessors.push_back(pred); } void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) { std::vector<MachineBasicBlock *>::iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred); assert(I != Predecessors.end() && "Pred is not a predecessor of this block!"); Predecessors.erase(I); } <commit_msg>print the machine CFG in the -print-machineinstrs dump<commit_after>//===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Collect the sequence of machine instructions for a basic block. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/BasicBlock.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/LeakDetector.h" #include <iostream> #include <algorithm> using namespace llvm; MachineBasicBlock::~MachineBasicBlock() { LeakDetector::removeGarbageObject(this); } // MBBs start out as #-1. When a MBB is added to a MachineFunction, it // gets the next available unique MBB number. If it is removed from a // MachineFunction, it goes back to being #-1. void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock* N) { assert(N->Parent == 0 && "machine instruction already in a basic block"); N->Parent = Parent; N->Number = Parent->addToMBBNumbering(N); LeakDetector::removeGarbageObject(N); } void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock* N) { assert(N->Parent != 0 && "machine instruction not in a basic block"); N->Parent->removeFromMBBNumbering(N->Number); N->Number = -1; N->Parent = 0; LeakDetector::addGarbageObject(N); } MachineInstr* ilist_traits<MachineInstr>::createSentinel() { MachineInstr* dummy = new MachineInstr(0, 0); LeakDetector::removeGarbageObject(dummy); return dummy; } void ilist_traits<MachineInstr>::addNodeToList(MachineInstr* N) { assert(N->parent == 0 && "machine instruction already in a basic block"); N->parent = parent; LeakDetector::removeGarbageObject(N); } void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr* N) { assert(N->parent != 0 && "machine instruction not in a basic block"); N->parent = 0; LeakDetector::addGarbageObject(N); } void ilist_traits<MachineInstr>::transferNodesFromList( iplist<MachineInstr, ilist_traits<MachineInstr> >& toList, ilist_iterator<MachineInstr> first, ilist_iterator<MachineInstr> last) { if (parent != toList.parent) for (; first != last; ++first) first->parent = toList.parent; } MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() { const TargetInstrInfo& TII = *getParent()->getTarget().getInstrInfo(); iterator I = end(); while (I != begin() && TII.isTerminatorInstr((--I)->getOpcode())); if (I != end() && !TII.isTerminatorInstr(I->getOpcode())) ++I; return I; } void MachineBasicBlock::dump() const { print(std::cerr); } void MachineBasicBlock::print(std::ostream &OS) const { if(!getParent()) { OS << "Can't print out MachineBasicBlock because parent MachineFunction" << " is null\n"; return; } const BasicBlock *LBB = getBasicBlock(); if (LBB) OS << "\n" << LBB->getName() << " (" << (const void*)this << ", LLVM BB @" << (const void*) LBB << "):\n"; for (const_iterator I = begin(); I != end(); ++I) { OS << "\t"; I->print(OS, &getParent()->getTarget()); } // Print the successors of this block according to the CFG. if (!succ_empty()) { OS << " Successors according to CFG:"; for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) OS << " " << *SI; OS << "\n"; } } void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ) { Successors.push_back(succ); succ->addPredecessor(this); } void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) { succ->removePredecessor(this); succ_iterator I = std::find(Successors.begin(), Successors.end(), succ); assert(I != Successors.end() && "Not a current successor!"); Successors.erase(I); } void MachineBasicBlock::removeSuccessor(succ_iterator I) { assert(I != Successors.end() && "Not a current successor!"); (*I)->removePredecessor(this); Successors.erase(I); } void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) { Predecessors.push_back(pred); } void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) { std::vector<MachineBasicBlock *>::iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred); assert(I != Predecessors.end() && "Pred is not a predecessor of this block!"); Predecessors.erase(I); } <|endoftext|>
<commit_before>//===-- PatchableFunction.cpp - Patchable prologues for LLVM -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements edits function bodies in place to support the // "patchable-function" attribute. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/Analysis.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/Target/TargetFrameLowering.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetSubtargetInfo.h" using namespace llvm; namespace { struct PatchableFunction : public MachineFunctionPass { static char ID; // Pass identification, replacement for typeid PatchableFunction() : MachineFunctionPass(ID) { initializePatchableFunctionPass(*PassRegistry::getPassRegistry()); } bool runOnMachineFunction(MachineFunction &F) override; MachineFunctionProperties getRequiredProperties() const override { return MachineFunctionProperties().set( MachineFunctionProperties::Property::AllVRegsAllocated); } }; } bool PatchableFunction::runOnMachineFunction(MachineFunction &MF) { if (!MF.getFunction()->hasFnAttribute("patchable-function")) return false; #ifndef NDEBUG Attribute PatchAttr = MF.getFunction()->getFnAttribute("patchable-function"); StringRef PatchType = PatchAttr.getValueAsString(); assert(PatchType == "prologue-short-redirect" && "Only possibility today!"); #endif auto &FirstMBB = *MF.begin(); auto &FirstMI = *FirstMBB.begin(); auto *TII = MF.getSubtarget().getInstrInfo(); auto MIB = BuildMI(FirstMBB, FirstMBB.begin(), FirstMI.getDebugLoc(), TII->get(TargetOpcode::PATCHABLE_OP)) .addImm(2) .addImm(FirstMI.getOpcode()); for (auto &MO : FirstMI.operands()) MIB.addOperand(MO); FirstMI.eraseFromParent(); MF.ensureAlignment(4); return true; } char PatchableFunction::ID = 0; char &llvm::PatchableFunctionID = PatchableFunction::ID; INITIALIZE_PASS(PatchableFunction, "patchable-function", "", false, false) <commit_msg>Add a description for the PatchableFunction pass; NFC<commit_after>//===-- PatchableFunction.cpp - Patchable prologues for LLVM -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements edits function bodies in place to support the // "patchable-function" attribute. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/Analysis.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/Target/TargetFrameLowering.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetSubtargetInfo.h" using namespace llvm; namespace { struct PatchableFunction : public MachineFunctionPass { static char ID; // Pass identification, replacement for typeid PatchableFunction() : MachineFunctionPass(ID) { initializePatchableFunctionPass(*PassRegistry::getPassRegistry()); } bool runOnMachineFunction(MachineFunction &F) override; MachineFunctionProperties getRequiredProperties() const override { return MachineFunctionProperties().set( MachineFunctionProperties::Property::AllVRegsAllocated); } }; } bool PatchableFunction::runOnMachineFunction(MachineFunction &MF) { if (!MF.getFunction()->hasFnAttribute("patchable-function")) return false; #ifndef NDEBUG Attribute PatchAttr = MF.getFunction()->getFnAttribute("patchable-function"); StringRef PatchType = PatchAttr.getValueAsString(); assert(PatchType == "prologue-short-redirect" && "Only possibility today!"); #endif auto &FirstMBB = *MF.begin(); auto &FirstMI = *FirstMBB.begin(); auto *TII = MF.getSubtarget().getInstrInfo(); auto MIB = BuildMI(FirstMBB, FirstMBB.begin(), FirstMI.getDebugLoc(), TII->get(TargetOpcode::PATCHABLE_OP)) .addImm(2) .addImm(FirstMI.getOpcode()); for (auto &MO : FirstMI.operands()) MIB.addOperand(MO); FirstMI.eraseFromParent(); MF.ensureAlignment(4); return true; } char PatchableFunction::ID = 0; char &llvm::PatchableFunctionID = PatchableFunction::ID; INITIALIZE_PASS(PatchableFunction, "patchable-function", "Implement the 'patchable-function' attribute", false, false) <|endoftext|>
<commit_before>/* Simulator for deterministic Turing machines. Based on the definition in Sipser's Introduction to the Theory of Computation. A state can be any integer. The start state is 0. Any negative state is an accept state. A symbol can be any string of non-whitespace characters. The blank symbol is _. Each line in the machine description specifies a transition: q a r b d where - q is the current state - a is the symbol read from the tape - r is the new state - b is the symbol written to the tape - d is a direction: L (left), N (no move), or R (right) The tape extends infinitely to the right, but not to the left. Initially, characters are read from stdin, all the way to EOF, and are encoded on the tape as 8-bit ASCII codes, most significant bit first. The remainder of the tape is filled with blank symbols (_). For example, "ABC" would be encoded as 010000010100001001000011___ ... The head starts on the first square of the tape. If the machine attempts to move the head to the left of the first square, the head remains on the first square. If the machine enters an accept state, the simulator exits with status 0. If a move is not possible, the simulator exists with status 1. In either case, the contents of the tape are written to stdout, using the same encoding as described above. Symbols that are neither 0 nor 1 are ignored, as are incomplete bytes. */ #include <iostream> #include <fstream> #include <sstream> #include <unordered_map> #include <string> #include <vector> #include <tuple> #include <unistd.h> using namespace std; typedef int state_t; typedef char symbol_t; const symbol_t BLANK = '_'; const symbol_t ONE = '1'; const symbol_t ZERO = '0'; class parse_error: public std::runtime_error { public: parse_error(const std::string &message): runtime_error(message) { } }; typedef std::tuple<state_t, symbol_t> condition; typedef std::tuple<state_t, symbol_t, int> action; namespace std { template<> struct hash<condition> { std::size_t operator()(const condition &c) const { return (std::get<0>(c) << 4) ^ std::get<1>(c); } }; } class dtm { std::unordered_map<condition, action> transitions; public: void add_transition(state_t q, symbol_t a, state_t r, symbol_t b, int d) { if (transitions.count(make_tuple(q,a)) > 0) throw std::runtime_error("machine is not deterministic at state " + to_string(q)); transitions.insert({make_tuple(q,a),make_tuple(r,b,d)}); } bool find_transition(state_t q, symbol_t a, state_t &r, symbol_t &b, int &d) const { auto it = transitions.find(make_tuple(q,a)); if (it != transitions.end()) { std::tie(r, b, d) = it->second; return true; } else { return false; } } }; state_t convert_state(const string &s) { size_t idx; state_t q = stoi(s, &idx); if (idx != s.size()) throw parse_error("invalid state: " + s); return q; } symbol_t convert_symbol(const string &s) { if (s.size() != 1) throw parse_error("invalid symbol: " + s); return s.at(0); } int convert_direction(const string &s) { if (s == "L") return -1; else if (s == "N") return 0; else if (s == "R") return 1; else throw parse_error("invalid direction: " + s); } void remove_comment(string &line) { auto pos = line.find("//"); if (pos != string::npos) line = line.substr(0, pos); } void split(const string &line, vector<string> &fields) { istringstream iss(line); string field; fields.clear(); while (iss >> field) fields.push_back(field); } void read_dtm(ifstream &is, dtm &m) { string line; while (getline(is, line)) { remove_comment(line); vector<string> fields; split(line, fields); if (fields.size() == 0) continue; try { condition cond; action act; if (fields.size() != 5) throw parse_error("could not read transition: " + line); m.add_transition(convert_state(fields[0]), convert_symbol(fields[1]), convert_state(fields[2]), convert_symbol(fields[3]), convert_direction(fields[4])); } catch (parse_error e) { cerr << e.what() << endl; exit(2); } } } bool run_dtm(const dtm &m, vector<symbol_t> &tape, int verbose=0) { state_t q = 0; vector<symbol_t>::size_type pos = 0, max_pos = 0; bool accept; long long int steps = 0; while (true) { while (pos+1 > tape.size()) tape.push_back(BLANK); while (tape.back() == BLANK && tape.size() > pos+1) tape.pop_back(); if (pos > max_pos) max_pos = pos; if (verbose >= 2) { cerr << q << " | "; for (vector<symbol_t>::size_type i=0; i<tape.size(); i++) { if (i == pos) cerr << "[" << tape[i] << "]"; else cerr << tape[i]; } cerr << endl; } if (q < 0) { accept = true; break; } int d; if (!m.find_transition(q, tape[pos], q, tape[pos], d)) { accept = false; break; } if (d == 1) ++pos; else if (d == -1 and pos > 0) --pos; ++steps; if (verbose == 1 && steps % 10000000 == 0) { cerr << "running: steps=" << steps << " cells=" << max_pos+1 << endl; } } if (verbose >= 1) { cerr << "halt: accept=" << accept << " steps=" << steps << " cells=" << max_pos+1 << endl; } return accept; } void encode_tape(const string &s, vector<symbol_t> &tape) { tape.clear(); for (auto c: s) { for (int i=7; i>=0; i--) tape.push_back(c & (1<<i) ? ONE : ZERO); } } void decode_tape(const vector<symbol_t> &tape, string &s) { s.clear(); char c = 0; int k = 0; for (const auto &a: tape) { if (a == ONE) { c = (c<<1) | 1; k++; } else if (a == ZERO) { c = (c<<1) | 0; k++; } if (k == 8) { s.push_back(c); c = 0; k = 0; } } } void usage() { cerr << "usage: tm [-n] [-v] <filename>\n"; exit(2); } int main(int argc, char *argv[]) { int verbose = 0; bool read_input = true; int ch; while ((ch = getopt(argc, argv, "nv")) != -1) { switch (ch) { case 'n': read_input = false; break; case 'v': verbose++; break; default: usage(); } } argc -= optind; argv += optind; if (argc != 1) usage(); ifstream is(argv[0]); dtm m; if (!is) { cerr << "could not open " << argv[0] << endl; return 1; } read_dtm(is, m); char c; string s; if (read_input) while (cin.get(c)) s.push_back(c); vector<symbol_t> tape; encode_tape(s, tape); if (run_dtm(m, tape, verbose)) { decode_tape(tape, s); cout << s; return 0; } else { return 1; } } <commit_msg>Include stdexcept in tm.cc<commit_after>/* Simulator for deterministic Turing machines. Based on the definition in Sipser's Introduction to the Theory of Computation. A state can be any integer. The start state is 0. Any negative state is an accept state. A symbol can be any string of non-whitespace characters. The blank symbol is _. Each line in the machine description specifies a transition: q a r b d where - q is the current state - a is the symbol read from the tape - r is the new state - b is the symbol written to the tape - d is a direction: L (left), N (no move), or R (right) The tape extends infinitely to the right, but not to the left. Initially, characters are read from stdin, all the way to EOF, and are encoded on the tape as 8-bit ASCII codes, most significant bit first. The remainder of the tape is filled with blank symbols (_). For example, "ABC" would be encoded as 010000010100001001000011___ ... The head starts on the first square of the tape. If the machine attempts to move the head to the left of the first square, the head remains on the first square. If the machine enters an accept state, the simulator exits with status 0. If a move is not possible, the simulator exists with status 1. In either case, the contents of the tape are written to stdout, using the same encoding as described above. Symbols that are neither 0 nor 1 are ignored, as are incomplete bytes. */ #include <fstream> #include <iostream> #include <sstream> #include <stdexcept> #include <string> #include <tuple> #include <unordered_map> #include <vector> #include <unistd.h> using namespace std; typedef int state_t; typedef char symbol_t; const symbol_t BLANK = '_'; const symbol_t ONE = '1'; const symbol_t ZERO = '0'; class parse_error: public std::runtime_error { public: parse_error(const std::string &message): runtime_error(message) { } }; typedef std::tuple<state_t, symbol_t> condition; typedef std::tuple<state_t, symbol_t, int> action; namespace std { template<> struct hash<condition> { std::size_t operator()(const condition &c) const { return (std::get<0>(c) << 4) ^ std::get<1>(c); } }; } class dtm { std::unordered_map<condition, action> transitions; public: void add_transition(state_t q, symbol_t a, state_t r, symbol_t b, int d) { if (transitions.count(make_tuple(q,a)) > 0) throw std::runtime_error("machine is not deterministic at state " + to_string(q)); transitions.insert({make_tuple(q,a),make_tuple(r,b,d)}); } bool find_transition(state_t q, symbol_t a, state_t &r, symbol_t &b, int &d) const { auto it = transitions.find(make_tuple(q,a)); if (it != transitions.end()) { std::tie(r, b, d) = it->second; return true; } else { return false; } } }; state_t convert_state(const string &s) { size_t idx; state_t q = stoi(s, &idx); if (idx != s.size()) throw parse_error("invalid state: " + s); return q; } symbol_t convert_symbol(const string &s) { if (s.size() != 1) throw parse_error("invalid symbol: " + s); return s.at(0); } int convert_direction(const string &s) { if (s == "L") return -1; else if (s == "N") return 0; else if (s == "R") return 1; else throw parse_error("invalid direction: " + s); } void remove_comment(string &line) { auto pos = line.find("//"); if (pos != string::npos) line = line.substr(0, pos); } void split(const string &line, vector<string> &fields) { istringstream iss(line); string field; fields.clear(); while (iss >> field) fields.push_back(field); } void read_dtm(ifstream &is, dtm &m) { string line; while (getline(is, line)) { remove_comment(line); vector<string> fields; split(line, fields); if (fields.size() == 0) continue; try { condition cond; action act; if (fields.size() != 5) throw parse_error("could not read transition: " + line); m.add_transition(convert_state(fields[0]), convert_symbol(fields[1]), convert_state(fields[2]), convert_symbol(fields[3]), convert_direction(fields[4])); } catch (parse_error e) { cerr << e.what() << endl; exit(2); } } } bool run_dtm(const dtm &m, vector<symbol_t> &tape, int verbose=0) { state_t q = 0; vector<symbol_t>::size_type pos = 0, max_pos = 0; bool accept; long long int steps = 0; while (true) { while (pos+1 > tape.size()) tape.push_back(BLANK); while (tape.back() == BLANK && tape.size() > pos+1) tape.pop_back(); if (pos > max_pos) max_pos = pos; if (verbose >= 2) { cerr << q << " | "; for (vector<symbol_t>::size_type i=0; i<tape.size(); i++) { if (i == pos) cerr << "[" << tape[i] << "]"; else cerr << tape[i]; } cerr << endl; } if (q < 0) { accept = true; break; } int d; if (!m.find_transition(q, tape[pos], q, tape[pos], d)) { accept = false; break; } if (d == 1) ++pos; else if (d == -1 and pos > 0) --pos; ++steps; if (verbose == 1 && steps % 10000000 == 0) { cerr << "running: steps=" << steps << " cells=" << max_pos+1 << endl; } } if (verbose >= 1) { cerr << "halt: accept=" << accept << " steps=" << steps << " cells=" << max_pos+1 << endl; } return accept; } void encode_tape(const string &s, vector<symbol_t> &tape) { tape.clear(); for (auto c: s) { for (int i=7; i>=0; i--) tape.push_back(c & (1<<i) ? ONE : ZERO); } } void decode_tape(const vector<symbol_t> &tape, string &s) { s.clear(); char c = 0; int k = 0; for (const auto &a: tape) { if (a == ONE) { c = (c<<1) | 1; k++; } else if (a == ZERO) { c = (c<<1) | 0; k++; } if (k == 8) { s.push_back(c); c = 0; k = 0; } } } void usage() { cerr << "usage: tm [-n] [-v] <filename>\n"; exit(2); } int main(int argc, char *argv[]) { int verbose = 0; bool read_input = true; int ch; while ((ch = getopt(argc, argv, "nv")) != -1) { switch (ch) { case 'n': read_input = false; break; case 'v': verbose++; break; default: usage(); } } argc -= optind; argv += optind; if (argc != 1) usage(); ifstream is(argv[0]); dtm m; if (!is) { cerr << "could not open " << argv[0] << endl; return 1; } read_dtm(is, m); char c; string s; if (read_input) while (cin.get(c)) s.push_back(c); vector<symbol_t> tape; encode_tape(s, tape); if (run_dtm(m, tape, verbose)) { decode_tape(tape, s); cout << s; return 0; } else { return 1; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2013, Christian Loose * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "provider.h" #include <QDebug> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QRegExp> #include <QUrl> #include <QUrlQuery> #include "request.h" namespace qoembed { /* information comes from https://github.com/panzi/oembedendpoints */ static QMap<QString, QString> InitUrlSchemeToEndpoints() { QMap<QString, QString> urlSchemeToEndpoints; // Youtube urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/watch.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/v/.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://youtu\\.be/.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/user/.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/[^#?/]+#[^#?/]+/.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://m\\.youtube\\.com/index.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/profile.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/view_play_list.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/playlist.+$"), QStringLiteral("http://www.youtube.com/oembed")); // Flickr urlSchemeToEndpoints.insert(QStringLiteral("^http://[-\\w]+\\.flickr\\.com/photos/.+$"), QStringLiteral("http://www.flickr.com/services/oembed/")); urlSchemeToEndpoints.insert(QStringLiteral("^http://flic\\.kr\\.com/.+$"), QStringLiteral("http://www.flickr.com/services/oembed/")); // Slideshare urlSchemeToEndpoints.insert(QStringLiteral("^http://www\\.slideshare\\.net/.+$"), QStringLiteral("https://www.slideshare.net/api/oembed/2")); // Twitter urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://twitter\\.com/(?:#!)?[^#?/]+/status/.+$"), QStringLiteral("https://api.twitter.com/1/statuses/oembed.{format}")); return urlSchemeToEndpoints; } const QMap<QString, QString> Provider::urlSchemeToEndpoints = InitUrlSchemeToEndpoints(); class ProviderPrivate { public: ProviderPrivate() : manager(0) {} ~ProviderPrivate() { delete manager; } QString endpoint; QNetworkAccessManager *manager; }; Provider::Provider(const QString &endpoint, QObject *parent) : QObject(parent), d(new ProviderPrivate) { setObjectName("Provider for " + endpoint); d->endpoint = endpoint; d->manager = new QNetworkAccessManager(); connect(d->manager, SIGNAL(finished(QNetworkReply*)), SLOT(replyFinished(QNetworkReply*))); } Provider::~Provider() { delete d; } void Provider::setEndpoint(const QString &endpoint) { d->endpoint = endpoint; } QString Provider::endpoint() const { return d->endpoint; } void Provider::fetch(const Request &request) { QUrl requestUrl(endpoint()); requestUrl.setQuery(request.createQuery()); qDebug() << request.url() << requestUrl; d->manager->get(QNetworkRequest(requestUrl)); } Provider *Provider::createForUrl(const QUrl &url, QObject *parent) { QMapIterator<QString, QString> it(urlSchemeToEndpoints); while (it.hasNext()) { it.next(); QRegExp rx(it.key()); if (rx.exactMatch(url.toString())) { return new Provider(it.value(), parent); } } return 0; } void Provider::replyFinished(QNetworkReply *reply) { if (reply->error() == QNetworkReply::NoError) { QVariant contentType = reply->header(QNetworkRequest::ContentTypeHeader); QByteArray contentData = reply->readAll(); emit finished(contentType.toString(), contentData); } else { emit error(reply->error(), reply->errorString()); } reply->deleteLater(); } } // namespace qoembed <commit_msg>Add oembed providers: GitHub, Kickstarter, Vimeo<commit_after>/* * Copyright (c) 2013, Christian Loose * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "provider.h" #include <QDebug> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QRegExp> #include <QUrl> #include <QUrlQuery> #include "request.h" namespace qoembed { /* information comes from https://github.com/panzi/oembedendpoints */ static QMap<QString, QString> InitUrlSchemeToEndpoints() { QMap<QString, QString> urlSchemeToEndpoints; // Youtube urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/watch.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/v/.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://youtu\\.be/.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/user/.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/[^#?/]+#[^#?/]+/.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://m\\.youtube\\.com/index.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/profile.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/view_play_list.+$"), QStringLiteral("http://www.youtube.com/oembed")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:[-\\w]+\\.)?youtube\\.com/playlist.+$"), QStringLiteral("http://www.youtube.com/oembed")); // Flickr urlSchemeToEndpoints.insert(QStringLiteral("^http://[-\\w]+\\.flickr\\.com/photos/.+$"), QStringLiteral("http://www.flickr.com/services/oembed/")); urlSchemeToEndpoints.insert(QStringLiteral("^http://flic\\.kr\\.com/.+$"), QStringLiteral("http://www.flickr.com/services/oembed/")); // GitHub urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://gist\\.github\\.com/.+$"), QStringLiteral("https://github.com/api/oembed")); // Kickstarter urlSchemeToEndpoints.insert(QStringLiteral("^http://[-\\w]+\\.kickstarter\\.com/projects/.+$"), QStringLiteral("http://www.kickstarter.com/services/oembed")); // Slideshare urlSchemeToEndpoints.insert(QStringLiteral("^http://www\\.slideshare\\.net/.+$"), QStringLiteral("https://www.slideshare.net/api/oembed/2")); // Twitter urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://twitter\\.com/(?:#!)?[^#?/]+/status/.+$"), QStringLiteral("https://api.twitter.com/1/statuses/oembed.{format}")); // Vimeo urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://(?:www\\.)?vimeo\\.com/.+$"), QStringLiteral("http://www.vimeo.com/api/oembed.{format}")); urlSchemeToEndpoints.insert(QStringLiteral("^http(?:s)?://player\\.vimeo\\.com/.+$"), QStringLiteral("http://www.vimeo.com/api/oembed.{format}")); return urlSchemeToEndpoints; } const QMap<QString, QString> Provider::urlSchemeToEndpoints = InitUrlSchemeToEndpoints(); class ProviderPrivate { public: ProviderPrivate() : manager(0) {} ~ProviderPrivate() { delete manager; } QString endpoint; QNetworkAccessManager *manager; }; Provider::Provider(const QString &endpoint, QObject *parent) : QObject(parent), d(new ProviderPrivate) { setObjectName("Provider for " + endpoint); d->endpoint = endpoint; d->manager = new QNetworkAccessManager(); connect(d->manager, SIGNAL(finished(QNetworkReply*)), SLOT(replyFinished(QNetworkReply*))); } Provider::~Provider() { delete d; } void Provider::setEndpoint(const QString &endpoint) { d->endpoint = endpoint; } QString Provider::endpoint() const { return d->endpoint; } void Provider::fetch(const Request &request) { QUrl requestUrl(endpoint()); requestUrl.setQuery(request.createQuery()); qDebug() << request.url() << requestUrl; d->manager->get(QNetworkRequest(requestUrl)); } Provider *Provider::createForUrl(const QUrl &url, QObject *parent) { QMapIterator<QString, QString> it(urlSchemeToEndpoints); while (it.hasNext()) { it.next(); QRegExp rx(it.key()); if (rx.exactMatch(url.toString())) { return new Provider(it.value(), parent); } } return 0; } void Provider::replyFinished(QNetworkReply *reply) { if (reply->error() == QNetworkReply::NoError) { QVariant contentType = reply->header(QNetworkRequest::ContentTypeHeader); QByteArray contentData = reply->readAll(); emit finished(contentType.toString(), contentData); } else { emit error(reply->error(), reply->errorString()); } reply->deleteLater(); } } // namespace qoembed <|endoftext|>
<commit_before>/* * Copyright (c) 2012, Dennis Hedback * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <iterator> #include <set> #include <string> #include <vector> typedef std::set<std::string> Set; typedef std::vector<std::string> Tuple; typedef std::set<Tuple> Product; typedef std::vector<Set> Generator; typedef std::set<Generator> Quotient; struct Options { bool verbose; }; static Options opts; #define VPRINT(x) if (opts.verbose) { std::cerr << x << std::endl; } Product read_tuples(void) { Product prod; Tuple current_tuple; std::string current_elem; for (std::istreambuf_iterator<char> it(std::cin), end; it != end; it++) { char c = *it; if (c == ',' || c == '\n') { current_tuple.push_back(current_elem); current_elem.clear(); if (c == '\n') { prod.insert(current_tuple); current_tuple.clear(); } } else { current_elem += c; } } return prod; } unsigned int product_cardinality(Generator gen) { unsigned int cardinality = 1; for (Generator::iterator it = gen.begin(); it != gen.end(); it++) cardinality *= (*it).size(); return cardinality; } Product cartesian_product(Generator gen) { Product prod; unsigned int counters[gen.size()]; size_t gen_size; gen_size = gen.size(); for (unsigned int i = 0; i < gen_size; i++) counters[i] = 0; for (unsigned int i = 0; i < product_cardinality(gen); i++) { Tuple current_tuple; for (unsigned int j = 0; j < gen_size; j++) { Set current_set = gen[j]; unsigned int k = 0; for (Set::iterator it = current_set.begin(); it != current_set.end(); k++, it++) if (k == counters[j]) current_tuple.push_back(*it); } prod.insert(current_tuple); for (unsigned int j = 0; j < gen_size; j++) { counters[j]++; if (counters[j] > gen[j].size() - 1) counters[j] = 0; else break; } } return prod; } Generator init_generator(size_t size) { Generator gen; for (unsigned int i = 0; i < size; i++) gen.push_back(Set()); return gen; } Generator reference_generator(Product prod) { Generator ref_generator; if (prod.size() > 0) ref_generator = init_generator((*prod.begin()).size()); for (Product::iterator pi = prod.begin(); pi != prod.end(); pi++) { unsigned int i = 0; for (Tuple::const_iterator ti = (*pi).begin(); ti != (*pi).end(); i++, ti++) { ref_generator[i].insert(*ti); } } return ref_generator; } bool product_contains(Product &prod, Tuple tuple) { return prod.find(tuple) != prod.end(); } Quotient generating_sets(Product prod) { Quotient quot; Product ref_prod = prod; for (unsigned int num_generators = 1, inserted = 0; prod.size() > 0; num_generators++) { Generator current_generator = init_generator((*prod.begin()).size()); Product to_erase; for (Product::iterator pi = prod.begin(); pi != prod.end();) { Tuple current_tuple = (*pi); Generator tmp = current_generator; size_t tup_size = current_tuple.size(); for (unsigned int i = 0; i < tup_size; i++) { tmp[i].insert(current_tuple[i]); } Product tmp_product = cartesian_product(tmp); for (Product::iterator tmpi = tmp_product.begin(); tmpi != tmp_product.end(); tmpi++) { if (!product_contains(ref_prod, *tmpi)) { ++pi; // FIXME: Go away ugly goto, go away! goto foo; } } current_generator = tmp; prod.erase(pi++); VPRINT(++inserted << " tuples inserted into " << num_generators << " generators "); // FIXME: Ugly "expected primary-expression before '}' token" fix foo: if (1 == 2) break; } quot.insert(current_generator); } return quot; } void print_quotient(Quotient quot) { for (Quotient::iterator qi = quot.begin(); qi != quot.end(); qi++) { for (Generator::const_iterator gi = (*qi).begin(); gi != (*qi).end(); gi++) { for (Set::iterator si = (*gi).begin(); si != (*gi).end(); si++) { std::cout << *si; if (++si != (*gi).end()) std::cout << ','; si--; } std::cout << std::endl; } std::cout << "%%" << std::endl; } } int main(int argc, char *argv[]) { opts.verbose = true; Product prod = read_tuples(); Quotient quot = generating_sets(prod); print_quotient(quot); return 0; } <commit_msg>Shaved off another 2 seconds<commit_after>/* * Copyright (c) 2012, Dennis Hedback * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <iostream> #include <iterator> #include <set> #include <string> #include <vector> typedef std::set<std::string> Set; typedef std::vector<std::string> Tuple; typedef std::set<Tuple> Product; typedef std::vector<Set> Generator; typedef std::set<Generator> Quotient; struct Options { bool verbose; }; static Options opts; #define VPRINT(x) if (opts.verbose) { std::cerr << x << std::endl; } void read_tuples(Product &prod) { VPRINT("Reading input..."); Tuple current_tuple; std::string current_elem; for (std::istreambuf_iterator<char> it(std::cin), end; it != end; it++) { char c = *it; if (c == ',' || c == '\n') { current_tuple.push_back(current_elem); current_elem.clear(); if (c == '\n') { prod.insert(current_tuple); current_tuple.clear(); } } else { current_elem += c; } } } unsigned int product_cardinality(Generator &gen) { unsigned int cardinality = 1; for (Generator::iterator it = gen.begin(); it != gen.end(); it++) cardinality *= it->size(); return cardinality; } Product cartesian_product(Generator &gen) { Product prod; size_t gen_size = gen.size(); unsigned int counters[gen_size]; for (unsigned int i = 0; i < gen_size; i++) counters[i] = 0; for (unsigned int i = 0; i < product_cardinality(gen); i++) { Tuple current_tuple; for (unsigned int j = 0; j < gen_size; j++) { Set current_set = gen[j]; unsigned int k = 0; for (Set::iterator it = current_set.begin(); it != current_set.end(); k++, it++) if (k == counters[j]) current_tuple.push_back(*it); } prod.insert(current_tuple); for (unsigned int j = 0; j < gen_size; j++) { counters[j]++; if (counters[j] > gen[j].size() - 1) counters[j] = 0; else break; } } return prod; } void init_generator(Generator &gen, size_t size) { for (unsigned int i = 0; i < size; i++) gen.push_back(Set()); } bool product_contains(Product &prod, Tuple tuple) { return prod.find(tuple) != prod.end(); } void print_generator(Generator &gen) { for (Generator::const_iterator gi = gen.begin(); gi != gen.end(); gi++) { for (Set::iterator si = gi->begin(); si != gi->end(); si++) { std::cout << *si; if (++si != gi->end()) std::cout << ','; si--; } std::cout << '\n'; } std::cout << "%%\n"; } void generating_sets(Product &prod) { Product ref_prod = prod; for (unsigned int num_generators = 1, inserted = 0; prod.size() > 0; num_generators++) { Generator current_generator; init_generator(current_generator, prod.begin()->size()); for (Product::iterator pi = prod.begin(); pi != prod.end();) { Tuple current_tuple = *pi; Generator tmp = current_generator; size_t tup_size = current_tuple.size(); for (unsigned int i = 0; i < tup_size; i++) { tmp[i].insert(current_tuple[i]); } Product tmp_product = cartesian_product(tmp); for (Product::iterator tmpi = tmp_product.begin(); tmpi != tmp_product.end(); tmpi++) { if (!product_contains(ref_prod, *tmpi)) { ++pi; // FIXME: Go away ugly goto, go away! goto foo; } } current_generator = tmp; prod.erase(pi++); VPRINT(++inserted << " tuples inserted into " << num_generators << " generators "); // FIXME: Ugly "expected primary-expression before '}' token" fix foo: if (1 == 2) break; } print_generator(current_generator); } } int main(int argc, char *argv[]) { opts.verbose = false; Product prod; read_tuples(prod); generating_sets(prod); return 0; } <|endoftext|>
<commit_before>#ifndef ENTT_REGISTRY_HPP #define ENTT_REGISTRY_HPP #include <tuple> #include <vector> #include <bitset> #include <utility> #include <cstddef> #include <iterator> #include <cassert> #include <type_traits> #include "sparse_set.hpp" #include "ident.hpp" namespace entt { template<typename, std::size_t...> class View; template<typename Pool, std::size_t Ident, std::size_t... Other> class View<Pool, Ident, Other...> final { using pool_type = Pool; using mask_type = std::bitset<std::tuple_size<Pool>::value + 1>; using underlying_iterator_type = typename std::tuple_element_t<Ident, Pool>::iterator_type; class ViewIterator; public: using iterator_type = ViewIterator; using entity_type = typename std::tuple_element_t<Ident, Pool>::index_type; using size_type = typename std::tuple_element_t<Ident, Pool>::size_type; private: class ViewIterator { inline bool valid() const noexcept { return ((mask[*begin] & bitmask) == bitmask); } public: using value_type = entity_type; ViewIterator(underlying_iterator_type begin, underlying_iterator_type end, const mask_type &bitmask, const mask_type *mask) noexcept : begin{begin}, end{end}, bitmask{bitmask}, mask{mask} { if(begin != end && !valid()) { ++(*this); } } ViewIterator & operator++() noexcept { ++begin; while(begin != end && !valid()) { ++begin; } return *this; } ViewIterator operator++(int) noexcept { ViewIterator orig = *this; return ++(*this), orig; } bool operator==(const ViewIterator &other) const noexcept { return other.begin == begin; } bool operator!=(const ViewIterator &other) const noexcept { return !(*this == other); } value_type operator*() const noexcept { return *begin; } private: underlying_iterator_type begin; underlying_iterator_type end; const mask_type bitmask; const mask_type *mask; }; template<std::size_t Idx> void prefer(size_type &size) noexcept { auto &&cpool = std::get<Idx>(*pool); auto sz = cpool.size(); if(sz < size) { from = cpool.begin(); to = cpool.end(); size = sz; } } public: explicit View(const pool_type *pool, const mask_type *mask) noexcept : from{std::get<Ident>(*pool).begin()}, to{std::get<Ident>(*pool).end()}, pool{pool}, mask{mask} { using accumulator_type = int[]; size_type size = std::get<Ident>(*pool).size(); bitmask.set(Ident); accumulator_type types = { 0, (bitmask.set(Other), 0)... }; accumulator_type pref = { 0, (prefer<Other>(size), 0)... }; (void)types, (void)pref; } iterator_type begin() const noexcept { return ViewIterator{from, to, bitmask, mask}; } iterator_type end() const noexcept { return ViewIterator{to, to, bitmask, mask}; } void reset() noexcept { using accumulator_type = int[]; auto &&cpool = std::get<Ident>(*pool); from = cpool.begin(); to = cpool.end(); size_type size = cpool.size(); accumulator_type accumulator = { 0, (prefer<Other>(size), 0)... }; (void)accumulator; } private: underlying_iterator_type from; underlying_iterator_type to; const pool_type *pool; const mask_type *mask; mask_type bitmask; }; template<typename Pool, std::size_t Ident> class View<Pool, Ident> final { using pool_type = std::tuple_element_t<Ident, Pool>; public: using iterator_type = typename pool_type::iterator_type; using entity_type = typename pool_type::index_type; using size_type = typename pool_type::size_type; using raw_type = typename pool_type::type; explicit View(const Pool *pool) noexcept : pool{&std::get<Ident>(*pool)} {} raw_type * raw() noexcept { return pool->raw(); } const raw_type * raw() const noexcept { return pool->raw(); } const entity_type * data() const noexcept { return pool->data(); } size_type size() const noexcept { return pool->size(); } iterator_type begin() const noexcept { return pool->begin(); } iterator_type end() const noexcept { return pool->end(); } private: const pool_type *pool; }; template<typename Entity, typename... Component> class Registry { using pool_type = std::tuple<SparseSet<Entity, Component>...>; using mask_type = std::bitset<sizeof...(Component)+1>; static constexpr auto validity_bit = sizeof...(Component); public: using entity_type = Entity; using size_type = typename std::vector<mask_type>::size_type; template<typename... Comp> using view_type = View<pool_type, ident<Component...>.template get<Comp>()...>; private: template<typename Comp> void clone(entity_type to, entity_type from) { constexpr auto index = ident<Component...>.template get<Comp>(); if(entities[from].test(index)) { assign<Comp>(to, std::get<index>(pool).get(from)); } } template<typename Comp> void sync(entity_type to, entity_type from) { constexpr auto index = ident<Component...>.template get<Comp>(); bool src = entities[from].test(index); bool dst = entities[to].test(index); if(src && dst) { copy<Comp>(to, from); } else if(src) { clone<Comp>(to, from); } else if(dst) { remove<Comp>(to); } } public: explicit Registry() = default; ~Registry() = default; Registry(const Registry &) = delete; Registry(Registry &&) = delete; Registry & operator=(const Registry &) = delete; Registry & operator=(Registry &&) = delete; template<typename Comp> size_type size() const noexcept { constexpr auto index = ident<Component...>.template get<Comp>(); return std::get<index>(pool).size(); } size_type size() const noexcept { return entities.size() - available.size(); } template<typename Comp> size_type capacity() const noexcept { constexpr auto index = ident<Component...>.template get<Comp>(); return std::get<index>(pool).capacity(); } size_type capacity() const noexcept { return entities.size(); } template<typename Comp> bool empty() const noexcept { constexpr auto index = ident<Component...>.template get<Comp>(); return std::get<index>(pool).empty(); } bool empty() const noexcept { return entities.empty(); } bool valid(entity_type entity) const noexcept { return (entity < entities.size() && entities[entity].test(validity_bit)); } template<typename... Comp> entity_type create() noexcept { using accumulator_type = int[]; auto entity = create(); accumulator_type accumulator = { 0, (assign<Comp>(entity), 0)... }; (void)accumulator; return entity; } entity_type create() noexcept { entity_type entity; if(available.empty()) { entity = entity_type(entities.size()); entities.emplace_back(); } else { entity = available.back(); available.pop_back(); } entities[entity].set(validity_bit); return entity; } void destroy(entity_type entity) { assert(valid(entity)); using accumulator_type = int[]; accumulator_type accumulator = { 0, (reset<Component>(entity), 0)... }; available.push_back(entity); entities[entity].reset(); (void)accumulator; } template<typename Comp, typename... Args> Comp & assign(entity_type entity, Args... args) { assert(valid(entity)); constexpr auto index = ident<Component...>.template get<Comp>(); entities[entity].set(index); return std::get<index>(pool).construct(entity, args...); } template<typename Comp> void remove(entity_type entity) { assert(valid(entity)); constexpr auto index = ident<Component...>.template get<Comp>(); entities[entity].reset(index); std::get<index>(pool).destroy(entity); } template<typename... Comp> bool has(entity_type entity) const noexcept { assert(valid(entity)); using accumulator_type = bool[]; bool all = true; auto &mask = entities[entity]; accumulator_type accumulator = { true, (all = all && mask.test(ident<Component...>.template get<Comp>()))... }; (void)accumulator; return all; } template<typename Comp> const Comp & get(entity_type entity) const noexcept { assert(valid(entity)); constexpr auto index = ident<Component...>.template get<Comp>(); return std::get<index>(pool).get(entity); } template<typename Comp> Comp & get(entity_type entity) noexcept { assert(valid(entity)); constexpr auto index = ident<Component...>.template get<Comp>(); return std::get<index>(pool).get(entity); } template<typename Comp, typename... Args> Comp & replace(entity_type entity, Args... args) { assert(valid(entity)); constexpr auto index = ident<Component...>.template get<Comp>(); return (std::get<index>(pool).get(entity) = Comp{args...}); } template<typename Comp, typename... Args> Comp & accomodate(entity_type entity, Args... args) { assert(valid(entity)); constexpr auto index = ident<Component...>.template get<Comp>(); return (entities[entity].test(index) ? this->template replace<Comp>(entity, std::forward<Args>(args)...) : this->template assign<Comp>(entity, std::forward<Args>(args)...)); } entity_type clone(entity_type from) { assert(valid(from)); using accumulator_type = int[]; auto to = create(); accumulator_type accumulator = { 0, (clone<Component>(to, from), 0)... }; (void)accumulator; return to; } template<typename Comp> Comp & copy(entity_type to, entity_type from) { assert(valid(to)); assert(valid(from)); constexpr auto index = ident<Component...>.template get<Comp>(); auto &&cpool = std::get<index>(pool); return (cpool.get(to) = cpool.get(from)); } void copy(entity_type to, entity_type from) { assert(valid(to)); assert(valid(from)); using accumulator_type = int[]; accumulator_type accumulator = { 0, (sync<Component>(to, from), 0)... }; (void)accumulator; } template<typename Comp> void swap(entity_type lhs, entity_type rhs) { assert(valid(lhs)); assert(valid(rhs)); std::get<ident<Component...>.template get<Comp>()>(pool).swap(lhs, rhs); } template<typename Comp, typename Compare> void sort(Compare compare) { std::get<ident<Component...>.template get<Comp>()>(pool).sort(std::move(compare)); } template<typename To, typename From> void sort() { auto &&to = std::get<ident<Component...>.template get<To>()>(pool); auto &&from = std::get<ident<Component...>.template get<From>()>(pool); to.respect(from); } template<typename Comp> void reset(entity_type entity) { assert(valid(entity)); constexpr auto index = ident<Component...>.template get<Comp>(); if(entities[entity].test(index)) { remove<Comp>(entity); } } template<typename Comp> void reset() { constexpr auto index = ident<Component...>.template get<Comp>(); for(entity_type entity = 0, last = entity_type(entities.size()); entity < last; ++entity) { if(entities[entity].test(index)) { remove<Comp>(entity); } } } void reset() { using accumulator_type = int[]; accumulator_type acc = { 0, (std::get<ident<Component...>.template get<Component>()>(pool).reset(), 0)... }; entities.clear(); available.clear(); (void)acc; } template<typename... Comp> std::enable_if_t<(sizeof...(Comp) == 1), view_type<Comp...>> view() noexcept { return view_type<Comp...>{&pool}; } template<typename... Comp> std::enable_if_t<(sizeof...(Comp) > 1), view_type<Comp...>> view() noexcept { return view_type<Comp...>{&pool, entities.data()}; } private: std::vector<mask_type> entities; std::vector<entity_type> available; pool_type pool; }; template<typename... Component> using DefaultRegistry = Registry<std::uint32_t, Component...>; } #endif // ENTT_REGISTRY_HPP <commit_msg>cleanup<commit_after>#ifndef ENTT_REGISTRY_HPP #define ENTT_REGISTRY_HPP #include <tuple> #include <vector> #include <bitset> #include <utility> #include <cstddef> #include <cassert> #include <type_traits> #include "sparse_set.hpp" #include "ident.hpp" namespace entt { template<typename, std::size_t...> class View; template<typename Pool, std::size_t Ident, std::size_t... Other> class View<Pool, Ident, Other...> final { using pool_type = Pool; using mask_type = std::bitset<std::tuple_size<Pool>::value + 1>; using underlying_iterator_type = typename std::tuple_element_t<Ident, Pool>::iterator_type; class ViewIterator; public: using iterator_type = ViewIterator; using entity_type = typename std::tuple_element_t<Ident, Pool>::index_type; using size_type = typename std::tuple_element_t<Ident, Pool>::size_type; private: class ViewIterator { inline bool valid() const noexcept { return ((mask[*begin] & bitmask) == bitmask); } public: using value_type = entity_type; ViewIterator(underlying_iterator_type begin, underlying_iterator_type end, const mask_type &bitmask, const mask_type *mask) noexcept : begin{begin}, end{end}, bitmask{bitmask}, mask{mask} { if(begin != end && !valid()) { ++(*this); } } ViewIterator & operator++() noexcept { ++begin; while(begin != end && !valid()) { ++begin; } return *this; } ViewIterator operator++(int) noexcept { ViewIterator orig = *this; return ++(*this), orig; } bool operator==(const ViewIterator &other) const noexcept { return other.begin == begin; } bool operator!=(const ViewIterator &other) const noexcept { return !(*this == other); } value_type operator*() const noexcept { return *begin; } private: underlying_iterator_type begin; underlying_iterator_type end; const mask_type bitmask; const mask_type *mask; }; template<std::size_t Idx> void prefer(size_type &size) noexcept { auto &&cpool = std::get<Idx>(*pool); auto sz = cpool.size(); if(sz < size) { from = cpool.begin(); to = cpool.end(); size = sz; } } public: explicit View(const pool_type *pool, const mask_type *mask) noexcept : from{std::get<Ident>(*pool).begin()}, to{std::get<Ident>(*pool).end()}, pool{pool}, mask{mask} { using accumulator_type = int[]; size_type size = std::get<Ident>(*pool).size(); bitmask.set(Ident); accumulator_type types = { 0, (bitmask.set(Other), 0)... }; accumulator_type pref = { 0, (prefer<Other>(size), 0)... }; (void)types, (void)pref; } iterator_type begin() const noexcept { return ViewIterator{from, to, bitmask, mask}; } iterator_type end() const noexcept { return ViewIterator{to, to, bitmask, mask}; } void reset() noexcept { using accumulator_type = int[]; auto &&cpool = std::get<Ident>(*pool); from = cpool.begin(); to = cpool.end(); size_type size = cpool.size(); accumulator_type accumulator = { 0, (prefer<Other>(size), 0)... }; (void)accumulator; } private: underlying_iterator_type from; underlying_iterator_type to; const pool_type *pool; const mask_type *mask; mask_type bitmask; }; template<typename Pool, std::size_t Ident> class View<Pool, Ident> final { using pool_type = std::tuple_element_t<Ident, Pool>; public: using iterator_type = typename pool_type::iterator_type; using entity_type = typename pool_type::index_type; using size_type = typename pool_type::size_type; using raw_type = typename pool_type::type; explicit View(const Pool *pool) noexcept : pool{&std::get<Ident>(*pool)} {} raw_type * raw() noexcept { return pool->raw(); } const raw_type * raw() const noexcept { return pool->raw(); } const entity_type * data() const noexcept { return pool->data(); } size_type size() const noexcept { return pool->size(); } iterator_type begin() const noexcept { return pool->begin(); } iterator_type end() const noexcept { return pool->end(); } private: const pool_type *pool; }; template<typename Entity, typename... Component> class Registry { using pool_type = std::tuple<SparseSet<Entity, Component>...>; using mask_type = std::bitset<sizeof...(Component)+1>; static constexpr auto validity_bit = sizeof...(Component); public: using entity_type = Entity; using size_type = typename std::vector<mask_type>::size_type; template<typename... Comp> using view_type = View<pool_type, ident<Component...>.template get<Comp>()...>; private: template<typename Comp> void clone(entity_type to, entity_type from) { constexpr auto index = ident<Component...>.template get<Comp>(); if(entities[from].test(index)) { assign<Comp>(to, std::get<index>(pool).get(from)); } } template<typename Comp> void sync(entity_type to, entity_type from) { constexpr auto index = ident<Component...>.template get<Comp>(); bool src = entities[from].test(index); bool dst = entities[to].test(index); if(src && dst) { copy<Comp>(to, from); } else if(src) { clone<Comp>(to, from); } else if(dst) { remove<Comp>(to); } } public: explicit Registry() = default; ~Registry() = default; Registry(const Registry &) = delete; Registry(Registry &&) = delete; Registry & operator=(const Registry &) = delete; Registry & operator=(Registry &&) = delete; template<typename Comp> size_type size() const noexcept { constexpr auto index = ident<Component...>.template get<Comp>(); return std::get<index>(pool).size(); } size_type size() const noexcept { return entities.size() - available.size(); } template<typename Comp> size_type capacity() const noexcept { constexpr auto index = ident<Component...>.template get<Comp>(); return std::get<index>(pool).capacity(); } size_type capacity() const noexcept { return entities.size(); } template<typename Comp> bool empty() const noexcept { constexpr auto index = ident<Component...>.template get<Comp>(); return std::get<index>(pool).empty(); } bool empty() const noexcept { return entities.empty(); } bool valid(entity_type entity) const noexcept { return (entity < entities.size() && entities[entity].test(validity_bit)); } template<typename... Comp> entity_type create() noexcept { using accumulator_type = int[]; auto entity = create(); accumulator_type accumulator = { 0, (assign<Comp>(entity), 0)... }; (void)accumulator; return entity; } entity_type create() noexcept { entity_type entity; if(available.empty()) { entity = entity_type(entities.size()); entities.emplace_back(); } else { entity = available.back(); available.pop_back(); } entities[entity].set(validity_bit); return entity; } void destroy(entity_type entity) { assert(valid(entity)); using accumulator_type = int[]; accumulator_type accumulator = { 0, (reset<Component>(entity), 0)... }; available.push_back(entity); entities[entity].reset(); (void)accumulator; } template<typename Comp, typename... Args> Comp & assign(entity_type entity, Args... args) { assert(valid(entity)); constexpr auto index = ident<Component...>.template get<Comp>(); entities[entity].set(index); return std::get<index>(pool).construct(entity, args...); } template<typename Comp> void remove(entity_type entity) { assert(valid(entity)); constexpr auto index = ident<Component...>.template get<Comp>(); entities[entity].reset(index); std::get<index>(pool).destroy(entity); } template<typename... Comp> bool has(entity_type entity) const noexcept { assert(valid(entity)); using accumulator_type = bool[]; bool all = true; auto &mask = entities[entity]; accumulator_type accumulator = { true, (all = all && mask.test(ident<Component...>.template get<Comp>()))... }; (void)accumulator; return all; } template<typename Comp> const Comp & get(entity_type entity) const noexcept { assert(valid(entity)); constexpr auto index = ident<Component...>.template get<Comp>(); return std::get<index>(pool).get(entity); } template<typename Comp> Comp & get(entity_type entity) noexcept { assert(valid(entity)); constexpr auto index = ident<Component...>.template get<Comp>(); return std::get<index>(pool).get(entity); } template<typename Comp, typename... Args> Comp & replace(entity_type entity, Args... args) { assert(valid(entity)); constexpr auto index = ident<Component...>.template get<Comp>(); return (std::get<index>(pool).get(entity) = Comp{args...}); } template<typename Comp, typename... Args> Comp & accomodate(entity_type entity, Args... args) { assert(valid(entity)); constexpr auto index = ident<Component...>.template get<Comp>(); return (entities[entity].test(index) ? this->template replace<Comp>(entity, std::forward<Args>(args)...) : this->template assign<Comp>(entity, std::forward<Args>(args)...)); } entity_type clone(entity_type from) { assert(valid(from)); using accumulator_type = int[]; auto to = create(); accumulator_type accumulator = { 0, (clone<Component>(to, from), 0)... }; (void)accumulator; return to; } template<typename Comp> Comp & copy(entity_type to, entity_type from) { assert(valid(to)); assert(valid(from)); constexpr auto index = ident<Component...>.template get<Comp>(); auto &&cpool = std::get<index>(pool); return (cpool.get(to) = cpool.get(from)); } void copy(entity_type to, entity_type from) { assert(valid(to)); assert(valid(from)); using accumulator_type = int[]; accumulator_type accumulator = { 0, (sync<Component>(to, from), 0)... }; (void)accumulator; } template<typename Comp> void swap(entity_type lhs, entity_type rhs) { assert(valid(lhs)); assert(valid(rhs)); std::get<ident<Component...>.template get<Comp>()>(pool).swap(lhs, rhs); } template<typename Comp, typename Compare> void sort(Compare compare) { std::get<ident<Component...>.template get<Comp>()>(pool).sort(std::move(compare)); } template<typename To, typename From> void sort() { auto &&to = std::get<ident<Component...>.template get<To>()>(pool); auto &&from = std::get<ident<Component...>.template get<From>()>(pool); to.respect(from); } template<typename Comp> void reset(entity_type entity) { assert(valid(entity)); constexpr auto index = ident<Component...>.template get<Comp>(); if(entities[entity].test(index)) { remove<Comp>(entity); } } template<typename Comp> void reset() { constexpr auto index = ident<Component...>.template get<Comp>(); for(entity_type entity = 0, last = entity_type(entities.size()); entity < last; ++entity) { if(entities[entity].test(index)) { remove<Comp>(entity); } } } void reset() { using accumulator_type = int[]; accumulator_type acc = { 0, (std::get<ident<Component...>.template get<Component>()>(pool).reset(), 0)... }; entities.clear(); available.clear(); (void)acc; } template<typename... Comp> std::enable_if_t<(sizeof...(Comp) == 1), view_type<Comp...>> view() noexcept { return view_type<Comp...>{&pool}; } template<typename... Comp> std::enable_if_t<(sizeof...(Comp) > 1), view_type<Comp...>> view() noexcept { return view_type<Comp...>{&pool, entities.data()}; } private: std::vector<mask_type> entities; std::vector<entity_type> available; pool_type pool; }; template<typename... Component> using DefaultRegistry = Registry<std::uint32_t, Component...>; } #endif // ENTT_REGISTRY_HPP <|endoftext|>
<commit_before>#include "dDNNF.h" #include <unordered_map> #include <algorithm> #include <cassert> /* Turn a bounded-treewidth circuit c for which a tree decomposition td is * provided into a dNNF rooted at root, following the construction in * Section 5.1 of https://arxiv.org/pdf/1811.02944 */ template<unsigned W> dDNNF::dDNNF(const BooleanCircuit &c, const uuid &root, TreeDecomposition<W> &td) { // Theoretically, the BooleanCircuit could be modified by getGate, but // only if root is not a gate of the circuit, so we check that it is a // gate. assert(c.hasGate(root)); unsigned root_id = const_cast<BooleanCircuit &>(c).getGate(root); // We make the tree decomposition friendly td.makeFriendly(root_id); // We look for bags responsible for each variable std::unordered_map<unsigned, unsigned long> responsible_bag; for(unsigned i=0; i<td.bags.size(); ++i) { const auto &b = td.bags[i]; if(td.children[i].empty() && b.nb_gates == 1 && c.gates[b.gates[0]] == BooleanGate::IN) responsible_bag[b.gates[0]] = i; } // A friendly tree decomposition has leaf bags for every variable // nodes. Let's just check that to be safe. assert(responsible_bag.size()==c.inputs.size()); // Create the input and negated input gates std::unordered_map<unsigned,unsigned long> input_gate, negated_input_gate; for(auto g: c.inputs) { unsigned gate = setGate(BooleanGate::IN, c.prob[g]); unsigned not_gate = setGate(BooleanGate::NOT); addWire(not_gate, gate); input_gate[g]=gate; negated_input_gate[g]=not_gate; } std::vector<dDNNFGate> result_gates = builddDNNF(c, td.root, td, responsible_bag, input_gate, negated_input_gate); unsigned long result_id = setGate("root", BooleanGate::OR); for(const auto &p: result_gates) { if(p.suspicious.empty() && p.valuation.find(root_id)->second) { addWire(result_id, p.id); return; } } } bool isStrong(BooleanGate type, bool value) { switch(type) { case BooleanGate::OR: return value; case BooleanGate::AND: return !value; default: return true; } } template<unsigned W> static bool isConnectible(const std::set<unsigned> &suspicious, const typename TreeDecomposition<W>::Bag &b) { for(const auto &g: suspicious) { bool found=false; for(unsigned k=0; k<b.nb_gates; ++k) if(g==b.gates[k]) { found=true; break; } if(!found) return false; } return true; } template<unsigned W> std::vector<dDNNF::dDNNFGate> dDNNF::builddDNNF( const BooleanCircuit &c, unsigned root, const TreeDecomposition<W> &td, const std::unordered_map<unsigned, unsigned long> &responsible_bag, const std::unordered_map<unsigned, unsigned long> &input_gate, const std::unordered_map<unsigned, unsigned long> &negated_input_gate) { std::vector<dDNNFGate> result_gates; if(td.children[root].empty()) { // If the bag is empty, it behaves as if it was not there if(td.bags[root].nb_gates!=0) { // Otherwise, since we have a friendly decomposition, we have a // single gate unsigned single_gate = td.bags[root].gates[0]; // We check if this bag is responsible for an input variable if(c.gates[single_gate]==BooleanGate::IN && responsible_bag.find(single_gate)->second==root) { // No need to create an extra gate, just point to the variable and // negated variable gate; no suspicious gate. dDNNFGate pos = { input_gate.find(single_gate)->second, {std::make_pair(single_gate,true)}, {} }; dDNNFGate neg = { negated_input_gate.find(single_gate)->second, {std::make_pair(single_gate,false)}, {} }; result_gates = { pos, neg }; } else { // We create two TRUE gates (AND gates with no inputs) for(auto v: {true, false}) { std::set<unsigned> suspicious; if(isStrong(c.gates[single_gate], v)) suspicious.insert(single_gate); result_gates.push_back({ setGate(BooleanGate::AND), {std::make_pair(single_gate, v)}, suspicious }); } } } } else { std::vector<dDNNFGate> gates1 = builddDNNF(c, td.children[root][0], td, responsible_bag, input_gate, negated_input_gate); std::vector<dDNNFGate> gates2; if(td.children[root].size()==2) gates2 = builddDNNF(c, td.children[root][1], td, responsible_bag, input_gate, negated_input_gate); else gates2 = {{ 0, {}, {} }}; std::map<std::pair<std::map<unsigned,bool>,std::set<unsigned>>,std::vector<unsigned>> gates_to_or; for(auto g1: gates1) { std::map<unsigned,bool> partial_valuation; std::set<unsigned> partial_innocent; for(const auto &p: g1.valuation) for(unsigned k=0; k<td.bags[root].nb_gates; ++k) if(p.first==td.bags[root].gates[k]) { partial_valuation.insert(p); if(g1.suspicious.find(p.first)==g1.suspicious.end()) { partial_innocent.insert(p.first); } } // We check all suspicious gates are in the bag of the parent if(!isConnectible<W>(g1.suspicious,td.bags[root])) continue; for(auto g2: gates2) { auto valuation = partial_valuation; auto innocent = partial_innocent; // Check if these two almost-evaluations mutually agree and if so // build the valuation of the root bool agree=true; for(const auto &p: g2.valuation) { bool found=false; auto it=g1.valuation.find(p.first); if(it!=g1.valuation.end()) { found=true; agree=(it->second==p.second); } if(!agree) break; for(unsigned k=0; k<td.bags[root].nb_gates; ++k) if(p.first==td.bags[root].gates[k]) { if(!found) valuation.insert(p); if(g2.suspicious.find(p.first)==g2.suspicious.end()) { innocent.insert(p.first); } } } if(!agree) continue; // We check all suspicious gates are in the bag of the parent if(!isConnectible<W>(g2.suspicious,td.bags[root])) continue; // We check valuation is still an almost-valuation bool almostvaluation = true; for(const auto &p1: valuation) { for(const auto &p2: valuation) { if(p1.first==p2.first) continue; if(!isStrong(c.gates[p1.first],p2.second)) continue; if(std::find(c.wires[p1.first].begin(),c.wires[p1.first].end(),p2.first)!= c.wires[p1.first].end()) { switch(c.gates[p1.first]) { case BooleanGate::AND: case BooleanGate::OR: almostvaluation = (p1.second==p2.second); break; case BooleanGate::NOT: almostvaluation = (p1.second!=p2.second); break; default: ; } if(!almostvaluation) break; } } if(!almostvaluation) break; } if(!almostvaluation) continue; std::set<unsigned> suspicious; for(const auto &p: valuation) { // We first check if this gate was innocent because it was // innocent in a child if(innocent.find(p.first)!=innocent.end()) continue; // Otherwise, we check if it is strong bool strong=isStrong(c.gates[p.first],p.second); if(!strong) continue; // We have a strong gate not innocented by the children bags, // it is suspicious unless we also have in the bag an input to // that gate which is strong for that gate bool susp=true; for(unsigned k=0; k<td.bags[root].nb_gates; ++k) { auto g=td.bags[root].gates[k]; if(g==p.first) continue; if(std::find(c.wires[p.first].begin(),c.wires[p.first].end(),g)!= c.wires[p.first].end()) { bool value = valuation[g]; if(isStrong(c.gates[p.first],value)) { susp=false; break; } } } if(susp) suspicious.insert(p.first); } unsigned long and_gate; // We optimize a bit by avoiding creating an AND gate if there // is only one child, or if a second child is a TRUE gate std::vector<unsigned long> gates_children; if(!(gates[g1.id]==BooleanGate::AND && wires[g1.id].empty())) gates_children.push_back(g1.id); if(td.children[root].size()==2) if(!(gates[g2.id]==BooleanGate::AND && wires[g2.id].empty())) gates_children.push_back(g2.id); if(gates_children.size()==1) { and_gate = gates_children[0]; } else { and_gate = setGate(BooleanGate::AND); for(auto x: gates_children) addWire(and_gate, x); } gates_to_or[make_pair(valuation,suspicious)].push_back(and_gate); } } for(const auto &p: gates_to_or) { unsigned long result_gate; if(p.second.size()==1) result_gate = p.second[0]; else { result_gate = setGate(BooleanGate::OR); for(auto &g: p.second) addWire(result_gate, g); } result_gates.push_back({result_gate, p.first.first, p.first.second}); } } return result_gates; } double dDNNF::dDNNFEvaluation(unsigned g) const { switch(gates[g]) { case BooleanGate::IN: return prob[g]; case BooleanGate::NOT: return 1-dDNNFEvaluation(wires[g][0]); case BooleanGate::AND: break; case BooleanGate::OR: break; case BooleanGate::UNDETERMINED: throw CircuitException("Incorrect gate type"); } double result=(gates[g]==BooleanGate::AND?1:0); for(auto s: wires[g]) { double d = dDNNFEvaluation(s); if(gates[g]==BooleanGate::AND) result*=d; else result+=d; } return result; } std::ostream &operator<<(std::ostream &o, const dDNNF::dDNNFGate &g) { o << g.id << "; {"; bool first=true; for(const auto &p: g.valuation) { if(!first) o << ","; first=false; o << "(" << p.first << "," << p.second << ")"; } o << "}; {"; first=true; for(auto x: g.suspicious) { if(!first) o << ","; first=false; o << x; } o << "}"; return o; } <commit_msg>Cache probabilities computed at each node of a dDNNF<commit_after>#include "dDNNF.h" #include <unordered_map> #include <algorithm> #include <cassert> /* Turn a bounded-treewidth circuit c for which a tree decomposition td is * provided into a dNNF rooted at root, following the construction in * Section 5.1 of https://arxiv.org/pdf/1811.02944 */ template<unsigned W> dDNNF::dDNNF(const BooleanCircuit &c, const uuid &root, TreeDecomposition<W> &td) { // Theoretically, the BooleanCircuit could be modified by getGate, but // only if root is not a gate of the circuit, so we check that it is a // gate. assert(c.hasGate(root)); unsigned root_id = const_cast<BooleanCircuit &>(c).getGate(root); // We make the tree decomposition friendly td.makeFriendly(root_id); // We look for bags responsible for each variable std::unordered_map<unsigned, unsigned long> responsible_bag; for(unsigned i=0; i<td.bags.size(); ++i) { const auto &b = td.bags[i]; if(td.children[i].empty() && b.nb_gates == 1 && c.gates[b.gates[0]] == BooleanGate::IN) responsible_bag[b.gates[0]] = i; } // A friendly tree decomposition has leaf bags for every variable // nodes. Let's just check that to be safe. assert(responsible_bag.size()==c.inputs.size()); // Create the input and negated input gates std::unordered_map<unsigned,unsigned long> input_gate, negated_input_gate; for(auto g: c.inputs) { unsigned gate = setGate(BooleanGate::IN, c.prob[g]); unsigned not_gate = setGate(BooleanGate::NOT); addWire(not_gate, gate); input_gate[g]=gate; negated_input_gate[g]=not_gate; } std::vector<dDNNFGate> result_gates = builddDNNF(c, td.root, td, responsible_bag, input_gate, negated_input_gate); unsigned long result_id = setGate("root", BooleanGate::OR); for(const auto &p: result_gates) { if(p.suspicious.empty() && p.valuation.find(root_id)->second) { addWire(result_id, p.id); return; } } } bool isStrong(BooleanGate type, bool value) { switch(type) { case BooleanGate::OR: return value; case BooleanGate::AND: return !value; default: return true; } } template<unsigned W> static bool isConnectible(const std::set<unsigned> &suspicious, const typename TreeDecomposition<W>::Bag &b) { for(const auto &g: suspicious) { bool found=false; for(unsigned k=0; k<b.nb_gates; ++k) if(g==b.gates[k]) { found=true; break; } if(!found) return false; } return true; } template<unsigned W> std::vector<dDNNF::dDNNFGate> dDNNF::builddDNNF( const BooleanCircuit &c, unsigned root, const TreeDecomposition<W> &td, const std::unordered_map<unsigned, unsigned long> &responsible_bag, const std::unordered_map<unsigned, unsigned long> &input_gate, const std::unordered_map<unsigned, unsigned long> &negated_input_gate) { std::vector<dDNNFGate> result_gates; if(td.children[root].empty()) { // If the bag is empty, it behaves as if it was not there if(td.bags[root].nb_gates!=0) { // Otherwise, since we have a friendly decomposition, we have a // single gate unsigned single_gate = td.bags[root].gates[0]; // We check if this bag is responsible for an input variable if(c.gates[single_gate]==BooleanGate::IN && responsible_bag.find(single_gate)->second==root) { // No need to create an extra gate, just point to the variable and // negated variable gate; no suspicious gate. dDNNFGate pos = { input_gate.find(single_gate)->second, {std::make_pair(single_gate,true)}, {} }; dDNNFGate neg = { negated_input_gate.find(single_gate)->second, {std::make_pair(single_gate,false)}, {} }; result_gates = { pos, neg }; } else { // We create two TRUE gates (AND gates with no inputs) for(auto v: {true, false}) { std::set<unsigned> suspicious; if(isStrong(c.gates[single_gate], v)) suspicious.insert(single_gate); result_gates.push_back({ setGate(BooleanGate::AND), {std::make_pair(single_gate, v)}, suspicious }); } } } } else { std::vector<dDNNFGate> gates1 = builddDNNF(c, td.children[root][0], td, responsible_bag, input_gate, negated_input_gate); std::vector<dDNNFGate> gates2; if(td.children[root].size()==2) gates2 = builddDNNF(c, td.children[root][1], td, responsible_bag, input_gate, negated_input_gate); else gates2 = {{ 0, {}, {} }}; std::map<std::pair<std::map<unsigned,bool>,std::set<unsigned>>,std::vector<unsigned>> gates_to_or; for(auto g1: gates1) { std::map<unsigned,bool> partial_valuation; std::set<unsigned> partial_innocent; for(const auto &p: g1.valuation) for(unsigned k=0; k<td.bags[root].nb_gates; ++k) if(p.first==td.bags[root].gates[k]) { partial_valuation.insert(p); if(g1.suspicious.find(p.first)==g1.suspicious.end()) { partial_innocent.insert(p.first); } } // We check all suspicious gates are in the bag of the parent if(!isConnectible<W>(g1.suspicious,td.bags[root])) continue; for(auto g2: gates2) { auto valuation = partial_valuation; auto innocent = partial_innocent; // Check if these two almost-evaluations mutually agree and if so // build the valuation of the root bool agree=true; for(const auto &p: g2.valuation) { bool found=false; auto it=g1.valuation.find(p.first); if(it!=g1.valuation.end()) { found=true; agree=(it->second==p.second); } if(!agree) break; for(unsigned k=0; k<td.bags[root].nb_gates; ++k) if(p.first==td.bags[root].gates[k]) { if(!found) valuation.insert(p); if(g2.suspicious.find(p.first)==g2.suspicious.end()) { innocent.insert(p.first); } } } if(!agree) continue; // We check all suspicious gates are in the bag of the parent if(!isConnectible<W>(g2.suspicious,td.bags[root])) continue; // We check valuation is still an almost-valuation bool almostvaluation = true; for(const auto &p1: valuation) { for(const auto &p2: valuation) { if(p1.first==p2.first) continue; if(!isStrong(c.gates[p1.first],p2.second)) continue; if(std::find(c.wires[p1.first].begin(),c.wires[p1.first].end(),p2.first)!= c.wires[p1.first].end()) { switch(c.gates[p1.first]) { case BooleanGate::AND: case BooleanGate::OR: almostvaluation = (p1.second==p2.second); break; case BooleanGate::NOT: almostvaluation = (p1.second!=p2.second); break; default: ; } if(!almostvaluation) break; } } if(!almostvaluation) break; } if(!almostvaluation) continue; std::set<unsigned> suspicious; for(const auto &p: valuation) { // We first check if this gate was innocent because it was // innocent in a child if(innocent.find(p.first)!=innocent.end()) continue; // Otherwise, we check if it is strong bool strong=isStrong(c.gates[p.first],p.second); if(!strong) continue; // We have a strong gate not innocented by the children bags, // it is suspicious unless we also have in the bag an input to // that gate which is strong for that gate bool susp=true; for(unsigned k=0; k<td.bags[root].nb_gates; ++k) { auto g=td.bags[root].gates[k]; if(g==p.first) continue; if(std::find(c.wires[p.first].begin(),c.wires[p.first].end(),g)!= c.wires[p.first].end()) { bool value = valuation[g]; if(isStrong(c.gates[p.first],value)) { susp=false; break; } } } if(susp) suspicious.insert(p.first); } unsigned long and_gate; // We optimize a bit by avoiding creating an AND gate if there // is only one child, or if a second child is a TRUE gate std::vector<unsigned long> gates_children; if(!(gates[g1.id]==BooleanGate::AND && wires[g1.id].empty())) gates_children.push_back(g1.id); if(td.children[root].size()==2) if(!(gates[g2.id]==BooleanGate::AND && wires[g2.id].empty())) gates_children.push_back(g2.id); if(gates_children.size()==1) { and_gate = gates_children[0]; } else { and_gate = setGate(BooleanGate::AND); for(auto x: gates_children) addWire(and_gate, x); } gates_to_or[make_pair(valuation,suspicious)].push_back(and_gate); } } for(const auto &p: gates_to_or) { unsigned long result_gate; if(p.second.size()==1) result_gate = p.second[0]; else { result_gate = setGate(BooleanGate::OR); for(auto &g: p.second) addWire(result_gate, g); } result_gates.push_back({result_gate, p.first.first, p.first.second}); } } return result_gates; } double dDNNF::dDNNFEvaluation(unsigned g) const { static std::unordered_map<unsigned, double> cache; auto it = cache.find(g); if(it!=cache.end()) return it->second; double result; if(gates[g]==BooleanGate::IN) result = prob[g]; else if(gates[g]==BooleanGate::IN) result = 1-dDNNFEvaluation(wires[g][0]); else { result=(gates[g]==BooleanGate::AND?1:0); for(auto s: wires[g]) { double d = dDNNFEvaluation(s); if(gates[g]==BooleanGate::AND) result*=d; else result+=d; } } cache[g]=result; return result; } std::ostream &operator<<(std::ostream &o, const dDNNF::dDNNFGate &g) { o << g.id << "; {"; bool first=true; for(const auto &p: g.valuation) { if(!first) o << ","; first=false; o << "(" << p.first << "," << p.second << ")"; } o << "}; {"; first=true; for(auto x: g.suspicious) { if(!first) o << ","; first=false; o << x; } o << "}"; return o; } <|endoftext|>
<commit_before>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "open_spiel/algorithms/sarsa.h" #include <algorithm> #include <random> #include "open_spiel/abseil-cpp/absl/container/flat_hash_map.h" #include "open_spiel/abseil-cpp/absl/random/distributions.h" #include "open_spiel/abseil-cpp/absl/random/random.h" #include "open_spiel/spiel_globals.h" #include "open_spiel/spiel_utils.h" namespace open_spiel { namespace algorithms { using std::vector; Action SarsaSolver::GetBestAction(const std::unique_ptr<State>& state, const Player& player, const double& min_utility, const double& max_utility) { vector<Action> legal_actions = state->LegalActions(); Action optimal_action = kInvalidAction; // Initialize value to be the minimum utility if current player // is the maximizing player (i.e. player 0), and to maximum utility // if current player is the minimizing player (i.e. player 1). double value = (player == Player{0}) ? min_utility : max_utility; for (const Action& action : legal_actions) { double q_val = values_[{state->ToString(), action}]; bool is_best_so_far = (player == Player{0} && q_val >= value) || (player == Player{1} && q_val <= value); if (is_best_so_far) { value = q_val; optimal_action = action; } } return optimal_action; } Action SarsaSolver::SampleActionFromEpsilonGreedyPolicy( const std::unique_ptr<State>& state, const Player& player, const double& min_utility, const double& max_utility) { vector<Action> legal_actions = state->LegalActions(); if (legal_actions.empty()) { return kInvalidAction; } if (absl::Uniform(rng_, 0.0, 1.0) < epsilon_) { // Choose a random action return legal_actions[absl::Uniform<int>(rng_, 0, legal_actions.size())]; } // Choose the best action return GetBestAction(state, player, min_utility, max_utility); } SarsaSolver::SarsaSolver(const Game& game) { game_ = game.shared_from_this(); depth_limit_ = kDefaultDepthLimit; epsilon_ = kDefaultEpsilon; learning_rate_ = kDefaultLearningRate; discount_factor_ = kDefaultDiscountFactor; // Currently only supports 1-player or 2-player zero sum games SPIEL_CHECK_TRUE(game_->NumPlayers() == 1 || game_->NumPlayers() == 2); if (game_->NumPlayers() == 2) { SPIEL_CHECK_EQ(game_->GetType().utility, GameType::Utility::kZeroSum); } // No support for simultaneous games (needs an LP solver). And so also must // be a perfect information game. SPIEL_CHECK_EQ(game_->GetType().dynamics, GameType::Dynamics::kSequential); SPIEL_CHECK_EQ(game_->GetType().information, GameType::Information::kPerfectInformation); } absl::flat_hash_map<std::pair<std::string, Action>, double> SarsaSolver::GetQValueTable() { return values_; } void SarsaSolver::RunIteration() { double min_utility = game_->MinUtility(); double max_utility = game_->MaxUtility(); // Choose start state std::unique_ptr<State> curr_state = game_->NewInitialState(); Player player = curr_state->CurrentPlayer(); // Sample action from the state using an epsilon-greedy policy Action curr_action = SampleActionFromEpsilonGreedyPolicy( curr_state, player, min_utility, max_utility); while (!curr_state->IsTerminal()) { std::unique_ptr<State> next_state = curr_state->Child(curr_action); double reward = next_state->Rewards()[player == Player{0} ? 0 : 1]; // Sample next action from the state using an epsilon-greedy policy player = next_state->CurrentPlayer(); Action next_action = SampleActionFromEpsilonGreedyPolicy( next_state, player, min_utility, max_utility); // Update action value string key = curr_state->ToString(); double prev_q_val = values_[{key, curr_action}]; double new_q_val = prev_q_val + learning_rate_ * (reward + discount_factor_ * values_[{next_state->ToString(), next_action}] - prev_q_val); values_[{key, curr_action}] = new_q_val; curr_state = next_state->Clone(); curr_action = next_action; } } } // namespace algorithms } // namespace open_spiel <commit_msg>Fix missing namespace in C++ Sarsa.<commit_after>// Copyright 2019 DeepMind Technologies Ltd. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "open_spiel/algorithms/sarsa.h" #include <algorithm> #include <random> #include <string> #include "open_spiel/abseil-cpp/absl/container/flat_hash_map.h" #include "open_spiel/abseil-cpp/absl/random/distributions.h" #include "open_spiel/abseil-cpp/absl/random/random.h" #include "open_spiel/spiel_globals.h" #include "open_spiel/spiel_utils.h" namespace open_spiel { namespace algorithms { using std::vector; Action SarsaSolver::GetBestAction(const std::unique_ptr<State>& state, const Player& player, const double& min_utility, const double& max_utility) { vector<Action> legal_actions = state->LegalActions(); Action optimal_action = kInvalidAction; // Initialize value to be the minimum utility if current player // is the maximizing player (i.e. player 0), and to maximum utility // if current player is the minimizing player (i.e. player 1). double value = (player == Player{0}) ? min_utility : max_utility; for (const Action& action : legal_actions) { double q_val = values_[{state->ToString(), action}]; bool is_best_so_far = (player == Player{0} && q_val >= value) || (player == Player{1} && q_val <= value); if (is_best_so_far) { value = q_val; optimal_action = action; } } return optimal_action; } Action SarsaSolver::SampleActionFromEpsilonGreedyPolicy( const std::unique_ptr<State>& state, const Player& player, const double& min_utility, const double& max_utility) { vector<Action> legal_actions = state->LegalActions(); if (legal_actions.empty()) { return kInvalidAction; } if (absl::Uniform(rng_, 0.0, 1.0) < epsilon_) { // Choose a random action return legal_actions[absl::Uniform<int>(rng_, 0, legal_actions.size())]; } // Choose the best action return GetBestAction(state, player, min_utility, max_utility); } SarsaSolver::SarsaSolver(const Game& game) { game_ = game.shared_from_this(); depth_limit_ = kDefaultDepthLimit; epsilon_ = kDefaultEpsilon; learning_rate_ = kDefaultLearningRate; discount_factor_ = kDefaultDiscountFactor; // Currently only supports 1-player or 2-player zero sum games SPIEL_CHECK_TRUE(game_->NumPlayers() == 1 || game_->NumPlayers() == 2); if (game_->NumPlayers() == 2) { SPIEL_CHECK_EQ(game_->GetType().utility, GameType::Utility::kZeroSum); } // No support for simultaneous games (needs an LP solver). And so also must // be a perfect information game. SPIEL_CHECK_EQ(game_->GetType().dynamics, GameType::Dynamics::kSequential); SPIEL_CHECK_EQ(game_->GetType().information, GameType::Information::kPerfectInformation); } absl::flat_hash_map<std::pair<std::string, Action>, double> SarsaSolver::GetQValueTable() { return values_; } void SarsaSolver::RunIteration() { double min_utility = game_->MinUtility(); double max_utility = game_->MaxUtility(); // Choose start state std::unique_ptr<State> curr_state = game_->NewInitialState(); Player player = curr_state->CurrentPlayer(); // Sample action from the state using an epsilon-greedy policy Action curr_action = SampleActionFromEpsilonGreedyPolicy( curr_state, player, min_utility, max_utility); while (!curr_state->IsTerminal()) { std::unique_ptr<State> next_state = curr_state->Child(curr_action); double reward = next_state->Rewards()[player == Player{0} ? 0 : 1]; // Sample next action from the state using an epsilon-greedy policy player = next_state->CurrentPlayer(); Action next_action = SampleActionFromEpsilonGreedyPolicy( next_state, player, min_utility, max_utility); // Update action value std::string key = curr_state->ToString(); double prev_q_val = values_[{key, curr_action}]; double new_q_val = prev_q_val + learning_rate_ * (reward + discount_factor_ * values_[{next_state->ToString(), next_action}] - prev_q_val); values_[{key, curr_action}] = new_q_val; curr_state = next_state->Clone(); curr_action = next_action; } } } // namespace algorithms } // namespace open_spiel <|endoftext|>
<commit_before>/// /// @file pmath.hpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef PMATH_HPP #define PMATH_HPP #include <stdint.h> #include <algorithm> #include <cassert> #include <cmath> #include <vector> namespace primecount { inline int64_t isquare(int64_t x) { return x * x; } inline int64_t ceil_div(int64_t a, int64_t b) { assert(b != 0); return (a + b - 1) / b; } template <typename T> inline T number_of_bits(T) { return (T) (sizeof(T) * 8); } /// @brief Check if an integer is a power of 2. /// @see Book "Hacker's Delight". /// template <typename T> inline bool is_power_of_2(T x) { return (x != 0 && (x & (x - 1)) == 0); } /// @brief Round up to the next power of 2. /// @see Book "Hacker's Delight". /// template <typename T> inline T next_power_of_2(T x) { if (x == 0) return 1; x--; for (T i = 1; i < number_of_bits(x); i += i) x |= (x >> i); return ++x; } template <typename T> inline int ilog(T x) { return (int) std::log((double) x); } /// Raise to power template <int N> inline int64_t ipow(int64_t x) { int64_t r = 1; for (int i = 0; i < N; i++) r *= x; return r; } /// Integer suare root template <typename T> inline T isqrt(T x) { T r = (T) std::sqrt((double) x); while (isquare(r) > x) r--; while (isquare(r + 1) <= x) r++; return r; } /// Integer nth root template <int N, typename T> inline T iroot(T x) { T r = (T) std::pow((double) x, 1.0 / N); while (ipow<N>(r) > x) r--; while (ipow<N>(r + 1) <= x) r++; return r; } /// Integer nth root template <int D, int N, typename T> inline T iroot(T x) { T r = (T) std::pow((double) x, D / (double) N); return r; } /// Calculate the number of primes below x using binary search. /// @pre primes[1] = 2, primes[3] = 3, ... /// @pre x <= primes.back() /// template <typename T1, typename T2> inline T2 pi_bsearch(const std::vector<T1>& primes, T2 x) { // primecount uses 1-indexing assert(primes[0] == 0); return (T2) (std::upper_bound(primes.begin() + 1, primes.end(), x) - (primes.begin() + 1)); } /// Calculate the number of primes below x using binary search. /// @pre primes[1] = 2, primes[3] = 3, ... /// @pre x <= primes.back() /// template <typename T1, typename T2, typename T3> inline T3 pi_bsearch(const std::vector<T1>& primes, T2 len, T3 x) { // primecount uses 1-indexing assert(primes[0] == 0); return (T3) (std::upper_bound(primes.begin() + 1, primes.begin() + len + 1, x) - (primes.begin() + 1)); } template <typename T1, typename T2, typename T3> inline T2 in_between(T1 min, T2 x, T3 max) { if (x < min) return (T2) min; if (x > max) return (T2) max; return x; } /// Generate a vector with Möbius function values. std::vector<int32_t> make_moebius(int64_t max); /// Generate a vector with the least prime /// factors of the integers <= max. /// std::vector<int32_t> make_least_prime_factor(int64_t max); /// Generate a vector with the prime counts below max /// using the sieve of Eratosthenes. /// std::vector<int32_t> make_pi(int64_t max); } // namespace #endif <commit_msg>Add generate_primes() functions<commit_after>/// /// @file pmath.hpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef PMATH_HPP #define PMATH_HPP #include <stdint.h> #include <algorithm> #include <cassert> #include <cmath> #include <vector> namespace primecount { inline int64_t isquare(int64_t x) { return x * x; } inline int64_t ceil_div(int64_t a, int64_t b) { assert(b != 0); return (a + b - 1) / b; } template <typename T> inline T number_of_bits(T) { return (T) (sizeof(T) * 8); } /// @brief Check if an integer is a power of 2. /// @see Book "Hacker's Delight". /// template <typename T> inline bool is_power_of_2(T x) { return (x != 0 && (x & (x - 1)) == 0); } /// @brief Round up to the next power of 2. /// @see Book "Hacker's Delight". /// template <typename T> inline T next_power_of_2(T x) { if (x == 0) return 1; x--; for (T i = 1; i < number_of_bits(x); i += i) x |= (x >> i); return ++x; } template <typename T> inline int ilog(T x) { return (int) std::log((double) x); } /// Raise to power template <int N> inline int64_t ipow(int64_t x) { int64_t r = 1; for (int i = 0; i < N; i++) r *= x; return r; } /// Integer suare root template <typename T> inline T isqrt(T x) { T r = (T) std::sqrt((double) x); while (isquare(r) > x) r--; while (isquare(r + 1) <= x) r++; return r; } /// Integer nth root template <int N, typename T> inline T iroot(T x) { T r = (T) std::pow((double) x, 1.0 / N); while (ipow<N>(r) > x) r--; while (ipow<N>(r + 1) <= x) r++; return r; } /// Integer nth root template <int D, int N, typename T> inline T iroot(T x) { T r = (T) std::pow((double) x, D / (double) N); return r; } /// Calculate the number of primes below x using binary search. /// @pre primes[1] = 2, primes[3] = 3, ... /// @pre x <= primes.back() /// template <typename T1, typename T2> inline T2 pi_bsearch(const std::vector<T1>& primes, T2 x) { // primecount uses 1-indexing assert(primes[0] == 0); return (T2) (std::upper_bound(primes.begin() + 1, primes.end(), x) - (primes.begin() + 1)); } /// Calculate the number of primes below x using binary search. /// @pre primes[1] = 2, primes[3] = 3, ... /// @pre x <= primes.back() /// template <typename T1, typename T2, typename T3> inline T3 pi_bsearch(const std::vector<T1>& primes, T2 len, T3 x) { // primecount uses 1-indexing assert(primes[0] == 0); return (T3) (std::upper_bound(primes.begin() + 1, primes.begin() + len + 1, x) - (primes.begin() + 1)); } template <typename T1, typename T2, typename T3> inline T2 in_between(T1 min, T2 x, T3 max) { if (x < min) return (T2) min; if (x > max) return (T2) max; return x; } /// Generate a vector with the primes <= max. /// The primes vector uses 1-indexing i.e. primes[1] = 2. // std::vector<int32_t> generate_primes(int64_t max); /// Generate a vector with the first n primes. /// The primes vector uses 1-indexing i.e. primes[1] = 2. // std::vector<int32_t> generate_n_primes(int64_t n); /// Generate a vector with Möbius function values. std::vector<int32_t> make_moebius(int64_t max); /// Generate a vector with the least prime /// factors of the integers <= max. /// std::vector<int32_t> make_least_prime_factor(int64_t max); /// Generate a vector with the prime counts below max /// using the sieve of Eratosthenes. /// std::vector<int32_t> make_pi(int64_t max); } // namespace #endif <|endoftext|>
<commit_before>#include "Stack.hpp" #include <stdexcept> #ifndef STACK_CPP #define STACK_CPP template <typename T1, typename T2> void construct(T1 * ptr, T2 const & value) { new(ptr) T1(value); } template <typename T> void destroy(T * array) noexcept { array->~T(); } template <typename FwdIter> void destroy(FwdIter first, FwdIter last) noexcept { for (; first != last; ++first) { destroy(&*first); } } template<typename T> bool stack<T>::empty()const noexcept { return (allocator<T>::count_ == 0); }; template <typename T> allocator<T>::allocator(size_t size) : array_(static_cast<T *>(size == 0 ? nullptr : operator new(size * sizeof(T)))), array_size_(size), count_(0) {}; template <typename T> allocator<T>::~allocator() { operator delete(array_); }; template <typename T> void allocator<T>::swap(allocator& v) { std::swap(array_, v.array_); std::swap(array_size_, v.array_size_); std::swap(count_, v.count_); }; template <typename T> stack<T>::stack(size_t size) : allocator<T>(size) { } template <typename T> size_t stack<T>::count() const noexcept { return allocator<T>::count_; } template <typename T> size_t stack<T>::pop() { if (allocator<T>::count_ == 0) { throw std::logic_error("Stack is empty!"); } destroy(allocator<T>::array_ + allocator<T>::count_); return --allocator<T>::count_; } template <typename T> const T& stack<T>::top() const { if (allocator<T>::count_ == 0) { throw std::logic_error("Stack is empty!"); } return allocator<T>::array_[allocator<T>::count_ - 1]; } template <typename T> void stack<T>::push(T const &elem) { if (allocator<T>::count_ == allocator<T>::array_size_) { size_t array_size = allocator<T>::array_size_ * 2 + (allocator<T>::array_size_ == 0); stack<T> temp(array_size); while (temp.count() < allocator<T>::count_) temp.push(allocator<T>::array_[temp.count()]); this->swap(temp); } construct(allocator<T>::array_ + allocator<T>::count_, elem); ++allocator<T>::count_; } template <typename T> stack<T>::~stack() { destroy(allocator<T>::ptr_, allocator<T>::ptr_ + allocator<T>::count_); } template <typename T> stack<T>::stack(const stack& x) : allocator<T>(x.size_) { for (size_t i = 0; i < x.count_; i++) construct(allocator<T>::ptr_ + i, x.ptr_[i]); allocator<T>::count_ = x.count_; }; template<typename T> stack<T>& stack<T>::operator=(const stack& b){ if (this != &b){ stack<T> temp(b); this->swap(temp); } return *this; } template<typename T> bool stack<T>::operator==(stack const & _s) { if ((_s.count_ != allocator<T>::count_) || (_s.array_size_ != allocator<T>::array_size_)) { return false; } else { for (size_t i = 0; i < allocator<T>::count_; i++) { if (_s.array_[i] != allocator<T>::array_[i]) { return false; } } } return true; } #endif <commit_msg>Update stack.cpp<commit_after>#include "Stack.hpp" #include <stdexcept> #ifndef STACK_CPP #define STACK_CPP template <typename T1, typename T2> void construct(T1 * ptr, T2 const & value) { new(ptr) T1(value); } template <typename T> void destroy(T * array) noexcept { array->~T(); } template <typename FwdIter> void destroy(FwdIter first, FwdIter last) noexcept { for (; first != last; ++first) { destroy(&*first); } } template<typename T> bool stack<T>::empty()const noexcept { return (allocator<T>::count_ == 0); }; template <typename T> allocator<T>::allocator(size_t size) : array_(static_cast<T *>(size == 0 ? nullptr : operator new(size * sizeof(T)))), array_size_(size), count_(0) {}; template <typename T> allocator<T>::~allocator() { operator delete(array_); }; template <typename T> void allocator<T>::swap(allocator& v) { std::swap(array_, v.array_); std::swap(array_size_, v.array_size_); std::swap(count_, v.count_); }; template <typename T> stack<T>::stack(size_t size) : allocator<T>(size) { } template <typename T> size_t stack<T>::count() const noexcept { return allocator<T>::count_; } template <typename T> size_t stack<T>::pop() { if (allocator<T>::count_ == 0) { throw std::logic_error("Stack is empty!"); } destroy(allocator<T>::array_ + allocator<T>::count_); return --allocator<T>::count_; } template <typename T> const T& stack<T>::top() const { if (allocator<T>::count_ == 0) { throw std::logic_error("Stack is empty!"); } return allocator<T>::array_[allocator<T>::count_ - 1]; } template <typename T> void stack<T>::push(T const &elem) { if (allocator<T>::count_ == allocator<T>::array_size_) { size_t array_size = allocator<T>::array_size_ * 2 + (allocator<T>::array_size_ == 0); stack<T> temp(array_size); while (temp.count() < allocator<T>::count_) temp.push(allocator<T>::array_[temp.count()]); this->swap(temp); } construct(allocator<T>::array_ + allocator<T>::count_, elem); ++allocator<T>::count_; } template <typename T> stack<T>::~stack() { destroy(allocator<T>::ptr_, allocator<T>::ptr_ + allocator<T>::count_); } template <typename T> stack<T>::stack(const stack& x) : allocator<T>(x.size_) { for (size_t i = 0; i < x.count_; i++) construct(allocator<T>::ptr_ + i, x.ptr_[i]); allocator<T>::count_ = x.count_; }; template<typename T> stack<T>& stack<T>::operator=(const stack& b){ if (this != &b){ stack<T> temp(b); this->swap(temp); } return *this; } template<typename T> bool stack<T>::operator==(stack const & _s) { if ((_s.count_ != allocator<T>::count_) || (_s.array_size_ != allocator<T>::array_size_)) { return false; } else { for (size_t i = 0; i < allocator<T>::count_; i++) { if (_s.array_[i] != allocator<T>::array_[i]) { return false; } } } return true; } #endif <|endoftext|>
<commit_before>#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> template<typename T> auto newcopy( const T * item, size_t size, size_t count) -> T* //strong { T * buff = new T[size]; try { std::copy(item, item + count, buff); } catch(...) { delete[] buff; throw; } return buff; } template <typename T> class allocator { protected: allocator(size_t size = 0); ~allocator(); auto swap(allocator & other) -> void; allocator(allocator const &) = delete; auto operator =(allocator const &) -> allocator & = delete; T * ptr_; size_t size_; size_t count_; }; template<typename T> allocator<T>::allocator(size_t size) : ptr_(static_cast<T *>(size == 0 ? nullptr : operator new(size * sizeof(T)))), size_(0), count_(size) { } template<typename T> allocator<T>::~allocator() { delete ptr_; } template<typename T> auto allocator<T>::swap(allocator & other) -> void { std::swap(ptr_, other.ptr_); std::swap(count_, other.count_); std::swap(size_, other.size_); } template <typename T> class stack : protected allocator<T> { public: stack(); //noexcept stack(stack const &); //strong ~stack(); //noexcept size_t count() const; //noexcept auto push(T const &) -> void; //strong void pop(); //strong const T& top(); //strong auto operator=(stack const & right)->stack &; //strong auto empty() const -> bool; //noexcept }; template <typename T> size_t stack<T>::count() const { return allocator<T>::count_; } template <typename T> stack<T>::stack():allocator(){} { } template <typename T> stack<T>::stack(const stack& item) : allocator<T>(item.size_){ allocator<T>::ptr_ = newcopy(item.allocator<T>::ptr_, item.allocator<T>::count_, item.allocator<T>::size_); allocator<T>::count_ = item.allocator<T>::count_; }; template <typename T> stack<T>::~stack() { } template<typename T> auto stack<T>::push(T const & item) -> void { if (allocator<T>::count_ == allocator<T>::size_) { T * buff = newcopy(allocator<T>::ptr_, allocator<T>::count_, allocator<T>::size_ = allocator<T>::size_ * 2 + (allocator<T>::count_ == 0)); delete allocator<T>::ptr_; allocator<T>::ptr_ = buff; allocator<T>::size_ = allocator<T>::size_ * 2 + (allocator<T>::count_ == 0) ; } allocator<T>::ptr_[allocator<T>::count_] = item; ++allocator<T>::count_; } template<typename T> void stack<T>::pop() { if (allocator::count_ == 0) { throw std::logic_error("Stack is empty!"); } else { allocator::count_--; } } template<typename T> const T& stack<T>::top() { if (allocator::count_ == 0) { throw ("Stack is empty!"); } return allocator::ptr_[allocator::count_ - 1]; } template<typename T> auto stack<T>::operator=(stack const & right) -> stack & { if (this != &right) { T* buff = newcopy(right.allocator<T>::ptr_, right.allocator<T>::size_, right.allocator<T>::count_); delete[] allocator<T>::ptr_; allocator<T>::ptr = buff; allocator<T>::count_ = right.allocator<T>::count_; allocator<T>::size_ = right.allocator<T>::size_; } return *this; } template<typename T> auto stack<T>::empty() const -> bool{ if (allocator::count_ == 0){ return true; } else{ return false; } } #endif <commit_msg>Update stack.cpp<commit_after>#ifndef stack_cpp #define stack_cpp #pragma once #include <iostream> template<typename T> auto newcopy( const T * item, size_t size, size_t count) -> T* //strong { T * buff = new T[size]; try { std::copy(item, item + count, buff); } catch(...) { delete[] buff; throw; } return buff; } template <typename T> class allocator { protected: allocator(size_t size = 0); ~allocator(); auto swap(allocator & other) -> void; allocator(allocator const &) = delete; auto operator =(allocator const &) -> allocator & = delete; T * ptr_; size_t size_; size_t count_; }; template<typename T> allocator<T>::allocator(size_t size) : ptr_(static_cast<T *>(size == 0 ? nullptr : operator new(size * sizeof(T)))), size_(0), count_(size) { } template<typename T> allocator<T>::~allocator() { delete ptr_; } template<typename T> auto allocator<T>::swap(allocator & other) -> void { std::swap(ptr_, other.ptr_); std::swap(count_, other.count_); std::swap(size_, other.size_); } template <typename T> class stack : protected allocator<T> { public: stack(); //noexcept stack(stack const &); //strong ~stack(); //noexcept size_t count() const; //noexcept auto push(T const &) -> void; //strong void pop(); //strong const T& top(); //strong auto operator=(stack const & right)->stack &; //strong auto empty() const -> bool; //noexcept }; template <typename T> size_t stack<T>::count() const { return allocator<T>::count_; } template <typename T> stack<T>::stack():allocator<T>(){} { } template <typename T> stack<T>::stack(const stack& item) : allocator<T>(item.size_){ allocator<T>::ptr_ = newcopy(item.allocator<T>::ptr_, item.allocator<T>::count_, item.allocator<T>::size_); allocator<T>::count_ = item.allocator<T>::count_; }; template <typename T> stack<T>::~stack() { } template<typename T> auto stack<T>::push(T const & item) -> void { if (allocator<T>::count_ == allocator<T>::size_) { T * buff = newcopy(allocator<T>::ptr_, allocator<T>::count_, allocator<T>::size_ = allocator<T>::size_ * 2 + (allocator<T>::count_ == 0)); delete allocator<T>::ptr_; allocator<T>::ptr_ = buff; allocator<T>::size_ = allocator<T>::size_ * 2 + (allocator<T>::count_ == 0) ; } allocator<T>::ptr_[allocator<T>::count_] = item; ++allocator<T>::count_; } template<typename T> void stack<T>::pop() { if (allocator::count_ == 0) { throw std::logic_error("Stack is empty!"); } else { allocator::count_--; } } template<typename T> const T& stack<T>::top() { if (allocator::count_ == 0) { throw ("Stack is empty!"); } return allocator::ptr_[allocator::count_ - 1]; } template<typename T> auto stack<T>::operator=(stack const & right) -> stack & { if (this != &right) { T* buff = newcopy(right.allocator<T>::ptr_, right.allocator<T>::size_, right.allocator<T>::count_); delete[] allocator<T>::ptr_; allocator<T>::ptr = buff; allocator<T>::count_ = right.allocator<T>::count_; allocator<T>::size_ = right.allocator<T>::size_; } return *this; } template<typename T> auto stack<T>::empty() const -> bool{ if (allocator::count_ == 0){ return true; } else{ return false; } } #endif <|endoftext|>
<commit_before>#include "allocator.hpp" template <typename T> class stack : private allocator<T> { public: stack(size_t size = 0); /*noexcept*/ stack(const stack & _stack); /*strong*/ stack& operator=(const stack & _stack); /*strong*/ size_t count() const; /*noexcept*/ void push(T const &); /*strong*/ const T& top() const; /*strong*/ void pop(); /*strong*/ bool empty() { return this->count_ == 0; } /*noexcept*/ ~stack(); /*noexcept*/ }; template<typename T> stack<T>::stack(size_t size = 0) : allocator(size) { ; } template<typename T> stack<T>::stack(const stack & _stack) /*strong*/ { this->ptr_ = operatorNewCopiedArray(_stack.ptr_, _stack.count_, _stack.size_); this->size_ = _stack.size_; this->count_ = _stack.count_; } template<typename T> stack<T>& stack<T>::operator=(const stack & _stack) /*strong*/ { if (this != &_stack) { stack(_stack).swap(*this); /*T* midterm = newCopiedArray(_stack.ptr_, _stack.count_, _stack.size_); delete[] this->ptr_; this->ptr_ = midterm; this->count_ = _stack.count_; this->size_ = _stack.size_;*/ } return *this; } template<typename T> size_t stack<T>::count() const /*noexcept*/ { return this->count_; } template<typename T> void stack<T>::push(T const & new_element) /*strong*/ { if (this->count_ >= this->size_) { size_t new_size = (this->size_ * 3) / 2 + 1; T* new_array = operatorNewCopiedArray(this->ptr_, this->count_, new_size); try { construct(&new_array[this->count_], new_element); } catch (...) { destroy(new_array, new_array + this->count_); ::operator delete(new_array); throw; } destroy(this->ptr_, this->ptr_ + this->count_); ::operator delete(this->ptr_); this->ptr_ = new_array; this->size_ = new_size; } else { construct(&(this->ptr_[this->count_]), new_element); } this->count_++; } template<typename T> const T& stack<T>::top() const /*strong*/ //I don't understand first const { if (this->count_ == 0) { throw ("top: count_ == 0"); } return this->ptr_[this->count_ - 1]; } template<typename T> void stack<T>::pop() /*strong*/ { if (this->count_ == 0) { throw("pop(): count_ == 0"); } this->count_--; } template<typename T> stack<T>::~stack() /*noexcept*/ { destroy(this->ptr_, this->ptr_ + this->count_); } <commit_msg>Update stack.hpp<commit_after>#include "allocator.hpp" template <typename T> class stack : private allocator<T> { public: stack(size_t size = 0); /*noexcept*/ stack(const stack & _stack); /*strong*/ stack& operator=(const stack & _stack); /*strong*/ size_t count() const; /*noexcept*/ void push(T const &); /*strong*/ const T & top() const; /*strong*/ void pop(); /*strong*/ bool empty() { return this->count_ == 0; } /*noexcept*/ ~stack(); /*noexcept*/ }; template<typename T> stack<T>::stack(size_t size) : allocator(size) { ; } template<typename T> stack<T>::stack(const stack & _stack) /*strong*/ { this->ptr_ = operatorNewCopiedArray(_stack.ptr_, _stack.count_, _stack.size_); this->size_ = _stack.size_; this->count_ = _stack.count_; } template<typename T> stack<T> & stack<T>::operator=(const stack & _stack) /*strong*/ { if (this != &_stack) { stack(_stack).swap(*this); /*T* midterm = newCopiedArray(_stack.ptr_, _stack.count_, _stack.size_); delete[] this->ptr_; this->ptr_ = midterm; this->count_ = _stack.count_; this->size_ = _stack.size_;*/ } return *this; } template<typename T> size_t stack<T>::count() const /*noexcept*/ { return this->count_; } template <typename T> void stack<T>::push(const T & value) /*strong*/ { if (this->count_ == this->size_) { size_t array_size = (this->size_ * 3) / 2 + 1; stack temp(array_size); while (temp.count() < this->count_) { temp.push(this->ptr_[temp.count()]); } this->swap(temp); } construct(this->ptr_ + this->count_, value); ++this->count_; } template<typename T> const T & stack<T>::top() const /*strong*/ { if (this->count_ == 0) { throw ("top: count_ == 0"); } return this->ptr_[this->count_ - 1]; } template<typename T> void stack<T>::pop() /*strong*/ { if (this->count_ == 0) { throw("pop(): count_ == 0"); } destroy(&(this->ptr_[this->count_ - 1])); this->count_--; } template<typename T> stack<T>::~stack() /*noexcept*/ { destroy(this->ptr_, this->ptr_ + this->count_); } <|endoftext|>
<commit_before>#if !defined(DOUBLETAKE_XPHEAP_H) #define DOUBLETAKE_XPHEAP_H /* * @file xpheap.h * @brief A heap optimized to reduce the likelihood of false sharing. * @author Tongping Liu <http://www.cs.umass.edu/~tonyliu> */ #include <assert.h> #include <stddef.h> #include <new> #include "log.hh" #include "objectheader.hh" #include "sentinelmap.hh" #include "xdefines.hh" // Include all of heaplayers #include "heaplayers.h" template <class SourceHeap> class AdaptAppHeap : public SourceHeap { public: void* malloc(size_t sz) { void *ptr; // We are adding one objectHeader and two "canary" words along the object // The layout will be: objectHeader + "canary" + Object + "canary". #if defined(DETECT_OVERFLOW) || defined(DETECT_MEMORY_LEAKS) ptr = SourceHeap::malloc(sz + sizeof(objectHeader) + 2 * xdefines::SENTINEL_SIZE); #else ptr = SourceHeap::malloc(sz + sizeof(objectHeader)); #endif if(!ptr) { return NULL; } // fprintf(stderr, "AdaptAppHeap malloc sz %lx ptr %p\n", sz, ptr); // Set the objectHeader. objectHeader* o = new (ptr) objectHeader(sz); void* newptr = getPointer(o); // Now we are adding two sentinels and mark them on the shared bitmap. // PRINF("AdaptAppHeap malloc sz %d ptr %p nextp %lx\n", sz, ptr, (intptr_t)ptr + sz + // sizeof(objectHeader) + 2 * xdefines::SENTINEL_SIZE); #if defined(DETECT_OVERFLOW) || defined(DETECT_MEMORY_LEAKS) sentinelmap::getInstance().setupSentinels(newptr, sz); #endif assert(getSize(newptr) == sz); // PRINF("NEWSOURCEHEAP: sz is %x - %d, newptr %p\n", sz, sz, newptr); return newptr; } void free(void* ptr) { SourceHeap::free((void*)getObject(ptr)); } size_t getSize(void* ptr) { objectHeader* o = getObject(ptr); size_t sz = o->getSize(); if(sz == 0) { PRINT("Object size cannot be zero\n"); abort(); } return sz; } private: static objectHeader* getObject(void* ptr) { objectHeader* o = (objectHeader*)ptr; return (o - 1); } static void* getPointer(objectHeader* o) { return (void*)(o + 1); } }; template <class SourceHeap, int Chunky> class KingsleyStyleHeap : public HL::ANSIWrapper< HL::StrictSegHeap<Kingsley::NUMBINS, Kingsley::size2Class, Kingsley::class2Size, HL::AdaptHeap<HL::SLList, AdaptAppHeap<SourceHeap>>, AdaptAppHeap<HL::ZoneHeap<SourceHeap, Chunky>>>> { private: typedef HL::ANSIWrapper< HL::StrictSegHeap<Kingsley::NUMBINS, Kingsley::size2Class, Kingsley::class2Size, HL::AdaptHeap<HL::SLList, AdaptAppHeap<SourceHeap>>, AdaptAppHeap<HL::ZoneHeap<SourceHeap, Chunky>>>> SuperHeap; public: KingsleyStyleHeap() {} private: // We want that a single heap's metadata are on different page // to avoid conflicts on one page // char buf[4096 - (sizeof(SuperHeap) % 4096)]; }; // Different processes will have a different heap. // class PerThreadHeap : public TheHeapType { template <int NumHeaps, class TheHeapType> class PerThreadHeap { public: PerThreadHeap() { // PRINF("TheHeapType size is %ld\n", sizeof(TheHeapType)); } void* malloc(int ind, size_t sz) { // PRINF("PerThreadheap malloc ind %d sz %d _heap[ind] %p\n", ind, sz, &_heap[ind]); // Try to get memory from the local heap first. void* ptr = _heap[ind].malloc(sz); return ptr; } // Here, we will give one block of memory back to the originated process related heap. void free(int ind, void* ptr) { REQUIRE(ind < NumHeaps, "Invalid free status"); _heap[ind].free(ptr); // PRINF("now first word is %lx\n", *((unsigned long*)ptr)); } // For getSize, it doesn't matter which heap is used // since they are the same size_t getSize(void* ptr) { //fprintf(stderr, "perthreadheap getSize %p\n", ptr); return _heap[0].getSize(ptr); } private: TheHeapType _heap[NumHeaps]; }; // Protect heap template <class SourceHeap> class xpheap : public SourceHeap { typedef PerThreadHeap<xdefines::NUM_HEAPS, KingsleyStyleHeap<SourceHeap, xdefines::USER_HEAP_CHUNK>> SuperHeap; // typedef PerThreadHeap<xdefines::NUM_HEAPS, KingsleyStyleHeap<SourceHeap, // AdaptAppHeap<SourceHeap>, xdefines::USER_HEAP_CHUNK> > public: xpheap() {} void* initialize(void* start, size_t heapsize) { int metasize = alignup(sizeof(SuperHeap), xdefines::PageSize); // Initialize the SourceHeap before malloc from there. char* base = (char*)SourceHeap::initialize(start, heapsize, metasize); REQUIRE(base != NULL, "Failed to allocate memory for heap metadata"); _heap = new (base) SuperHeap; // PRINF("xpheap calling sourceHeap::malloc size %lx base %p metasize %lx\n", metasize, base, // metasize); // Get the heap start and heap end; _heapStart = SourceHeap::getHeapStart(); _heapEnd = SourceHeap::getHeapEnd(); // Sanity check related information #if defined(DETECT_OVERFLOW) || defined(DETECT_MEMORY_LEAKS) void* sentinelmapStart; size_t sentinelmapSize; sentinelmapStart = _heapStart; sentinelmapSize = xdefines::USER_HEAP_SIZE; // PRINF("INITIAT: sentinelmapStart %p _heapStart %p original size %lx\n", sentinelmapStart, // _heapStart, xdefines::USER_HEAP_SIZE); // Initialize bitmap sentinelmap::getInstance().initialize(sentinelmapStart, sentinelmapSize); #endif return (void*)_heapStart; // base = (char *)malloc(0, 4); } // Performing the actual sanity check. bool checkHeapOverflow() { void* heapEnd = (void*)SourceHeap::getHeapPosition(); return SourceHeap::checkHeapOverflow(heapEnd); } void recoverMemory() { void* heapEnd = (void*)SourceHeap::getHeapPosition(); // PRINF("recoverMemory, heapEnd %p\n", heapEnd); SourceHeap::recoverMemory(heapEnd); } void backup() { void* heapEnd = (void*)SourceHeap::getHeapPosition(); return SourceHeap::backup(heapEnd); } void* getHeapEnd() { return (void*)SourceHeap::getHeapPosition(); } void* malloc(size_t size) { // printf("malloc in xpheap with size %d\n", size); return _heap->malloc(getThreadIndex(), size); } void free(void* ptr) { int tid = getThreadIndex(); #ifndef DETECT_USAGE_AFTER_FREE _heap->free(tid, ptr); #else size_t size = getSize(ptr); // Adding this to the quarantine list if(addThreadQuarantineList(ptr, size) == false) { // If an object is too large, we simply freed this object. _heap->free(tid, ptr); } #endif } void realfree(void* ptr) { _heap->free(getThreadIndex(), ptr); } size_t getSize(void* ptr) { //fprintf(stderr, "xheap getSize ptr %p\n", ptr); return _heap->getSize(ptr); } bool inRange(void* addr) { return ((addr >= _heapStart) && (addr <= _heapEnd)) ? true : false; } private: SuperHeap* _heap; void* _heapStart; void* _heapEnd; }; #endif <commit_msg>xpheap: define MALLOC_TRACE to 0<commit_after>#if !defined(DOUBLETAKE_XPHEAP_H) #define DOUBLETAKE_XPHEAP_H /* * @file xpheap.h * @brief A heap optimized to reduce the likelihood of false sharing. * @author Tongping Liu <http://www.cs.umass.edu/~tonyliu> */ #include <assert.h> #include <stddef.h> #include <new> #include "log.hh" #include "objectheader.hh" #include "sentinelmap.hh" #include "xdefines.hh" // Include all of heaplayers #define MALLOC_TRACE 0 #include "heaplayers.h" template <class SourceHeap> class AdaptAppHeap : public SourceHeap { public: void* malloc(size_t sz) { void *ptr; // We are adding one objectHeader and two "canary" words along the object // The layout will be: objectHeader + "canary" + Object + "canary". #if defined(DETECT_OVERFLOW) || defined(DETECT_MEMORY_LEAKS) ptr = SourceHeap::malloc(sz + sizeof(objectHeader) + 2 * xdefines::SENTINEL_SIZE); #else ptr = SourceHeap::malloc(sz + sizeof(objectHeader)); #endif if(!ptr) { return NULL; } // fprintf(stderr, "AdaptAppHeap malloc sz %lx ptr %p\n", sz, ptr); // Set the objectHeader. objectHeader* o = new (ptr) objectHeader(sz); void* newptr = getPointer(o); // Now we are adding two sentinels and mark them on the shared bitmap. // PRINF("AdaptAppHeap malloc sz %d ptr %p nextp %lx\n", sz, ptr, (intptr_t)ptr + sz + // sizeof(objectHeader) + 2 * xdefines::SENTINEL_SIZE); #if defined(DETECT_OVERFLOW) || defined(DETECT_MEMORY_LEAKS) sentinelmap::getInstance().setupSentinels(newptr, sz); #endif assert(getSize(newptr) == sz); // PRINF("NEWSOURCEHEAP: sz is %x - %d, newptr %p\n", sz, sz, newptr); return newptr; } void free(void* ptr) { SourceHeap::free((void*)getObject(ptr)); } size_t getSize(void* ptr) { objectHeader* o = getObject(ptr); size_t sz = o->getSize(); if(sz == 0) { PRINT("Object size cannot be zero\n"); abort(); } return sz; } private: static objectHeader* getObject(void* ptr) { objectHeader* o = (objectHeader*)ptr; return (o - 1); } static void* getPointer(objectHeader* o) { return (void*)(o + 1); } }; template <class SourceHeap, int Chunky> class KingsleyStyleHeap : public HL::ANSIWrapper< HL::StrictSegHeap<Kingsley::NUMBINS, Kingsley::size2Class, Kingsley::class2Size, HL::AdaptHeap<HL::SLList, AdaptAppHeap<SourceHeap>>, AdaptAppHeap<HL::ZoneHeap<SourceHeap, Chunky>>>> { private: typedef HL::ANSIWrapper< HL::StrictSegHeap<Kingsley::NUMBINS, Kingsley::size2Class, Kingsley::class2Size, HL::AdaptHeap<HL::SLList, AdaptAppHeap<SourceHeap>>, AdaptAppHeap<HL::ZoneHeap<SourceHeap, Chunky>>>> SuperHeap; public: KingsleyStyleHeap() {} private: // We want that a single heap's metadata are on different page // to avoid conflicts on one page // char buf[4096 - (sizeof(SuperHeap) % 4096)]; }; // Different processes will have a different heap. // class PerThreadHeap : public TheHeapType { template <int NumHeaps, class TheHeapType> class PerThreadHeap { public: PerThreadHeap() { // PRINF("TheHeapType size is %ld\n", sizeof(TheHeapType)); } void* malloc(int ind, size_t sz) { // PRINF("PerThreadheap malloc ind %d sz %d _heap[ind] %p\n", ind, sz, &_heap[ind]); // Try to get memory from the local heap first. void* ptr = _heap[ind].malloc(sz); return ptr; } // Here, we will give one block of memory back to the originated process related heap. void free(int ind, void* ptr) { REQUIRE(ind < NumHeaps, "Invalid free status"); _heap[ind].free(ptr); // PRINF("now first word is %lx\n", *((unsigned long*)ptr)); } // For getSize, it doesn't matter which heap is used // since they are the same size_t getSize(void* ptr) { //fprintf(stderr, "perthreadheap getSize %p\n", ptr); return _heap[0].getSize(ptr); } private: TheHeapType _heap[NumHeaps]; }; // Protect heap template <class SourceHeap> class xpheap : public SourceHeap { typedef PerThreadHeap<xdefines::NUM_HEAPS, KingsleyStyleHeap<SourceHeap, xdefines::USER_HEAP_CHUNK>> SuperHeap; // typedef PerThreadHeap<xdefines::NUM_HEAPS, KingsleyStyleHeap<SourceHeap, // AdaptAppHeap<SourceHeap>, xdefines::USER_HEAP_CHUNK> > public: xpheap() {} void* initialize(void* start, size_t heapsize) { int metasize = alignup(sizeof(SuperHeap), xdefines::PageSize); // Initialize the SourceHeap before malloc from there. char* base = (char*)SourceHeap::initialize(start, heapsize, metasize); REQUIRE(base != NULL, "Failed to allocate memory for heap metadata"); _heap = new (base) SuperHeap; // PRINF("xpheap calling sourceHeap::malloc size %lx base %p metasize %lx\n", metasize, base, // metasize); // Get the heap start and heap end; _heapStart = SourceHeap::getHeapStart(); _heapEnd = SourceHeap::getHeapEnd(); // Sanity check related information #if defined(DETECT_OVERFLOW) || defined(DETECT_MEMORY_LEAKS) void* sentinelmapStart; size_t sentinelmapSize; sentinelmapStart = _heapStart; sentinelmapSize = xdefines::USER_HEAP_SIZE; // PRINF("INITIAT: sentinelmapStart %p _heapStart %p original size %lx\n", sentinelmapStart, // _heapStart, xdefines::USER_HEAP_SIZE); // Initialize bitmap sentinelmap::getInstance().initialize(sentinelmapStart, sentinelmapSize); #endif return (void*)_heapStart; // base = (char *)malloc(0, 4); } // Performing the actual sanity check. bool checkHeapOverflow() { void* heapEnd = (void*)SourceHeap::getHeapPosition(); return SourceHeap::checkHeapOverflow(heapEnd); } void recoverMemory() { void* heapEnd = (void*)SourceHeap::getHeapPosition(); // PRINF("recoverMemory, heapEnd %p\n", heapEnd); SourceHeap::recoverMemory(heapEnd); } void backup() { void* heapEnd = (void*)SourceHeap::getHeapPosition(); return SourceHeap::backup(heapEnd); } void* getHeapEnd() { return (void*)SourceHeap::getHeapPosition(); } void* malloc(size_t size) { // printf("malloc in xpheap with size %d\n", size); return _heap->malloc(getThreadIndex(), size); } void free(void* ptr) { int tid = getThreadIndex(); #ifndef DETECT_USAGE_AFTER_FREE _heap->free(tid, ptr); #else size_t size = getSize(ptr); // Adding this to the quarantine list if(addThreadQuarantineList(ptr, size) == false) { // If an object is too large, we simply freed this object. _heap->free(tid, ptr); } #endif } void realfree(void* ptr) { _heap->free(getThreadIndex(), ptr); } size_t getSize(void* ptr) { //fprintf(stderr, "xheap getSize ptr %p\n", ptr); return _heap->getSize(ptr); } bool inRange(void* addr) { return ((addr >= _heapStart) && (addr <= _heapEnd)) ? true : false; } private: SuperHeap* _heap; void* _heapStart; void* _heapEnd; }; #endif <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/planning_request_adapter/planning_request_adapter.h> #include <moveit/robot_state/conversions.h> #include <class_loader/class_loader.h> #include <moveit/trajectory_processing/trajectory_tools.h> #include <ros/ros.h> namespace default_planner_request_adapters { class FixStartStatePathConstraints : public planning_request_adapter::PlanningRequestAdapter { public: FixStartStatePathConstraints() : planning_request_adapter::PlanningRequestAdapter() { } virtual std::string getDescription() const { return "Fix Start State Path Constraints"; } virtual bool adaptAndPlan(const PlannerFn &planner, const planning_scene::PlanningSceneConstPtr& planning_scene, const planning_interface::MotionPlanRequest &req, planning_interface::MotionPlanResponse &res, std::vector<std::size_t> &added_path_index) const { ROS_DEBUG("Running '%s'", getDescription().c_str()); // get the specified start state robot_state::RobotState start_state = planning_scene->getCurrentState(); robot_state::robotStateMsgToRobotState(*planning_scene->getTransforms(), req.start_state, start_state); // if the start state is otherwise valid but does not meet path constraints if (planning_scene->isStateValid(start_state) && !planning_scene->isStateValid(start_state, req.path_constraints)) { ROS_INFO("Planning to path constraints..."); planning_interface::MotionPlanRequest req2 = req; req2.goal_constraints.resize(1); req2.goal_constraints[0] = req.path_constraints; req2.path_constraints = moveit_msgs::Constraints(); planning_interface::MotionPlanResponse res2; bool solved1 = planner(planning_scene, req2, res2); if (solved1) { planning_interface::MotionPlanRequest req3 = req; ROS_INFO("Planned to path constraints. Resuming original planning request."); // extract the last state of the computed motion plan and set it as the new start state robot_state::robotStateToRobotStateMsg(res2.trajectory_->getLastWayPoint(), req3.start_state); bool solved2 = planner(planning_scene, req3, res); res.planning_time_ += res2.planning_time_; if (solved2) { // we need to append the solution paths. res.trajectory_->append(*res2.trajectory_, 0.0); return true; } else return false; } else { ROS_WARN("Unable to plan to path constraints. Running usual motion plan."); bool result = planner(planning_scene, req, res); res.planning_time_ += res2.planning_time_; return result; } } else { ROS_DEBUG("Path constraints are OK. Running usual motion plan."); return planner(planning_scene, req, res); } } }; } CLASS_LOADER_REGISTER_CLASS(default_planner_request_adapters::FixStartStatePathConstraints, planning_request_adapter::PlanningRequestAdapter); <commit_msg>print the path constraints that fail<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/planning_request_adapter/planning_request_adapter.h> #include <moveit/robot_state/conversions.h> #include <class_loader/class_loader.h> #include <moveit/trajectory_processing/trajectory_tools.h> #include <ros/ros.h> namespace default_planner_request_adapters { class FixStartStatePathConstraints : public planning_request_adapter::PlanningRequestAdapter { public: FixStartStatePathConstraints() : planning_request_adapter::PlanningRequestAdapter() { } virtual std::string getDescription() const { return "Fix Start State Path Constraints"; } virtual bool adaptAndPlan(const PlannerFn &planner, const planning_scene::PlanningSceneConstPtr& planning_scene, const planning_interface::MotionPlanRequest &req, planning_interface::MotionPlanResponse &res, std::vector<std::size_t> &added_path_index) const { ROS_DEBUG("Running '%s'", getDescription().c_str()); // get the specified start state robot_state::RobotState start_state = planning_scene->getCurrentState(); robot_state::robotStateMsgToRobotState(*planning_scene->getTransforms(), req.start_state, start_state); // if the start state is otherwise valid but does not meet path constraints if (planning_scene->isStateValid(start_state, req.group_name) && !planning_scene->isStateValid(start_state, req.path_constraints, req.group_name)) { ROS_INFO("Path constraints not satisfied for start state..."); planning_scene->isStateValid(start_state, req.path_constraints, req.group_name, true); ROS_INFO("Planning to path constraints..."); planning_interface::MotionPlanRequest req2 = req; req2.goal_constraints.resize(1); req2.goal_constraints[0] = req.path_constraints; req2.path_constraints = moveit_msgs::Constraints(); planning_interface::MotionPlanResponse res2; bool solved1 = planner(planning_scene, req2, res2); if (solved1) { planning_interface::MotionPlanRequest req3 = req; ROS_INFO("Planned to path constraints. Resuming original planning request."); // extract the last state of the computed motion plan and set it as the new start state robot_state::robotStateToRobotStateMsg(res2.trajectory_->getLastWayPoint(), req3.start_state); bool solved2 = planner(planning_scene, req3, res); res.planning_time_ += res2.planning_time_; if (solved2) { // we need to append the solution paths. res.trajectory_->append(*res2.trajectory_, 0.0); return true; } else return false; } else { ROS_WARN("Unable to plan to path constraints. Running usual motion plan."); bool result = planner(planning_scene, req, res); res.planning_time_ += res2.planning_time_; return result; } } else { ROS_DEBUG("Path constraints are OK. Running usual motion plan."); return planner(planning_scene, req, res); } } }; } CLASS_LOADER_REGISTER_CLASS(default_planner_request_adapters::FixStartStatePathConstraints, planning_request_adapter::PlanningRequestAdapter); <|endoftext|>
<commit_before>/* * StatZone 1.0.5 * Copyright (c) 2012-2021, Frederic Cambus * https://www.statdns.com * * Created: 2012-02-13 * Last Updated: 2021-03-30 * * StatZone is released under the BSD 2-Clause license * See LICENSE file for details. */ #include <err.h> #include <getopt.h> #include <inttypes.h> #include <signal.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <chrono> #include <iostream> #include <string> #include <unordered_set> #ifdef HAVE_SECCOMP #include <sys/prctl.h> #include <linux/seccomp.h> #include "seccomp.h" #endif #include "compat.hpp" #include "config.hpp" #include "strtolower.hpp" std::chrono::steady_clock::time_point begin, current, elapsed; struct results results; static void error(const char *str) { errx(EXIT_FAILURE, "%s", str); } static void usage() { printf("statzone [-hv] zonefile\n\n" \ "The options are as follows:\n\n" \ " -h Display usage.\n" \ " -v Display version.\n"); } static void summary() { /* Stopping timer */ current = std::chrono::steady_clock::now(); /* Print summary */ std::cerr << "Processed " << results.processedLines << " lines in "; std::cerr << std::chrono::duration_cast<std::chrono::microseconds>(current - begin).count() / 1E6; std::cerr << " seconds." << std::endl; } int main(int argc, char *argv[]) { struct stat zonefile_stat; std::unordered_set<std::string> signed_domains; std::unordered_set<std::string> unique_ns; int opt, token_count; char linebuffer[LINE_LENGTH_MAX]; char *input; std::string domain, previous_domain; char *rdata, *token = NULL, *token_lc = NULL; FILE *zonefile; if (pledge("stdio rpath", NULL) == -1) { err(EXIT_FAILURE, "pledge"); } #ifdef HAVE_SECCOMP if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) { perror("Can't initialize seccomp"); return EXIT_FAILURE; } if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &statzone)) { perror("Can't load seccomp filter"); return EXIT_FAILURE; } #endif #ifdef SIGINFO signal(SIGINFO, summary); #endif while ((opt = getopt(argc, argv, "hv")) != -1) { switch (opt) { case 'h': usage(); return EXIT_SUCCESS; case 'v': printf("%s\n", VERSION); return EXIT_SUCCESS; } } if (optind < argc) { input = argv[optind]; } else { usage(); return EXIT_SUCCESS; } /* Starting timer */ begin = std::chrono::steady_clock::now(); /* Open zone file */ if (!strcmp(input, "-")) { /* Read from standard input */ zonefile = stdin; } else { /* Attempt to read from file */ if (!(zonefile = fopen(input, "r"))) { perror("Can't open zone file"); return EXIT_FAILURE; } } /* Get zone file size */ if (fstat(fileno(zonefile), &zonefile_stat)) { perror("Can't stat zone file"); return EXIT_FAILURE; } while (fgets(linebuffer, LINE_LENGTH_MAX, zonefile)) { if (!*linebuffer) continue; if (*linebuffer == ';') /* Comments */ continue; if (*linebuffer == '$') /* Directives */ continue; token_count = 0; token = strtok(linebuffer, " \t"); if (token) domain = strtolower(token); while (token) { if (*token == ';') { /* Comments */ token = NULL; continue; } token_lc = strtolower(token); if (token_count && !strcmp(token_lc, "nsec")) { token = NULL; continue; } if (token_count && !strcmp(token_lc, "nsec3")) { token = NULL; continue; } if (token_count && !strcmp(token_lc, "rrsig")) { token = NULL; continue; } if (token_count && !strcmp(token_lc, "a")) results.a++; if (token_count && !strcmp(token_lc, "aaaa")) results.aaaa++; if (token_count && !strcmp(token_lc, "ds")) { results.ds++; signed_domains.insert(domain); } if (!strcmp(token_lc, "ns")) { results.ns++; if (previous_domain.empty() || previous_domain.length() != domain.length() || strncmp(domain.c_str(), previous_domain.c_str(), domain.length())) { results.domains++; previous_domain = domain; if (!strncmp(domain.c_str(), "xn--", 4)) results.idn++; } rdata = strtok(NULL, "\n"); if (rdata && strchr(rdata, ' ')) rdata = strtok(NULL, "\n"); if (rdata) unique_ns.insert(rdata); } token = strtok(NULL, " \t"); token_count++; } results.processedLines++; } /* Don't count origin */ if (results.domains) results.domains--; /* Printing CVS values */ std::cout << "---[ CSV values ]--------------------------------------------------------------" << std::endl; std::cout << "IPv4 Glue,IPv6 Glue,NS,Unique NS,DS,Signed,IDNs,Domains" << std::endl; std::cout << results.a << ","; std::cout << results.aaaa << ","; std::cout << results.ns << ","; std::cout << unique_ns.size() << ","; std::cout << results.ds << ","; std::cout << signed_domains.size() << ","; std::cout << results.idn << ","; std::cout << results.domains << std::endl; /* Printing results */ summary(); /* Clean up */ fclose(zonefile); return EXIT_SUCCESS; } <commit_msg>Remove now unused error() function.<commit_after>/* * StatZone 1.0.5 * Copyright (c) 2012-2021, Frederic Cambus * https://www.statdns.com * * Created: 2012-02-13 * Last Updated: 2021-03-30 * * StatZone is released under the BSD 2-Clause license * See LICENSE file for details. */ #include <err.h> #include <getopt.h> #include <inttypes.h> #include <signal.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <chrono> #include <iostream> #include <string> #include <unordered_set> #ifdef HAVE_SECCOMP #include <sys/prctl.h> #include <linux/seccomp.h> #include "seccomp.h" #endif #include "compat.hpp" #include "config.hpp" #include "strtolower.hpp" std::chrono::steady_clock::time_point begin, current, elapsed; struct results results; static void usage() { printf("statzone [-hv] zonefile\n\n" \ "The options are as follows:\n\n" \ " -h Display usage.\n" \ " -v Display version.\n"); } static void summary() { /* Stopping timer */ current = std::chrono::steady_clock::now(); /* Print summary */ std::cerr << "Processed " << results.processedLines << " lines in "; std::cerr << std::chrono::duration_cast<std::chrono::microseconds>(current - begin).count() / 1E6; std::cerr << " seconds." << std::endl; } int main(int argc, char *argv[]) { struct stat zonefile_stat; std::unordered_set<std::string> signed_domains; std::unordered_set<std::string> unique_ns; int opt, token_count; char linebuffer[LINE_LENGTH_MAX]; char *input; std::string domain, previous_domain; char *rdata, *token = NULL, *token_lc = NULL; FILE *zonefile; if (pledge("stdio rpath", NULL) == -1) { err(EXIT_FAILURE, "pledge"); } #ifdef HAVE_SECCOMP if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) { perror("Can't initialize seccomp"); return EXIT_FAILURE; } if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &statzone)) { perror("Can't load seccomp filter"); return EXIT_FAILURE; } #endif #ifdef SIGINFO signal(SIGINFO, summary); #endif while ((opt = getopt(argc, argv, "hv")) != -1) { switch (opt) { case 'h': usage(); return EXIT_SUCCESS; case 'v': printf("%s\n", VERSION); return EXIT_SUCCESS; } } if (optind < argc) { input = argv[optind]; } else { usage(); return EXIT_SUCCESS; } /* Starting timer */ begin = std::chrono::steady_clock::now(); /* Open zone file */ if (!strcmp(input, "-")) { /* Read from standard input */ zonefile = stdin; } else { /* Attempt to read from file */ if (!(zonefile = fopen(input, "r"))) { perror("Can't open zone file"); return EXIT_FAILURE; } } /* Get zone file size */ if (fstat(fileno(zonefile), &zonefile_stat)) { perror("Can't stat zone file"); return EXIT_FAILURE; } while (fgets(linebuffer, LINE_LENGTH_MAX, zonefile)) { if (!*linebuffer) continue; if (*linebuffer == ';') /* Comments */ continue; if (*linebuffer == '$') /* Directives */ continue; token_count = 0; token = strtok(linebuffer, " \t"); if (token) domain = strtolower(token); while (token) { if (*token == ';') { /* Comments */ token = NULL; continue; } token_lc = strtolower(token); if (token_count && !strcmp(token_lc, "nsec")) { token = NULL; continue; } if (token_count && !strcmp(token_lc, "nsec3")) { token = NULL; continue; } if (token_count && !strcmp(token_lc, "rrsig")) { token = NULL; continue; } if (token_count && !strcmp(token_lc, "a")) results.a++; if (token_count && !strcmp(token_lc, "aaaa")) results.aaaa++; if (token_count && !strcmp(token_lc, "ds")) { results.ds++; signed_domains.insert(domain); } if (!strcmp(token_lc, "ns")) { results.ns++; if (previous_domain.empty() || previous_domain.length() != domain.length() || strncmp(domain.c_str(), previous_domain.c_str(), domain.length())) { results.domains++; previous_domain = domain; if (!strncmp(domain.c_str(), "xn--", 4)) results.idn++; } rdata = strtok(NULL, "\n"); if (rdata && strchr(rdata, ' ')) rdata = strtok(NULL, "\n"); if (rdata) unique_ns.insert(rdata); } token = strtok(NULL, " \t"); token_count++; } results.processedLines++; } /* Don't count origin */ if (results.domains) results.domains--; /* Printing CVS values */ std::cout << "---[ CSV values ]--------------------------------------------------------------" << std::endl; std::cout << "IPv4 Glue,IPv6 Glue,NS,Unique NS,DS,Signed,IDNs,Domains" << std::endl; std::cout << results.a << ","; std::cout << results.aaaa << ","; std::cout << results.ns << ","; std::cout << unique_ns.size() << ","; std::cout << results.ds << ","; std::cout << signed_domains.size() << ","; std::cout << results.idn << ","; std::cout << results.domains << std::endl; /* Printing results */ summary(); /* Clean up */ fclose(zonefile); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "twitter.h" #define STR__(x) #x #define STR_(x) STR__(x) // うーむ、 static const int dataStreamVersion = QDataStream::Qt_5_8; Twitter::Twitter(QObject *parent) : QOAuth1(parent) , httpReplyHandler(nullptr) { // 実行するとすぐにポートを開きに行くので遅延させる //setReplyHandler(new QOAuthHttpServerReplyHandler(this)); // https://dev.twitter.com/oauth/reference/post/oauth/request_token setTemporaryCredentialsUrl(QUrl("https://api.twitter.com/oauth/request_token")); // https://dev.twitter.com/oauth/reference/get/oauth/authorize setAuthorizationUrl(QUrl("https://api.twitter.com/oauth/authenticate")); // https://dev.twitter.com/oauth/reference/post/oauth/access_token setTokenCredentialsUrl(QUrl("https://api.twitter.com/oauth/access_token")); connect(this, &QAbstractOAuth::authorizeWithBrowser, [=](QUrl url) { qDebug() << __FUNCTION__ << __LINE__ << url; QUrlQuery query(url); query.addQueryItem("force_login", "true"); //if (!screenName.isEmpty()) { // query.addQueryItem("screen_name", screenName); //} url.setQuery(query); QDesktopServices::openUrl(url); }); connect(this, &QOAuth1::granted, this, &Twitter::authenticated); connect(this, &QOAuth1::granted, this, [=]() { verifyCredentials(); }); connect(this, &QOAuth1::requestFailed, [=](const Error error) { qDebug() << "QOAuth1::requestFailed" << (int)error; }); qDebug() << QString("TWITTER_APP_KEY='%1'").arg(STR_(TWITTER_APP_KEY)); qDebug() << QString("TWITTER_APP_SECRET='%1'").arg(STR_(TWITTER_APP_SECRET)); // QAbstractOAuth::setClientIdentifier() // > qmake ... DEFINES+=TWITTER_APP_KEY="{App key}" // --> https://apps.twitter.com/app/{App key}/keys setClientIdentifier(STR_(TWITTER_APP_KEY)); // QAbstractOAuth::setClientSharedSecret() // > qmake ... DEFINES+=TWITTER_APP_SECRET="{App secret}" // --> https://apps.twitter.com/app/{App key}/keys setClientSharedSecret(STR_(TWITTER_APP_SECRET)); } const QString Twitter::serialize() const { QMap<QString, QVariant> serialized; QByteArray dataBytes; QDataStream out(&dataBytes, QIODevice::WriteOnly); out.setVersion(dataStreamVersion); if (QAbstractOAuth::Status::Granted == status()) { serialized.insert("token", token()); serialized.insert("tokenSecret", tokenSecret()); } serialized.insert("id", m_id); serialized.insert("name", m_name); serialized.insert("screenName", m_screenName); serialized.insert("profileImage", m_icon); out << serialized; return dataBytes.toBase64(); } void Twitter::deserialize(const QString& data) { QMap<QString, QVariant> deserialized; QByteArray dataBytes = QByteArray::fromBase64(data.toUtf8()); QDataStream in(&dataBytes, QIODevice::ReadOnly); in.setVersion(dataStreamVersion); in >> deserialized; m_id = deserialized.value("id").toString(); m_name = deserialized.value("name").toString(); m_screenName = deserialized.value("screenName").toString(); m_icon = deserialized.value("profileImage").value<QIcon>(); QString userToken = deserialized.value("token").toString(); QString userTokenSecret = deserialized.value("tokenSecret").toString(); if (userToken.isEmpty() || userTokenSecret.isEmpty()) { setTokenCredentials("", ""); setStatus(QAbstractOAuth::Status::NotAuthenticated); } else { qDebug() << QString("USER_TOKEN='%1'").arg(userToken); qDebug() << QString("USER_TOKEN_SECRET='%1'").arg(userTokenSecret); setTokenCredentials(userToken, userTokenSecret); setStatus(QAbstractOAuth::Status::Granted); } } void Twitter::authenticate() { // ポートをここでオープン if (!httpReplyHandler) { httpReplyHandler = new QOAuthHttpServerReplyHandler(this); const QString messageHtml = QString("<style>" \ "html, body { padding: 0; margin: 0; } " \ "body { background-color: #f5f8fb; padding: 1em; } " \ "body > div { vertical-align: middle; text-align: center; margin: auto 0; }" \ "</style>" \ "<div><h1>%1</h1><div>%2</div></div>") .arg(qApp->applicationName()) .arg("コールバックを受け取りました。<br />このページは閉じていただいて問題ありません。"); // https://bugreports.qt.io/browse/QTBUG-59725 が修正されるまでこのまま const QString postfixTag = "</body></html>"; const int fixedPaddingSize = messageHtml.toUtf8().length() - messageHtml.length() - postfixTag.length(); //httpReplyHandler->setCallbackText(messageHtml + postfixTag + QString(fixedPaddingSize, '*')); // 本来は httpReplyHandler->setCallbackText(messageHtml); // このようにしたかった setReplyHandler(httpReplyHandler); } // 認証処理開始 grant(); } // OAuth check authentication method bool Twitter::isAuthenticated() const { return !token().isEmpty() && !tokenSecret().isEmpty() && QAbstractOAuth::Status::Granted == status(); } const QString &Twitter::id() const { return m_id; } const QString &Twitter::screenName() const { return m_screenName; } const QString &Twitter::name() const { return m_name; } const QIcon &Twitter::icon() const { return m_icon; } bool Twitter::tweet(const QString& text, const QString& inReplyToStatusId) { // https://dev.twitter.com/rest/reference/post/statuses/update QUrl url("https://api.twitter.com/1.1/statuses/update.json"); QUrlQuery query(url); QVariantMap data; data.insert("status", text); if (!inReplyToStatusId.isEmpty()) { data.insert("in_reply_to_status_id", inReplyToStatusId); } url.setQuery(query); QNetworkReply *reply = post(url, data); connect(reply, &QNetworkReply::finished, this, [=](){ auto reply_ = qobject_cast<QNetworkReply*>(sender()); qDebug() << "finished tweet"; // {\n \"errors\": [\n {\n \"code\": 170,\n \"message\": \"Missing required parameter: status.\"\n }\n ]\n}\n QJsonParseError parseError; const auto resultJson = reply_->readAll(); const auto resultDoc = QJsonDocument::fromJson(resultJson, &parseError); if (parseError.error) { qDebug() << QString(resultJson); qCritical() << "Twitter::tweet() finished Error at:" << parseError.offset << parseError.errorString(); return; } else if (!resultDoc.isObject()) { qDebug() << QString(resultJson).replace(QRegExp(" +"), " "); return; } const auto result = resultDoc.object(); if (result.value("id_str").isUndefined()) { qDebug() << resultDoc.toJson(); return; } qDebug() << "***\n" << QString(resultDoc.toJson()).replace(QRegExp(" +"), " "); const auto tweetId = result.value("id_str").toString(); Q_EMIT tweeted(tweetId); }); return true; } void Twitter::verifyCredentials(bool include_entities, bool skip_status, bool include_email) { // https://dev.twitter.com/rest/reference/get/account/verify_credentials QUrl url("https://api.twitter.com/1.1/account/verify_credentials.json"); QUrlQuery query(url); QVariantMap data; query.addQueryItem("include_entities", include_entities ? "true" : "false"); query.addQueryItem("skip_status", skip_status ? "true" : "false"); query.addQueryItem("include_email", include_email ? "true" : "false"); url.setQuery(query); QNetworkReply *reply = get(url); connect(reply, &QNetworkReply::finished, this, [=](){ auto reply_ = qobject_cast<QNetworkReply*>(sender()); qDebug() << "verifyCredentials finished"; QJsonParseError parseError; const auto resultJson = reply_->readAll(); const auto resultDoc = QJsonDocument::fromJson(resultJson, &parseError); if (parseError.error) { qDebug() << QString(resultJson); qCritical() << "Twitter::tweet() finished Error at:" << parseError.offset << parseError.errorString(); return; } else if (!resultDoc.isObject()) { qDebug() << "!resultDoc.isObject()\n" << QString(resultJson).replace(QRegExp(" +"), " "); return; } const auto result = resultDoc.object(); if (result.value("id_str").isUndefined() || result.value("name").isUndefined() || result.value("screen_name").isUndefined() || result.value("profile_image_url_https").isUndefined()) { qDebug() << "!result.value(\"id_str\").isUndefined()\n" << resultDoc.toJson(); return; } qDebug() << "***\n" << QString(resultDoc.toJson()).replace(QRegExp(" +"), " "); m_id = result.value("id_str").toString(); m_screenName = result.value("screen_name").toString(); m_name = result.value("name").toString(); const auto profileImageUrlHttps = result.value("profile_image_url_https").toString(); qDebug() << m_id; qDebug() << profileImageUrlHttps; // アイコン取得 QNetworkAccessManager *netManager = networkAccessManager(); QNetworkRequest reqIcon; reqIcon.setUrl(QUrl(profileImageUrlHttps)); QNetworkReply *replyIcon = netManager->get(reqIcon); connect(replyIcon, &QNetworkReply::finished, this, [=](){ QImage profileImage; profileImage.loadFromData(replyIcon->readAll()); m_icon = QIcon(QPixmap::fromImage(profileImage)); Q_EMIT verified(); }); }); } <commit_msg>まだ QTBUG-59725 の修正が適用されてないのでバージョンで処理を分ける<commit_after>#include "twitter.h" #define STR__(x) #x #define STR_(x) STR__(x) // うーむ、 static const int dataStreamVersion = QDataStream::Qt_5_8; Twitter::Twitter(QObject *parent) : QOAuth1(parent) , httpReplyHandler(nullptr) { // 実行するとすぐにポートを開きに行くので遅延させる //setReplyHandler(new QOAuthHttpServerReplyHandler(this)); // https://dev.twitter.com/oauth/reference/post/oauth/request_token setTemporaryCredentialsUrl(QUrl("https://api.twitter.com/oauth/request_token")); // https://dev.twitter.com/oauth/reference/get/oauth/authorize setAuthorizationUrl(QUrl("https://api.twitter.com/oauth/authenticate")); // https://dev.twitter.com/oauth/reference/post/oauth/access_token setTokenCredentialsUrl(QUrl("https://api.twitter.com/oauth/access_token")); connect(this, &QAbstractOAuth::authorizeWithBrowser, [=](QUrl url) { qDebug() << __FUNCTION__ << __LINE__ << url; QUrlQuery query(url); query.addQueryItem("force_login", "true"); //if (!screenName.isEmpty()) { // query.addQueryItem("screen_name", screenName); //} url.setQuery(query); QDesktopServices::openUrl(url); }); connect(this, &QOAuth1::granted, this, &Twitter::authenticated); connect(this, &QOAuth1::granted, this, [=]() { verifyCredentials(); }); connect(this, &QOAuth1::requestFailed, [=](const Error error) { qDebug() << "QOAuth1::requestFailed" << (int)error; }); qDebug() << QString("TWITTER_APP_KEY='%1'").arg(STR_(TWITTER_APP_KEY)); qDebug() << QString("TWITTER_APP_SECRET='%1'").arg(STR_(TWITTER_APP_SECRET)); // QAbstractOAuth::setClientIdentifier() // > qmake ... DEFINES+=TWITTER_APP_KEY="{App key}" // --> https://apps.twitter.com/app/{App key}/keys setClientIdentifier(STR_(TWITTER_APP_KEY)); // QAbstractOAuth::setClientSharedSecret() // > qmake ... DEFINES+=TWITTER_APP_SECRET="{App secret}" // --> https://apps.twitter.com/app/{App key}/keys setClientSharedSecret(STR_(TWITTER_APP_SECRET)); } const QString Twitter::serialize() const { QMap<QString, QVariant> serialized; QByteArray dataBytes; QDataStream out(&dataBytes, QIODevice::WriteOnly); out.setVersion(dataStreamVersion); if (QAbstractOAuth::Status::Granted == status()) { serialized.insert("token", token()); serialized.insert("tokenSecret", tokenSecret()); } serialized.insert("id", m_id); serialized.insert("name", m_name); serialized.insert("screenName", m_screenName); serialized.insert("profileImage", m_icon); out << serialized; return dataBytes.toBase64(); } void Twitter::deserialize(const QString& data) { QMap<QString, QVariant> deserialized; QByteArray dataBytes = QByteArray::fromBase64(data.toUtf8()); QDataStream in(&dataBytes, QIODevice::ReadOnly); in.setVersion(dataStreamVersion); in >> deserialized; m_id = deserialized.value("id").toString(); m_name = deserialized.value("name").toString(); m_screenName = deserialized.value("screenName").toString(); m_icon = deserialized.value("profileImage").value<QIcon>(); QString userToken = deserialized.value("token").toString(); QString userTokenSecret = deserialized.value("tokenSecret").toString(); if (userToken.isEmpty() || userTokenSecret.isEmpty()) { setTokenCredentials("", ""); setStatus(QAbstractOAuth::Status::NotAuthenticated); } else { qDebug() << QString("USER_TOKEN='%1'").arg(userToken); qDebug() << QString("USER_TOKEN_SECRET='%1'").arg(userTokenSecret); setTokenCredentials(userToken, userTokenSecret); setStatus(QAbstractOAuth::Status::Granted); } } void Twitter::authenticate() { // ポートをここでオープン if (!httpReplyHandler) { httpReplyHandler = new QOAuthHttpServerReplyHandler(this); const QString messageHtml = QString("<style>" \ "html, body { padding: 0; margin: 0; } " \ "body { background-color: #f5f8fb; padding: 1em; } " \ "body > div { vertical-align: middle; text-align: center; margin: auto 0; }" \ "</style>" \ "<div><h1>%1</h1><div>%2</div></div>") .arg(qApp->applicationName()) .arg("コールバックを受け取りました。<br />このページは閉じていただいて問題ありません。"); #if (QT_VERSION < QT_VERSION_CHECK(5, 9, 0)) // https://bugreports.qt.io/browse/QTBUG-59725 が修正されるまでこのまま const QString postfixTag = "</body></html>"; const int fixedPaddingSize = messageHtml.toUtf8().length() - messageHtml.length() - postfixTag.length(); httpReplyHandler->setCallbackText(messageHtml + postfixTag + QString(fixedPaddingSize, '*')); #else // fix in "5.9.0 Beta 2" // 本来はこのようにしたかった httpReplyHandler->setCallbackText(messageHtml); #endif setReplyHandler(httpReplyHandler); } // 認証処理開始 grant(); } // OAuth check authentication method bool Twitter::isAuthenticated() const { return !token().isEmpty() && !tokenSecret().isEmpty() && QAbstractOAuth::Status::Granted == status(); } const QString &Twitter::id() const { return m_id; } const QString &Twitter::screenName() const { return m_screenName; } const QString &Twitter::name() const { return m_name; } const QIcon &Twitter::icon() const { return m_icon; } bool Twitter::tweet(const QString& text, const QString& inReplyToStatusId) { // https://dev.twitter.com/rest/reference/post/statuses/update QUrl url("https://api.twitter.com/1.1/statuses/update.json"); QUrlQuery query(url); QVariantMap data; data.insert("status", text); if (!inReplyToStatusId.isEmpty()) { data.insert("in_reply_to_status_id", inReplyToStatusId); } url.setQuery(query); QNetworkReply *reply = post(url, data); connect(reply, &QNetworkReply::finished, this, [=](){ auto reply_ = qobject_cast<QNetworkReply*>(sender()); qDebug() << "finished tweet"; // {\n \"errors\": [\n {\n \"code\": 170,\n \"message\": \"Missing required parameter: status.\"\n }\n ]\n}\n QJsonParseError parseError; const auto resultJson = reply_->readAll(); const auto resultDoc = QJsonDocument::fromJson(resultJson, &parseError); if (parseError.error) { qDebug() << QString(resultJson); qCritical() << "Twitter::tweet() finished Error at:" << parseError.offset << parseError.errorString(); return; } else if (!resultDoc.isObject()) { qDebug() << QString(resultJson).replace(QRegExp(" +"), " "); return; } const auto result = resultDoc.object(); if (result.value("id_str").isUndefined()) { qDebug() << resultDoc.toJson(); return; } qDebug() << "***\n" << QString(resultDoc.toJson()).replace(QRegExp(" +"), " "); const auto tweetId = result.value("id_str").toString(); Q_EMIT tweeted(tweetId); }); return true; } void Twitter::verifyCredentials(bool include_entities, bool skip_status, bool include_email) { // https://dev.twitter.com/rest/reference/get/account/verify_credentials QUrl url("https://api.twitter.com/1.1/account/verify_credentials.json"); QUrlQuery query(url); QVariantMap data; query.addQueryItem("include_entities", include_entities ? "true" : "false"); query.addQueryItem("skip_status", skip_status ? "true" : "false"); query.addQueryItem("include_email", include_email ? "true" : "false"); url.setQuery(query); QNetworkReply *reply = get(url); connect(reply, &QNetworkReply::finished, this, [=](){ auto reply_ = qobject_cast<QNetworkReply*>(sender()); qDebug() << "verifyCredentials finished"; QJsonParseError parseError; const auto resultJson = reply_->readAll(); const auto resultDoc = QJsonDocument::fromJson(resultJson, &parseError); if (parseError.error) { qDebug() << QString(resultJson); qCritical() << "Twitter::tweet() finished Error at:" << parseError.offset << parseError.errorString(); return; } else if (!resultDoc.isObject()) { qDebug() << "!resultDoc.isObject()\n" << QString(resultJson).replace(QRegExp(" +"), " "); return; } const auto result = resultDoc.object(); if (result.value("id_str").isUndefined() || result.value("name").isUndefined() || result.value("screen_name").isUndefined() || result.value("profile_image_url_https").isUndefined()) { qDebug() << "!result.value(\"id_str\").isUndefined()\n" << resultDoc.toJson(); return; } qDebug() << "***\n" << QString(resultDoc.toJson()).replace(QRegExp(" +"), " "); m_id = result.value("id_str").toString(); m_screenName = result.value("screen_name").toString(); m_name = result.value("name").toString(); const auto profileImageUrlHttps = result.value("profile_image_url_https").toString(); qDebug() << m_id; qDebug() << profileImageUrlHttps; // アイコン取得 QNetworkAccessManager *netManager = networkAccessManager(); QNetworkRequest reqIcon; reqIcon.setUrl(QUrl(profileImageUrlHttps)); QNetworkReply *replyIcon = netManager->get(reqIcon); connect(replyIcon, &QNetworkReply::finished, this, [=](){ QImage profileImage; profileImage.loadFromData(replyIcon->readAll()); m_icon = QIcon(QPixmap::fromImage(profileImage)); Q_EMIT verified(); }); }); } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/syscoin-config.h> #endif #include <chainparams.h> #include <clientversion.h> #include <compat.h> #include <fs.h> #include <interfaces/chain.h> #include <init.h> #include <noui.h> #include <shutdown.h> #include <util/system.h> #include <util/threadnames.h> #include <util/strencodings.h> #include <stdio.h> // SYSCOIN #include <masternodeconfig.h> const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr; /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * * This is the developer documentation of the reference client for an experimental new digital currency called Syscoin, * which enables instant payments to anyone, anywhere in the world. Syscoin uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * See https://github.com/syscoin/syscoin and https://syscoin.org/ for further information about the project. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ static void WaitForShutdown() { while (!ShutdownRequested()) { MilliSleep(200); } Interrupt(); } ////////////////////////////////////////////////////////////////////////////// // // Start // static bool AppInit(int argc, char* argv[]) { InitInterfaces interfaces; interfaces.chain = interfaces::MakeChain(); bool fRet = false; util::ThreadRename("init"); // // Parameters // // If Qt is used, parameters/syscoin.conf are parsed in qt/syscoin.cpp's main() SetupServerArgs(); std::string error; if (!gArgs.ParseParameters(argc, argv, error)) { tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error.c_str()); return false; } // Process help and version before taking care about datadir if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) { std::string strUsage = PACKAGE_NAME " Daemon version " + FormatFullVersion() + "\n"; if (gArgs.IsArgSet("-version")) { strUsage += FormatParagraph(LicenseInfo()) + "\n"; } else { strUsage += "\nUsage: syscoind [options] Start " PACKAGE_NAME " Daemon\n"; strUsage += "\n" + gArgs.GetHelpMessage(); } tfm::format(std::cout, "%s", strUsage.c_str()); return true; } try { if (!fs::is_directory(GetDataDir(false))) { tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); return false; } if (!gArgs.ReadConfigFiles(error, true)) { tfm::format(std::cerr, "Error reading configuration file: %s\n", error.c_str()); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(gArgs.GetChainName()); } catch (const std::exception& e) { tfm::format(std::cerr, "Error: %s\n", e.what()); return false; } // Error out when loose non-argument tokens are encountered on command line for (int i = 1; i < argc; i++) { if (!IsSwitchChar(argv[i][0])) { tfm::format(std::cerr, "Error: Command line contains unexpected token '%s', see syscoind -h for a list of options.\n", argv[i]); return false; } } // SYSCOIN parse masternode.conf std::string strErr; if(!masternodeConfig.read(strErr)) { fprintf(stderr,"Error reading masternode configuration file: %s\n", strErr.c_str()); return false; } // -server defaults to true for syscoind but not for the GUI so do this here gArgs.SoftSetBoolArg("-server", true); // Set this early so that parameter interactions go to console InitLogging(); InitParameterInteraction(); // SYSCOIN if (!AppInitBasicSetup(argv)) { // InitError will have been called with detailed error, which ends up on console return false; } if (!AppInitParameterInteraction()) { // InitError will have been called with detailed error, which ends up on console return false; } if (!AppInitSanityChecks()) { // InitError will have been called with detailed error, which ends up on console return false; } if (gArgs.GetBoolArg("-daemon", false)) { #if HAVE_DECL_DAEMON #if defined(MAC_OSX) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif tfm::format(std::cout, "Syscoin server starting\n"); // Daemonize if (daemon(1, 0)) { // don't chdir (1), do close FDs (0) tfm::format(std::cerr, "Error: daemon() failed: %s\n", strerror(errno)); return false; } #if defined(MAC_OSX) #pragma GCC diagnostic pop #endif #else tfm::format(std::cerr, "Error: -daemon is not supported on this operating system\n"); return false; #endif // HAVE_DECL_DAEMON } // Lock data directory after daemonization if (!AppInitLockDataDirectory()) { // If locking the data directory failed, exit immediately return false; } fRet = AppInitMain(interfaces); } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(nullptr, "AppInit()"); } if (!fRet) { Interrupt(); } else { WaitForShutdown(); } Shutdown(interfaces); return fRet; } int main(int argc, char* argv[]) { #ifdef WIN32 util::WinCmdLineArgs winArgs; std::tie(argc, argv) = winArgs.get(); #endif SetupEnvironment(); // Connect syscoind signal handlers noui_connect(); return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE); } <commit_msg>use tinyformat not fprintf<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Syscoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/syscoin-config.h> #endif #include <chainparams.h> #include <clientversion.h> #include <compat.h> #include <fs.h> #include <interfaces/chain.h> #include <init.h> #include <noui.h> #include <shutdown.h> #include <util/system.h> #include <util/threadnames.h> #include <util/strencodings.h> #include <stdio.h> // SYSCOIN #include <masternodeconfig.h> const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr; /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * * This is the developer documentation of the reference client for an experimental new digital currency called Syscoin, * which enables instant payments to anyone, anywhere in the world. Syscoin uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * See https://github.com/syscoin/syscoin and https://syscoin.org/ for further information about the project. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ static void WaitForShutdown() { while (!ShutdownRequested()) { MilliSleep(200); } Interrupt(); } ////////////////////////////////////////////////////////////////////////////// // // Start // static bool AppInit(int argc, char* argv[]) { InitInterfaces interfaces; interfaces.chain = interfaces::MakeChain(); bool fRet = false; util::ThreadRename("init"); // // Parameters // // If Qt is used, parameters/syscoin.conf are parsed in qt/syscoin.cpp's main() SetupServerArgs(); std::string error; if (!gArgs.ParseParameters(argc, argv, error)) { tfm::format(std::cerr, "Error parsing command line arguments: %s\n", error.c_str()); return false; } // Process help and version before taking care about datadir if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) { std::string strUsage = PACKAGE_NAME " Daemon version " + FormatFullVersion() + "\n"; if (gArgs.IsArgSet("-version")) { strUsage += FormatParagraph(LicenseInfo()) + "\n"; } else { strUsage += "\nUsage: syscoind [options] Start " PACKAGE_NAME " Daemon\n"; strUsage += "\n" + gArgs.GetHelpMessage(); } tfm::format(std::cout, "%s", strUsage.c_str()); return true; } try { if (!fs::is_directory(GetDataDir(false))) { tfm::format(std::cerr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); return false; } if (!gArgs.ReadConfigFiles(error, true)) { tfm::format(std::cerr, "Error reading configuration file: %s\n", error.c_str()); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(gArgs.GetChainName()); } catch (const std::exception& e) { tfm::format(std::cerr, "Error: %s\n", e.what()); return false; } // Error out when loose non-argument tokens are encountered on command line for (int i = 1; i < argc; i++) { if (!IsSwitchChar(argv[i][0])) { tfm::format(std::cerr, "Error: Command line contains unexpected token '%s', see syscoind -h for a list of options.\n", argv[i]); return false; } } // SYSCOIN parse masternode.conf std::string strErr; if(!masternodeConfig.read(strErr)) { tfm::format(std::cerr,"Error reading masternode configuration file: %s\n", strErr.c_str()); return false; } // -server defaults to true for syscoind but not for the GUI so do this here gArgs.SoftSetBoolArg("-server", true); // Set this early so that parameter interactions go to console InitLogging(); InitParameterInteraction(); // SYSCOIN if (!AppInitBasicSetup(argv)) { // InitError will have been called with detailed error, which ends up on console return false; } if (!AppInitParameterInteraction()) { // InitError will have been called with detailed error, which ends up on console return false; } if (!AppInitSanityChecks()) { // InitError will have been called with detailed error, which ends up on console return false; } if (gArgs.GetBoolArg("-daemon", false)) { #if HAVE_DECL_DAEMON #if defined(MAC_OSX) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif tfm::format(std::cout, "Syscoin server starting\n"); // Daemonize if (daemon(1, 0)) { // don't chdir (1), do close FDs (0) tfm::format(std::cerr, "Error: daemon() failed: %s\n", strerror(errno)); return false; } #if defined(MAC_OSX) #pragma GCC diagnostic pop #endif #else tfm::format(std::cerr, "Error: -daemon is not supported on this operating system\n"); return false; #endif // HAVE_DECL_DAEMON } // Lock data directory after daemonization if (!AppInitLockDataDirectory()) { // If locking the data directory failed, exit immediately return false; } fRet = AppInitMain(interfaces); } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(nullptr, "AppInit()"); } if (!fRet) { Interrupt(); } else { WaitForShutdown(); } Shutdown(interfaces); return fRet; } int main(int argc, char* argv[]) { #ifdef WIN32 util::WinCmdLineArgs winArgs; std::tie(argc, argv) = winArgs.get(); #endif SetupEnvironment(); // Connect syscoind signal handlers noui_connect(); return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE); } <|endoftext|>
<commit_before>#include <unistd.h> #include <getopt.h> #include <stdlib.h> #include <time.h> #include <vector> #include <deal.II/base/mpi.h> #include "gtest/gtest.h" #include "test_helpers/gmock_wrapper.h" #include "test_helpers/bart_test_helper.h" int main(int argc, char** argv) { // Parse optional arguments int option_index = 0, c = 0; bool use_mpi = false; std::string filter = ""; const struct option longopts[] = { {"filter", no_argument, NULL, 'f'}, {"report", no_argument, NULL, 'r'}, {"mpi", no_argument, NULL, 'm'}, {NULL, 0, NULL, 0} }; while ((c = getopt_long (argc, argv, "rmd:f:", longopts, &option_index)) != -1) { switch(c) { case 'r': { btest::GlobalBARTTestHelper().SetReport(true); break; } case 'd': { btest::GlobalBARTTestHelper().SetGoldFilesDirectory(optarg); break; } case 'm': { use_mpi = true; break; } case 'f': { filter = optarg; break; } default: break; } } std::vector<const char*> new_argv(argv, argv + argc); if (filter != "") { filter = "--gtest_filter=" + filter; new_argv.push_back(filter.c_str()); } else if (use_mpi) { new_argv.push_back("--gtest_filter=*MPI*"); } else { new_argv.push_back("--gtest_filter=-*MPI*"); } new_argv.push_back(nullptr); argv = const_cast<char**>(new_argv.data()); argc += 1; dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); ::testing::InitGoogleMock(&argc, argv); // Re-seed random number generator for random number tests std::srand(time(NULL)); return RUN_ALL_TESTS(); } <commit_msg>changed filter for MPI only tests to MPIOnly, added removal of non rank-0 listener for GTest<commit_after>#include <unistd.h> #include <getopt.h> #include <stdlib.h> #include <time.h> #include <vector> #include <deal.II/base/mpi.h> #include "gtest/gtest.h" #include "test_helpers/gmock_wrapper.h" #include "test_helpers/bart_test_helper.h" int main(int argc, char** argv) { // Parse optional arguments int option_index = 0, c = 0; bool use_mpi = false; std::string filter = ""; const struct option longopts[] = { {"filter", no_argument, NULL, 'f'}, {"report", no_argument, NULL, 'r'}, {"mpi", no_argument, NULL, 'm'}, {NULL, 0, NULL, 0} }; while ((c = getopt_long (argc, argv, "rmd:f:", longopts, &option_index)) != -1) { switch(c) { case 'r': { btest::GlobalBARTTestHelper().SetReport(true); break; } case 'd': { btest::GlobalBARTTestHelper().SetGoldFilesDirectory(optarg); break; } case 'm': { use_mpi = true; break; } case 'f': { filter = optarg; break; } default: break; } } std::vector<const char*> new_argv(argv, argv + argc); if (filter != "") { filter = "--gtest_filter=" + filter; new_argv.push_back(filter.c_str()); } else if (use_mpi) { new_argv.push_back("--gtest_filter=*MPI*"); } else { new_argv.push_back("--gtest_filter=-*MPIOnly*"); } new_argv.push_back(nullptr); argv = const_cast<char**>(new_argv.data()); argc += 1; dealii::Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1); ::testing::InitGoogleMock(&argc, argv); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); int world_rank; MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); if (world_rank != 0) { delete listeners.Release(listeners.default_result_printer()); } // Re-seed random number generator for random number tests std::srand(time(NULL)); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "color.hpp" #include "ui.hpp" #include "ui-buttons.hpp" #include "ui-label.hpp" #include "ui-textboxes.hpp" #include "ui-toggle.hpp" using namespace std; int WIDTH = 1280; // width of the user window int HEIGHT = 768; // height of the user window char programName[] = "scheduler"; // button info vector<Button> buttons; vector<TextBox> textboxes; vector<Toggle> toggles; vector<Label> labels; const unsigned int MAX_NUM_CHARS_IN_TEXTBOX = 20; void drawWindow() { glClear(GL_COLOR_BUFFER_BIT); // clear the buffer for (vector<Button>::iterator i = buttons.begin(); i != buttons.end(); ++i) i->draw(); for (vector<TextBox>::iterator i = textboxes.begin(); i != textboxes.end(); ++i) i->draw(); for (vector<Label>::iterator i = labels.begin(); i != labels.end(); ++i) i->draw(); for (vector<Toggle>::iterator i = toggles.begin(); i != toggles.end(); ++i) i->draw(); glutSwapBuffers(); // tell the graphics card that we're done. } // close the window and finish the program void exitAll() { int win = glutGetWindow(); glutDestroyWindow(win); exit(0); } // the reshape function handles the case where the user changes the size of the window. We need to fix the coordinate system, so that the drawing area is still the unit square. void reshape(int w, int h) { glViewport(0, 0, (GLsizei) w, (GLsizei) h); WIDTH = w; HEIGHT = h; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0., WIDTH-1, HEIGHT-1, 0., -1.0, 1.0); } // initGlWindow is the function that starts the ball rolling, in terms of getting everything set up and passing control over to the glut library for event handling. It needs to tell the glut library about all the essential functions: what function to call if the window changes shape, what to do to redraw, handle the keyboard, etc. int main() { char *argv[] = { programName }; int argc = sizeof(argv) / sizeof(argv[0]); glutInit(&argc, argv); glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE ); glutInitWindowSize(WIDTH,HEIGHT); glutInitWindowPosition(100,100); glutCreateWindow(programName); // clear the window to black glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); // set up the coordinate system: number of pixels along x and y glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0., WIDTH-1, HEIGHT-1, 0., -1.0, 1.0); // welcome message cout << "Welcome to " << programName << endl; glutDisplayFunc(drawWindow); glutReshapeFunc(reshape); glutMainLoop(); } <commit_msg>Reformat the for loops in ui-test<commit_after>#include "color.hpp" #include "ui.hpp" #include "ui-buttons.hpp" #include "ui-label.hpp" #include "ui-textboxes.hpp" #include "ui-toggle.hpp" using namespace std; int WIDTH = 1280; // width of the user window int HEIGHT = 768; // height of the user window char programName[] = "scheduler"; // button info vector<Button> buttons; vector<TextBox> textboxes; vector<Toggle> toggles; vector<Label> labels; const unsigned int MAX_NUM_CHARS_IN_TEXTBOX = 20; void drawWindow() { glClear(GL_COLOR_BUFFER_BIT); // clear the buffer for (vector<Button>::iterator i = buttons.begin(); i != buttons.end(); ++i) i->draw(); for (vector<TextBox>::iterator i = textboxes.begin(); i != textboxes.end(); ++i) i->draw(); for (vector<Label>::iterator i = labels.begin(); i != labels.end(); ++i) i->draw(); for (vector<Toggle>::iterator i = toggles.begin(); i != toggles.end(); ++i) i->draw(); glutSwapBuffers(); // tell the graphics card that we're done. } // close the window and finish the program void exitAll() { int win = glutGetWindow(); glutDestroyWindow(win); exit(0); } // the reshape function handles the case where the user changes the size of the window. We need to fix the coordinate system, so that the drawing area is still the unit square. void reshape(int w, int h) { glViewport(0, 0, (GLsizei) w, (GLsizei) h); WIDTH = w; HEIGHT = h; glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0., WIDTH-1, HEIGHT-1, 0., -1.0, 1.0); } // initGlWindow is the function that starts the ball rolling, in terms of getting everything set up and passing control over to the glut library for event handling. It needs to tell the glut library about all the essential functions: what function to call if the window changes shape, what to do to redraw, handle the keyboard, etc. int main() { char *argv[] = { programName }; int argc = sizeof(argv) / sizeof(argv[0]); glutInit(&argc, argv); glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE ); glutInitWindowSize(WIDTH,HEIGHT); glutInitWindowPosition(100,100); glutCreateWindow(programName); // clear the window to black glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); // set up the coordinate system: number of pixels along x and y glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0., WIDTH-1, HEIGHT-1, 0., -1.0, 1.0); // welcome message cout << "Welcome to " << programName << endl; glutDisplayFunc(drawWindow); glutReshapeFunc(reshape); glutMainLoop(); } <|endoftext|>
<commit_before>// @(#)root/gl:$Name: $:$Id: TGLText.cxx,v 1.3 2007/06/21 17:27:55 brun Exp $ // Author: Olivier Couet 12/04/2007 /************************************************************************* * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "TROOT.h" #include "TError.h" #include "TGLText.h" #include "TColor.h" #include "TSystem.h" #include "TEnv.h" #include "FTGLExtrdFont.h" #include "FTGLOutlineFont.h" #include "FTGLPolygonFont.h" #include "FTGLTextureFont.h" #include "FTGLPixmapFont.h" #include "FTGLBitmapFont.h" #define FTGL_BITMAP 0 #define FTGL_PIXMAP 1 #define FTGL_OUTLINE 2 #define FTGL_POLYGON 3 #define FTGL_EXTRUDE 4 #define FTGL_TEXTURE 5 ClassImp(TGLText) //______________________________________________________________________________ TGLText::TGLText() { fX = 0; fY = 0; fZ = 0; fAngle1 = 90; fAngle2 = 0; fAngle3 = 0; fGLTextFont = 0; SetGLTextFont(13); // Default font. } //______________________________________________________________________________ TGLText::TGLText(Double_t x, Double_t y, Double_t z, const char * /*text*/) { // TGLext normal constructor. fX = x; fY = y; fZ = z; fAngle1 = 90; fAngle2 = 0; fAngle3 = 0; fGLTextFont = 0; SetGLTextFont(13); // Default font. } //______________________________________________________________________________ TGLText::~TGLText() { if (fGLTextFont) delete fGLTextFont; } //______________________________________________________________________________ void TGLText::PaintGLText(Double_t x, Double_t y, Double_t z, const char *text) { // Draw text if (!fGLTextFont) return; glPushMatrix(); glTranslatef(x, y, z); // Set Text color. TColor *col; Float_t red, green, blue; col = gROOT->GetColor(GetTextColor()); col->GetRGB(red, green, blue); glColor3d(red, green, blue); // Text size Double_t s = GetTextSize(); glScalef(s,s,s); // Text alignment Float_t llx, lly, llz, urx, ury, urz; fGLTextFont->BBox(text, llx, lly, llz, urx, ury, urz); Short_t halign = fTextAlign/10; Short_t valign = fTextAlign - 10*halign; Float_t dx = 0, dy = 0; switch (halign) { case 1 : dx = 0 ; break; case 2 : dx = -urx/2; break; case 3 : dx = -urx ; break; } switch (valign) { case 1 : dy = 0 ; break; case 2 : dy = -ury/2; break; case 3 : dy = -ury ; break; } glTranslatef(dx, dy, 0); //In XY plane glRotatef(fAngle1,1.,0.,0.); //In XZ plane glRotatef(fAngle2,0.,1.,0.); //In YZ plane glRotatef(fAngle3,0.,0.,1.); // Render text fGLTextFont->Render(text); glPopMatrix(); } //______________________________________________________________________________ void TGLText::PaintBBox(const char *text) { Float_t llx, lly, llz, urx, ury, urz; fGLTextFont->BBox(text, llx, lly, llz, urx, ury, urz); glBegin(GL_LINES); glVertex3f( 0, 0, 0); glVertex3f( urx, 0, 0); glVertex3f( 0, 0, 0); glVertex3f( 0, ury, 0); glVertex3f( 0, ury, 0); glVertex3f( urx, ury, 0); glVertex3f( urx, ury, 0); glVertex3f( urx, 0, 0); glEnd(); } //______________________________________________________________________________ void TGLText::BBox(const char* string, float& llx, float& lly, float& llz, float& urx, float& ury, float& urz) { // Calculate bounding-box for given string. fGLTextFont->BBox(string, llx, lly, lly, urx, ury, urz); } //______________________________________________________________________________ void TGLText::SetGLTextAngles(Double_t a1, Double_t a2, Double_t a3) { // Set the text rotation angles. fAngle1 = a1; fAngle2 = a2; fAngle3 = a3; } //______________________________________________________________________________ void TGLText::SetGLTextFont(Font_t fontnumber) { int fontid = fontnumber / 10; char *fontname=0; if (fontid == 0) fontname = "arialbd.ttf"; if (fontid == 1) fontname = "timesi.ttf"; if (fontid == 2) fontname = "timesbd.ttf"; if (fontid == 3) fontname = "timesbi.ttf"; if (fontid == 4) fontname = "arial.ttf"; if (fontid == 5) fontname = "ariali.ttf"; if (fontid == 6) fontname = "arialbd.ttf"; if (fontid == 7) fontname = "arialbi.ttf"; if (fontid == 8) fontname = "cour.ttf"; if (fontid == 9) fontname = "couri.ttf"; if (fontid == 10) fontname = "courbd.ttf"; if (fontid == 11) fontname = "courbi.ttf"; if (fontid == 12) fontname = "symbol.ttf"; if (fontid == 13) fontname = "times.ttf"; if (fontid == 14) fontname = "wingding.ttf"; // try to load font (font must be in Root.TTFontPath resource) const char *ttpath = gEnv->GetValue("Root.TTFontPath", # ifdef TTFFONTDIR TTFFONTDIR # else "$(ROOTSYS)/fonts" # endif ); char *ttfont = gSystem->Which(ttpath, fontname, kReadPermission); if (fGLTextFont) delete fGLTextFont; // fGLTextFont = new FTGLOutlineFont(ttfont); fGLTextFont = new FTGLPolygonFont(ttfont); if (!fGLTextFont->FaceSize(1)) Error("SetGLTextFont","Cannot set FTGL::FaceSize"), delete [] ttfont; } <commit_msg>From Axel: - Fix a typo in BBox.<commit_after>// @(#)root/gl:$Name: $:$Id: TGLText.cxx,v 1.4 2007/07/23 15:10:17 rdm Exp $ // Author: Olivier Couet 12/04/2007 /************************************************************************* * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include "Riostream.h" #include "TROOT.h" #include "TError.h" #include "TGLText.h" #include "TColor.h" #include "TSystem.h" #include "TEnv.h" #include "FTGLExtrdFont.h" #include "FTGLOutlineFont.h" #include "FTGLPolygonFont.h" #include "FTGLTextureFont.h" #include "FTGLPixmapFont.h" #include "FTGLBitmapFont.h" #define FTGL_BITMAP 0 #define FTGL_PIXMAP 1 #define FTGL_OUTLINE 2 #define FTGL_POLYGON 3 #define FTGL_EXTRUDE 4 #define FTGL_TEXTURE 5 ClassImp(TGLText) //______________________________________________________________________________ TGLText::TGLText() { fX = 0; fY = 0; fZ = 0; fAngle1 = 90; fAngle2 = 0; fAngle3 = 0; fGLTextFont = 0; SetGLTextFont(13); // Default font. } //______________________________________________________________________________ TGLText::TGLText(Double_t x, Double_t y, Double_t z, const char * /*text*/) { // TGLext normal constructor. fX = x; fY = y; fZ = z; fAngle1 = 90; fAngle2 = 0; fAngle3 = 0; fGLTextFont = 0; SetGLTextFont(13); // Default font. } //______________________________________________________________________________ TGLText::~TGLText() { if (fGLTextFont) delete fGLTextFont; } //______________________________________________________________________________ void TGLText::PaintGLText(Double_t x, Double_t y, Double_t z, const char *text) { // Draw text if (!fGLTextFont) return; glPushMatrix(); glTranslatef(x, y, z); // Set Text color. TColor *col; Float_t red, green, blue; col = gROOT->GetColor(GetTextColor()); col->GetRGB(red, green, blue); glColor3d(red, green, blue); // Text size Double_t s = GetTextSize(); glScalef(s,s,s); // Text alignment Float_t llx, lly, llz, urx, ury, urz; fGLTextFont->BBox(text, llx, lly, llz, urx, ury, urz); Short_t halign = fTextAlign/10; Short_t valign = fTextAlign - 10*halign; Float_t dx = 0, dy = 0; switch (halign) { case 1 : dx = 0 ; break; case 2 : dx = -urx/2; break; case 3 : dx = -urx ; break; } switch (valign) { case 1 : dy = 0 ; break; case 2 : dy = -ury/2; break; case 3 : dy = -ury ; break; } glTranslatef(dx, dy, 0); //In XY plane glRotatef(fAngle1,1.,0.,0.); //In XZ plane glRotatef(fAngle2,0.,1.,0.); //In YZ plane glRotatef(fAngle3,0.,0.,1.); // Render text fGLTextFont->Render(text); glPopMatrix(); } //______________________________________________________________________________ void TGLText::PaintBBox(const char *text) { Float_t llx, lly, llz, urx, ury, urz; fGLTextFont->BBox(text, llx, lly, llz, urx, ury, urz); glBegin(GL_LINES); glVertex3f( 0, 0, 0); glVertex3f( urx, 0, 0); glVertex3f( 0, 0, 0); glVertex3f( 0, ury, 0); glVertex3f( 0, ury, 0); glVertex3f( urx, ury, 0); glVertex3f( urx, ury, 0); glVertex3f( urx, 0, 0); glEnd(); } //______________________________________________________________________________ void TGLText::BBox(const char* string, float& llx, float& lly, float& llz, float& urx, float& ury, float& urz) { // Calculate bounding-box for given string. fGLTextFont->BBox(string, llx, lly, llz, urx, ury, urz); } //______________________________________________________________________________ void TGLText::SetGLTextAngles(Double_t a1, Double_t a2, Double_t a3) { // Set the text rotation angles. fAngle1 = a1; fAngle2 = a2; fAngle3 = a3; } //______________________________________________________________________________ void TGLText::SetGLTextFont(Font_t fontnumber) { int fontid = fontnumber / 10; char *fontname=0; if (fontid == 0) fontname = "arialbd.ttf"; if (fontid == 1) fontname = "timesi.ttf"; if (fontid == 2) fontname = "timesbd.ttf"; if (fontid == 3) fontname = "timesbi.ttf"; if (fontid == 4) fontname = "arial.ttf"; if (fontid == 5) fontname = "ariali.ttf"; if (fontid == 6) fontname = "arialbd.ttf"; if (fontid == 7) fontname = "arialbi.ttf"; if (fontid == 8) fontname = "cour.ttf"; if (fontid == 9) fontname = "couri.ttf"; if (fontid == 10) fontname = "courbd.ttf"; if (fontid == 11) fontname = "courbi.ttf"; if (fontid == 12) fontname = "symbol.ttf"; if (fontid == 13) fontname = "times.ttf"; if (fontid == 14) fontname = "wingding.ttf"; // try to load font (font must be in Root.TTFontPath resource) const char *ttpath = gEnv->GetValue("Root.TTFontPath", # ifdef TTFFONTDIR TTFFONTDIR # else "$(ROOTSYS)/fonts" # endif ); char *ttfont = gSystem->Which(ttpath, fontname, kReadPermission); if (fGLTextFont) delete fGLTextFont; // fGLTextFont = new FTGLOutlineFont(ttfont); fGLTextFont = new FTGLPolygonFont(ttfont); if (!fGLTextFont->FaceSize(1)) Error("SetGLTextFont","Cannot set FTGL::FaceSize"), delete [] ttfont; } <|endoftext|>
<commit_before>#include "vlcplugin_gtk.h" #include <gdk/gdkx.h> #include <cstring> static uint32_t get_xid(GtkWidget *widget) { GdkDrawable *video_drawable = gtk_widget_get_window(widget); return (uint32_t)gdk_x11_drawable_get_xid(video_drawable); } VlcPluginGtk::VlcPluginGtk(NPP instance, NPuint16_t mode) : VlcPluginBase(instance, mode), parent(NULL), parent_vbox(NULL), video_container(NULL), toolbar(NULL), popupmenu(NULL), fullscreen_win(NULL), is_fullscreen(false) { memset(&video_xwindow, 0, sizeof(Window)); } VlcPluginGtk::~VlcPluginGtk() { } Display *VlcPluginGtk::get_display() { return ( (NPSetWindowCallbackStruct *) npwindow.ws_info )->display; } void VlcPluginGtk::set_player_window() { libvlc_media_player_set_xwindow(libvlc_media_player, video_xwindow); libvlc_video_set_mouse_input(libvlc_media_player, 0); } void VlcPluginGtk::toggle_fullscreen() { set_fullscreen(!get_fullscreen()); } void VlcPluginGtk::set_fullscreen(int yes) { /* we have to reparent windows */ /* note that the xid of video_container changes after reparenting */ Display *display = get_display(); g_signal_handler_block(video_container, video_container_size_handler_id); if (yes) { XUnmapWindow(display, video_xwindow); XReparentWindow(display, video_xwindow, gdk_x11_get_default_root_xwindow(), 0,0); gtk_widget_reparent(GTK_WIDGET(parent_vbox), GTK_WIDGET(fullscreen_win)); gtk_widget_show(fullscreen_win); gtk_window_fullscreen(GTK_WINDOW(fullscreen_win)); XReparentWindow(display, video_xwindow, get_xid(video_container), 0,0); XMapWindow(display, video_xwindow); } else { XUnmapWindow(display, video_xwindow); XReparentWindow(display, video_xwindow, gdk_x11_get_default_root_xwindow(), 0,0); gtk_widget_hide(fullscreen_win); gtk_widget_reparent(GTK_WIDGET(parent_vbox), GTK_WIDGET(parent)); gtk_widget_show_all(GTK_WIDGET(parent)); XReparentWindow(display, video_xwindow, get_xid(video_container), 0,0); XMapWindow(display, video_xwindow); } // libvlc_set_fullscreen(libvlc_media_player, yes); g_signal_handler_unblock(video_container, video_container_size_handler_id); gtk_widget_queue_resize_no_redraw(video_container); is_fullscreen = yes; } int VlcPluginGtk::get_fullscreen() { return is_fullscreen; } void VlcPluginGtk::show_toolbar() { gtk_box_pack_start(GTK_BOX(parent_vbox), toolbar, false, false, 0); gtk_widget_show_all(toolbar); } void VlcPluginGtk::hide_toolbar() { gtk_widget_hide(toolbar); gtk_container_remove(GTK_CONTAINER(parent_vbox), toolbar); } void VlcPluginGtk::resize_video_xwindow(GdkRectangle *rect) { Display *display = get_display(); XResizeWindow(display, video_xwindow, rect->width, rect->height); } struct tool_actions_t { const gchar *stock_id; vlc_toolbar_clicked_t clicked; }; static const tool_actions_t tool_actions[] = { {GTK_STOCK_MEDIA_PLAY, clicked_Play}, {GTK_STOCK_MEDIA_PAUSE, clicked_Pause}, {GTK_STOCK_MEDIA_STOP, clicked_Stop}, {"gtk-volume-muted", clicked_Mute}, {"gtk-volume-unmuted", clicked_Unmute} }; static void toolbar_handler(GtkToolButton *btn, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; const gchar *stock_id = gtk_tool_button_get_stock_id(btn); for (int i = 0; i < sizeof(tool_actions)/sizeof(tool_actions_t); ++i) { if (!strcmp(stock_id, tool_actions[i].stock_id)) { plugin->control_handler(tool_actions[i].clicked); return; } } fprintf(stderr, "WARNING: No idea what toolbar button you just clicked on (%s)\n", stock_id?stock_id:"NULL"); } static void menu_handler(GtkMenuItem *menuitem, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; const gchar *stock_id = gtk_menu_item_get_label(GTK_MENU_ITEM(menuitem)); for (int i = 0; i < sizeof(tool_actions)/sizeof(tool_actions_t); ++i) { if (!strcmp(stock_id, tool_actions[i].stock_id)) { plugin->control_handler(tool_actions[i].clicked); return; } } fprintf(stderr, "WARNING: No idea what menu item you just clicked on (%s)\n", stock_id?stock_id:"NULL"); } void VlcPluginGtk::popup_menu() { /* construct menu */ GtkWidget *popupmenu = gtk_menu_new(); GtkWidget *menuitem; /* play/pause */ menuitem = gtk_image_menu_item_new_from_stock( playlist_isplaying() ? GTK_STOCK_MEDIA_PAUSE : GTK_STOCK_MEDIA_PLAY, NULL); g_signal_connect(G_OBJECT(menuitem), "activate", G_CALLBACK(menu_handler), this); gtk_menu_shell_append(GTK_MENU_SHELL(popupmenu), menuitem); /* stop */ menuitem = gtk_image_menu_item_new_from_stock( GTK_STOCK_MEDIA_STOP, NULL); g_signal_connect(G_OBJECT(menuitem), "activate", G_CALLBACK(menu_handler), this); gtk_menu_shell_append(GTK_MENU_SHELL(popupmenu), menuitem); gtk_widget_show_all(popupmenu); gtk_menu_attach_to_widget(GTK_MENU(popupmenu), video_container, NULL); gtk_menu_popup(GTK_MENU(popupmenu), NULL, NULL, NULL, NULL, 0, gtk_get_current_event_time()); } static bool video_button_handler(GtkWidget *widget, GdkEventButton *event, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; if (event->button == 3 && event->type == GDK_BUTTON_PRESS) { plugin->popup_menu(); return true; } if (event->button == 1 && event->type == GDK_2BUTTON_PRESS) { plugin->toggle_fullscreen(); } return false; } static bool video_popup_handler(GtkWidget *widget, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; plugin->popup_menu(); return true; } static bool video_size_handler(GtkWidget *widget, GdkRectangle *rect, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; plugin->resize_video_xwindow(rect); return true; } static bool time_slider_handler(GtkRange *range, GtkScrollType scroll, gdouble value, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; libvlc_media_player_set_position(plugin->getMD(), value/100.0); return false; } static bool vol_slider_handler(GtkRange *range, GtkScrollType scroll, gdouble value, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; libvlc_audio_set_volume(plugin->getMD(), value); return false; } static void fullscreen_win_visibility_handler(GtkWidget *widget, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; plugin->set_fullscreen(gtk_widget_get_visible(widget)); } void VlcPluginGtk::update_controls() { GtkToolItem *toolbutton; /* play/pause button */ const gchar *stock_id = playlist_isplaying() ? GTK_STOCK_MEDIA_PAUSE : GTK_STOCK_MEDIA_PLAY; toolbutton = gtk_toolbar_get_nth_item(GTK_TOOLBAR(toolbar), 0); if (strcmp(gtk_tool_button_get_stock_id(GTK_TOOL_BUTTON(toolbutton)), stock_id)) { gtk_tool_button_set_stock_id(GTK_TOOL_BUTTON(toolbutton), stock_id); /* work around firefox not displaying the icon properly after change */ g_object_ref(toolbutton); gtk_container_remove(GTK_CONTAINER(toolbar), GTK_WIDGET(toolbutton)); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), toolbutton, 0); g_object_unref(toolbutton); } /* time slider */ if (!libvlc_media_player || !libvlc_media_player_is_seekable(libvlc_media_player)) { gtk_widget_set_sensitive(time_slider, false); gtk_range_set_value(GTK_RANGE(time_slider), 0); } else { gtk_widget_set_sensitive(time_slider, true); gdouble timepos = 100*libvlc_media_player_get_position(libvlc_media_player); gtk_range_set_value(GTK_RANGE(time_slider), timepos); } gtk_widget_show_all(toolbar); } bool VlcPluginGtk::create_windows() { Window socket = (Window) npwindow.window; GdkColor color_black; gdk_color_parse("black", &color_black); parent = gtk_plug_new(socket); gtk_widget_modify_bg(parent, GTK_STATE_NORMAL, &color_black); parent_vbox = gtk_vbox_new(false, 0); gtk_container_add(GTK_CONTAINER(parent), parent_vbox); video_container = gtk_drawing_area_new(); gtk_widget_modify_bg(video_container, GTK_STATE_NORMAL, &color_black); gtk_widget_add_events(video_container, GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK); g_signal_connect(G_OBJECT(video_container), "button-press-event", G_CALLBACK(video_button_handler), this); g_signal_connect(G_OBJECT(video_container), "popup-menu", G_CALLBACK(video_popup_handler), this); gtk_box_pack_start(GTK_BOX(parent_vbox), video_container, true, true, 0); gtk_widget_show_all(parent); /* fullscreen top-level */ fullscreen_win = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_decorated(GTK_WINDOW(fullscreen_win), false); g_signal_connect(G_OBJECT(fullscreen_win), "delete-event", G_CALLBACK(gtk_widget_hide_on_delete), this); g_signal_connect(G_OBJECT(fullscreen_win), "show", G_CALLBACK(fullscreen_win_visibility_handler), this); g_signal_connect(G_OBJECT(fullscreen_win), "hide", G_CALLBACK(fullscreen_win_visibility_handler), this); /* actual video window */ /* libvlc is handed this window's xid. A raw X window is used because * GTK+ is incapable of reparenting without changing xid */ Display *display = get_display(); int blackColor = BlackPixel(display, DefaultScreen(display)); video_xwindow = XCreateSimpleWindow(display, get_xid(video_container), 0, 0, 1, 1, 0, blackColor, blackColor); XMapWindow(display, video_xwindow); /* connect video_container resizes to video_xwindow */ video_container_size_handler_id = g_signal_connect( G_OBJECT(video_container), "size-allocate", G_CALLBACK(video_size_handler), this); gtk_widget_queue_resize_no_redraw(video_container); /*** TOOLBAR ***/ toolbar = gtk_toolbar_new(); gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS); GtkToolItem *toolitem; /* play/pause */ toolitem = gtk_tool_button_new_from_stock(GTK_STOCK_MEDIA_PLAY); g_signal_connect(G_OBJECT(toolitem), "clicked", G_CALLBACK(toolbar_handler), this); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), toolitem, -1); /* stop */ toolitem = gtk_tool_button_new_from_stock(GTK_STOCK_MEDIA_STOP); g_signal_connect(G_OBJECT(toolitem), "clicked", G_CALLBACK(toolbar_handler), this); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), toolitem, -1); /* time slider */ toolitem = gtk_tool_item_new(); time_slider = gtk_hscale_new_with_range(0, 100, 10); gtk_scale_set_draw_value(GTK_SCALE(time_slider), false); g_signal_connect(G_OBJECT(time_slider), "change-value", G_CALLBACK(time_slider_handler), this); gtk_container_add(GTK_CONTAINER(toolitem), time_slider); gtk_tool_item_set_expand(toolitem, true); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), toolitem, -1); /* volume slider */ toolitem = gtk_tool_item_new(); GtkWidget *vol_slider = gtk_hscale_new_with_range(0, 200, 10); gtk_scale_set_draw_value(GTK_SCALE(vol_slider), false); g_signal_connect(G_OBJECT(vol_slider), "change-value", G_CALLBACK(vol_slider_handler), this); gtk_range_set_value(GTK_RANGE(vol_slider), 100); gtk_widget_set_size_request(vol_slider, 100, -1); gtk_container_add(GTK_CONTAINER(toolitem), vol_slider); gtk_tool_item_set_expand(toolitem, false); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), toolitem, -1); update_controls(); show_toolbar(); return true; } bool VlcPluginGtk::resize_windows() { GtkRequisition req; req.width = npwindow.width; req.height = npwindow.height; gtk_widget_size_request(parent, &req); } bool VlcPluginGtk::destroy_windows() { /* TODO */ } <commit_msg>Minor cleanup<commit_after>#include "vlcplugin_gtk.h" #include <gdk/gdkx.h> #include <cstring> static uint32_t get_xid(GtkWidget *widget) { GdkDrawable *video_drawable = gtk_widget_get_window(widget); return (uint32_t)gdk_x11_drawable_get_xid(video_drawable); } VlcPluginGtk::VlcPluginGtk(NPP instance, NPuint16_t mode) : VlcPluginBase(instance, mode), parent(NULL), parent_vbox(NULL), video_container(NULL), toolbar(NULL), popupmenu(NULL), fullscreen_win(NULL), is_fullscreen(false) { memset(&video_xwindow, 0, sizeof(Window)); } VlcPluginGtk::~VlcPluginGtk() { } Display *VlcPluginGtk::get_display() { return ( (NPSetWindowCallbackStruct *) npwindow.ws_info )->display; } void VlcPluginGtk::set_player_window() { libvlc_media_player_set_xwindow(libvlc_media_player, video_xwindow); libvlc_video_set_mouse_input(libvlc_media_player, 0); } void VlcPluginGtk::toggle_fullscreen() { set_fullscreen(!get_fullscreen()); } void VlcPluginGtk::set_fullscreen(int yes) { /* we have to reparent windows */ /* note that the xid of video_container changes after reparenting */ Display *display = get_display(); g_signal_handler_block(video_container, video_container_size_handler_id); XUnmapWindow(display, video_xwindow); XReparentWindow(display, video_xwindow, gdk_x11_get_default_root_xwindow(), 0,0); if (yes) { gtk_widget_reparent(GTK_WIDGET(parent_vbox), GTK_WIDGET(fullscreen_win)); gtk_widget_show(fullscreen_win); gtk_window_fullscreen(GTK_WINDOW(fullscreen_win)); } else { gtk_widget_hide(fullscreen_win); gtk_widget_reparent(GTK_WIDGET(parent_vbox), GTK_WIDGET(parent)); gtk_widget_show_all(GTK_WIDGET(parent)); } XReparentWindow(display, video_xwindow, get_xid(video_container), 0,0); XMapWindow(display, video_xwindow); // libvlc_set_fullscreen(libvlc_media_player, yes); g_signal_handler_unblock(video_container, video_container_size_handler_id); gtk_widget_queue_resize_no_redraw(video_container); is_fullscreen = yes; } int VlcPluginGtk::get_fullscreen() { return is_fullscreen; } void VlcPluginGtk::show_toolbar() { gtk_box_pack_start(GTK_BOX(parent_vbox), toolbar, false, false, 0); gtk_widget_show_all(toolbar); } void VlcPluginGtk::hide_toolbar() { gtk_widget_hide(toolbar); gtk_container_remove(GTK_CONTAINER(parent_vbox), toolbar); } void VlcPluginGtk::resize_video_xwindow(GdkRectangle *rect) { Display *display = get_display(); XResizeWindow(display, video_xwindow, rect->width, rect->height); } struct tool_actions_t { const gchar *stock_id; vlc_toolbar_clicked_t clicked; }; static const tool_actions_t tool_actions[] = { {GTK_STOCK_MEDIA_PLAY, clicked_Play}, {GTK_STOCK_MEDIA_PAUSE, clicked_Pause}, {GTK_STOCK_MEDIA_STOP, clicked_Stop}, {"gtk-volume-muted", clicked_Mute}, {"gtk-volume-unmuted", clicked_Unmute} }; static void toolbar_handler(GtkToolButton *btn, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; const gchar *stock_id = gtk_tool_button_get_stock_id(btn); for (int i = 0; i < sizeof(tool_actions)/sizeof(tool_actions_t); ++i) { if (!strcmp(stock_id, tool_actions[i].stock_id)) { plugin->control_handler(tool_actions[i].clicked); return; } } fprintf(stderr, "WARNING: No idea what toolbar button you just clicked on (%s)\n", stock_id?stock_id:"NULL"); } static void menu_handler(GtkMenuItem *menuitem, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; const gchar *stock_id = gtk_menu_item_get_label(GTK_MENU_ITEM(menuitem)); for (int i = 0; i < sizeof(tool_actions)/sizeof(tool_actions_t); ++i) { if (!strcmp(stock_id, tool_actions[i].stock_id)) { plugin->control_handler(tool_actions[i].clicked); return; } } fprintf(stderr, "WARNING: No idea what menu item you just clicked on (%s)\n", stock_id?stock_id:"NULL"); } void VlcPluginGtk::popup_menu() { /* construct menu */ GtkWidget *popupmenu = gtk_menu_new(); GtkWidget *menuitem; /* play/pause */ menuitem = gtk_image_menu_item_new_from_stock( playlist_isplaying() ? GTK_STOCK_MEDIA_PAUSE : GTK_STOCK_MEDIA_PLAY, NULL); g_signal_connect(G_OBJECT(menuitem), "activate", G_CALLBACK(menu_handler), this); gtk_menu_shell_append(GTK_MENU_SHELL(popupmenu), menuitem); /* stop */ menuitem = gtk_image_menu_item_new_from_stock( GTK_STOCK_MEDIA_STOP, NULL); g_signal_connect(G_OBJECT(menuitem), "activate", G_CALLBACK(menu_handler), this); gtk_menu_shell_append(GTK_MENU_SHELL(popupmenu), menuitem); gtk_widget_show_all(popupmenu); gtk_menu_attach_to_widget(GTK_MENU(popupmenu), video_container, NULL); gtk_menu_popup(GTK_MENU(popupmenu), NULL, NULL, NULL, NULL, 0, gtk_get_current_event_time()); } static bool video_button_handler(GtkWidget *widget, GdkEventButton *event, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; if (event->button == 3 && event->type == GDK_BUTTON_PRESS) { plugin->popup_menu(); return true; } if (event->button == 1 && event->type == GDK_2BUTTON_PRESS) { plugin->toggle_fullscreen(); } return false; } static bool video_popup_handler(GtkWidget *widget, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; plugin->popup_menu(); return true; } static bool video_size_handler(GtkWidget *widget, GdkRectangle *rect, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; plugin->resize_video_xwindow(rect); return true; } static bool time_slider_handler(GtkRange *range, GtkScrollType scroll, gdouble value, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; libvlc_media_player_set_position(plugin->getMD(), value/100.0); return false; } static bool vol_slider_handler(GtkRange *range, GtkScrollType scroll, gdouble value, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; libvlc_audio_set_volume(plugin->getMD(), value); return false; } static void fullscreen_win_visibility_handler(GtkWidget *widget, gpointer user_data) { VlcPluginGtk *plugin = (VlcPluginGtk *) user_data; plugin->set_fullscreen(gtk_widget_get_visible(widget)); } void VlcPluginGtk::update_controls() { GtkToolItem *toolbutton; /* play/pause button */ const gchar *stock_id = playlist_isplaying() ? GTK_STOCK_MEDIA_PAUSE : GTK_STOCK_MEDIA_PLAY; toolbutton = gtk_toolbar_get_nth_item(GTK_TOOLBAR(toolbar), 0); if (strcmp(gtk_tool_button_get_stock_id(GTK_TOOL_BUTTON(toolbutton)), stock_id)) { gtk_tool_button_set_stock_id(GTK_TOOL_BUTTON(toolbutton), stock_id); /* work around firefox not displaying the icon properly after change */ g_object_ref(toolbutton); gtk_container_remove(GTK_CONTAINER(toolbar), GTK_WIDGET(toolbutton)); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), toolbutton, 0); g_object_unref(toolbutton); } /* time slider */ if (!libvlc_media_player || !libvlc_media_player_is_seekable(libvlc_media_player)) { gtk_widget_set_sensitive(time_slider, false); gtk_range_set_value(GTK_RANGE(time_slider), 0); } else { gtk_widget_set_sensitive(time_slider, true); gdouble timepos = 100*libvlc_media_player_get_position(libvlc_media_player); gtk_range_set_value(GTK_RANGE(time_slider), timepos); } gtk_widget_show_all(toolbar); } bool VlcPluginGtk::create_windows() { Window socket = (Window) npwindow.window; GdkColor color_black; gdk_color_parse("black", &color_black); parent = gtk_plug_new(socket); gtk_widget_modify_bg(parent, GTK_STATE_NORMAL, &color_black); parent_vbox = gtk_vbox_new(false, 0); gtk_container_add(GTK_CONTAINER(parent), parent_vbox); video_container = gtk_drawing_area_new(); gtk_widget_modify_bg(video_container, GTK_STATE_NORMAL, &color_black); gtk_widget_add_events(video_container, GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK); g_signal_connect(G_OBJECT(video_container), "button-press-event", G_CALLBACK(video_button_handler), this); g_signal_connect(G_OBJECT(video_container), "popup-menu", G_CALLBACK(video_popup_handler), this); gtk_box_pack_start(GTK_BOX(parent_vbox), video_container, true, true, 0); gtk_widget_show_all(parent); /* fullscreen top-level */ fullscreen_win = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_decorated(GTK_WINDOW(fullscreen_win), false); g_signal_connect(G_OBJECT(fullscreen_win), "delete-event", G_CALLBACK(gtk_widget_hide_on_delete), this); g_signal_connect(G_OBJECT(fullscreen_win), "show", G_CALLBACK(fullscreen_win_visibility_handler), this); g_signal_connect(G_OBJECT(fullscreen_win), "hide", G_CALLBACK(fullscreen_win_visibility_handler), this); /* actual video window */ /* libvlc is handed this window's xid. A raw X window is used because * GTK+ is incapable of reparenting without changing xid */ Display *display = get_display(); int blackColor = BlackPixel(display, DefaultScreen(display)); video_xwindow = XCreateSimpleWindow(display, get_xid(video_container), 0, 0, 1, 1, 0, blackColor, blackColor); XMapWindow(display, video_xwindow); /* connect video_container resizes to video_xwindow */ video_container_size_handler_id = g_signal_connect( G_OBJECT(video_container), "size-allocate", G_CALLBACK(video_size_handler), this); gtk_widget_queue_resize_no_redraw(video_container); /*** TOOLBAR ***/ toolbar = gtk_toolbar_new(); gtk_toolbar_set_style(GTK_TOOLBAR(toolbar), GTK_TOOLBAR_ICONS); GtkToolItem *toolitem; /* play/pause */ toolitem = gtk_tool_button_new_from_stock(GTK_STOCK_MEDIA_PLAY); g_signal_connect(G_OBJECT(toolitem), "clicked", G_CALLBACK(toolbar_handler), this); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), toolitem, -1); /* stop */ toolitem = gtk_tool_button_new_from_stock(GTK_STOCK_MEDIA_STOP); g_signal_connect(G_OBJECT(toolitem), "clicked", G_CALLBACK(toolbar_handler), this); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), toolitem, -1); /* time slider */ toolitem = gtk_tool_item_new(); time_slider = gtk_hscale_new_with_range(0, 100, 10); gtk_scale_set_draw_value(GTK_SCALE(time_slider), false); g_signal_connect(G_OBJECT(time_slider), "change-value", G_CALLBACK(time_slider_handler), this); gtk_container_add(GTK_CONTAINER(toolitem), time_slider); gtk_tool_item_set_expand(toolitem, true); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), toolitem, -1); /* volume slider */ toolitem = gtk_tool_item_new(); GtkWidget *vol_slider = gtk_hscale_new_with_range(0, 200, 10); gtk_scale_set_draw_value(GTK_SCALE(vol_slider), false); g_signal_connect(G_OBJECT(vol_slider), "change-value", G_CALLBACK(vol_slider_handler), this); gtk_range_set_value(GTK_RANGE(vol_slider), 100); gtk_widget_set_size_request(vol_slider, 100, -1); gtk_container_add(GTK_CONTAINER(toolitem), vol_slider); gtk_tool_item_set_expand(toolitem, false); gtk_toolbar_insert(GTK_TOOLBAR(toolbar), toolitem, -1); update_controls(); show_toolbar(); return true; } bool VlcPluginGtk::resize_windows() { GtkRequisition req; req.width = npwindow.width; req.height = npwindow.height; gtk_widget_size_request(parent, &req); } bool VlcPluginGtk::destroy_windows() { /* TODO */ } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "utiltime.h" #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/thread.hpp> using namespace std; static int64_t nMockTime = 0; //! For unit testing int64_t GetTime() { if (nMockTime) return nMockTime; return time(NULL); } void SetMockTime(int64_t nMockTimeIn) { nMockTime = nMockTimeIn; } int64_t GetTimeMillis() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds(); } int64_t GetTimeMicros() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds(); } void MilliSleep(int64_t n) { /** * Boost's sleep_for was uninterruptable when backed by nanosleep from 1.50 * until fixed in 1.52. Use the deprecated sleep method for the broken case. * See: https://svn.boost.org/trac/boost/ticket/7238 */ #if defined(HAVE_WORKING_BOOST_SLEEP_FOR) boost::this_thread::sleep_for(boost::chrono::milliseconds(n)); #elif defined(HAVE_WORKING_BOOST_SLEEP) boost::this_thread::sleep(boost::posix_time::milliseconds(n)); #else //should never get here #error missing boost sleep implementation #endif } std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime) { // std::locale takes ownership of the pointer std::locale loc(std::locale::classic(), new boost::posix_time::time_facet(pszFormat)); std::stringstream ss; ss.imbue(loc); ss << boost::posix_time::from_time_t(nTime); return ss.str(); } <commit_msg>Delete utiltime.cpp<commit_after><|endoftext|>
<commit_before>#pragma once #include <type_traits> #include <algorithm> #include <stdexcept> #include <cstddef> #include <utility> #include <string> #include <vector> #include <uv.h> namespace uvw { namespace details { enum class UVHandleType: std::underlying_type_t<uv_handle_type> { UNKNOWN = UV_UNKNOWN_HANDLE, ASYNC = UV_ASYNC, CHECK = UV_CHECK, FS_EVENT = UV_FS_EVENT, FS_POLL = UV_FS_POLL, HANDLE = UV_HANDLE, IDLE = UV_IDLE, PIPE = UV_NAMED_PIPE, POLL = UV_POLL, PREPARE = UV_PREPARE, PROCESS = UV_PROCESS, STREAM = UV_STREAM, TCP = UV_TCP, TIMER = UV_TIMER, TTY = UV_TTY, UDP = UV_UDP, SIGNAL = UV_SIGNAL, FILE = UV_FILE }; template<typename T> struct UVTypeWrapper { using Type = T; constexpr UVTypeWrapper(Type val): value{val} { } constexpr operator Type() const noexcept { return value; } private: const Type value; }; } /** * @brief Utility class to handle flags. * * This class can be used to handle flags of a same enumeration type.<br/> * It is meant to be used as an argument for functions and member methods and * as part of events.<br/> * `Flags<E>` objects can be easily _or-ed_ and _and-ed_ with other instances of * the same type or with instances of the type `E` (that is, the actual flag * type), thus converted to the underlying type when needed. */ template<typename E> class Flags final { using InnerType = std::underlying_type_t<E>; constexpr InnerType toInnerType(E flag) const noexcept { return static_cast<InnerType>(flag); } public: using Type = InnerType; /** * @brief Constructs a Flags object from a value of the enum `E`. * @param flag An value of the enum `E`. */ constexpr Flags(E flag) noexcept: flags{toInnerType(flag)} { } /** * @brief Constructs a Flags object from an instance of the underlying type * of the enum `E`. * @param f An instance of the underlying type of the enum `E`. */ constexpr Flags(Type f): flags{f} { } /** * @brief Constructs an uninitialized Flags object. */ constexpr Flags(): flags{} { } constexpr Flags(const Flags &f) noexcept: flags{f.flags} { } constexpr Flags(Flags &&f) noexcept: flags{std::move(f.flags)} { } ~Flags() noexcept { static_assert(std::is_enum<E>::value, "!"); } constexpr Flags& operator=(const Flags &f) noexcept { flags = f.flags; return *this; } constexpr Flags& operator=(Flags &&f) noexcept { flags = std::move(f.flags); return *this; } /** * @brief Or operator. * @param f A valid instance of Flags. * @return This instance _or-ed_ with `f`. */ constexpr Flags operator|(const Flags &f) const noexcept { return Flags(flags | f.flags); } /** * @brief Or operator. * @param flag A value of the enum `E`. * @return This instance _or-ed_ with `flag`. */ constexpr Flags operator|(E flag) const noexcept { return Flags(flags | toInnerType(flag)); } /** * @brief And operator. * @param f A valid instance of Flags. * @return This instance _and-ed_ with `f`. */ constexpr Flags operator&(const Flags &f) const noexcept { return Flags(flags & f.flags); } /** * @brief And operator. * @param flag A value of the enum `E`. * @return This instance _and-ed_ with `flag`. */ constexpr Flags operator&(E flag) const noexcept { return Flags(flags & toInnerType(flag)); } /** * @brief Checks if this instance is initialized. * @return False if it's uninitialized, true otherwise. */ explicit constexpr operator bool() const noexcept { return !(flags == InnerType{}); } /** * @brief Casts the instance to the underlying type of `E`. * @return An integral representation of the contained flags. */ constexpr operator Type() const noexcept { return flags; } private: InnerType flags; }; /** * @brief Windows size representation. */ struct WinSize { int width; /*!< The _width_ of the given window. */ int height; /*!< The _height_ of the given window. */ }; using HandleType = details::UVHandleType; using FileHandle = details::UVTypeWrapper<uv_file>; using OSSocketHandle = details::UVTypeWrapper<uv_os_sock_t>; using OSFileDescriptor = details::UVTypeWrapper<uv_os_fd_t>; using TimeSpec = uv_timespec_t; using Stat = uv_stat_t; using Uid = uv_uid_t; using Gid = uv_gid_t; /** * @brief The IPv4 tag. * * To be used as template parameter to switch between IPv4 and IPv6. */ struct IPv4 { }; /** * @brief The IPv6 tag. * * To be used as template parameter to switch between IPv4 and IPv6. */ struct IPv6 { }; /** * @brief Address representation. */ struct Addr { std::string ip; /*!< Either an IPv4 or an IPv6. */ unsigned int port; /*!< A valid service identifier. */ }; /** * \brief Interface address. */ struct Interface { std::string name; /*!< The name of the interface (as an example _eth0_). */ std::string physical; /*!< The physical address. */ bool internal; /*!< True if it is an internal interface (as an example _loopback_), false otherwise. */ Addr address; /*!< The address of the given interface. */ Addr netmask; /*!< The netmask of the given interface. */ }; namespace details { template<typename> struct IpTraits; template<> struct IpTraits<IPv4> { using Type = sockaddr_in; using AddrFuncType = int(*)(const char *, int, Type *); using NameFuncType = int(*)(const Type *, char *, std::size_t); static constexpr AddrFuncType addrFunc = &uv_ip4_addr; static constexpr NameFuncType nameFunc = &uv_ip4_name; static constexpr auto sinPort(const Type *addr) { return addr->sin_port; } }; template<> struct IpTraits<IPv6> { using Type = sockaddr_in6; using AddrFuncType = int(*)(const char *, int, Type *); using NameFuncType = int(*)(const Type *, char *, std::size_t); static constexpr AddrFuncType addrFunc = &uv_ip6_addr; static constexpr NameFuncType nameFunc = &uv_ip6_name; static constexpr auto sinPort(const Type *addr) { return addr->sin6_port; } }; template<typename I, typename..., std::size_t N = 128> Addr address(const typename details::IpTraits<I>::Type *aptr) noexcept { Addr addr; char name[N]; int err = details::IpTraits<I>::nameFunc(aptr, name, N); if(0 == err) { addr.port = ntohs(details::IpTraits<I>::sinPort(aptr)); addr.ip = std::string{name}; } return addr; } template<typename I, typename F, typename H> Addr address(F &&f, const H *handle) noexcept { sockaddr_storage ssto; int len = sizeof(ssto); Addr addr{}; int err = std::forward<F>(f)(handle, reinterpret_cast<sockaddr *>(&ssto), &len); if(0 == err) { typename IpTraits<I>::Type *aptr = reinterpret_cast<typename IpTraits<I>::Type *>(&ssto); addr = address<I>(aptr); } return addr; } template<typename F, typename H, typename..., std::size_t N = 128> std::string path(F &&f, H *handle) noexcept { std::size_t size = N; char buf[size]; std::string str{}; auto err = std::forward<F>(f)(handle, buf, &size); if(UV_ENOBUFS == err) { std::unique_ptr<char[]> data{new char[size]}; err = std::forward<F>(f)(handle, data.get(), &size); if(0 == err) { str = data.get(); } } else { str.assign(buf, size); } return str; } } /** * @brief Miscellaneous utilities. * * Miscellaneous functions that don’t really belong to any other class. */ struct Utilities { /** * @brief Gets the type of the stream to be used with the given descriptor. * * Returns the type of stream that should be used with a given file * descriptor.<br/> * Usually this will be used during initialization to guess the type of the * stdio streams. * * @param file A valid descriptor. * @return One of the following types: * * * `HandleType::UNKNOWN` * * `HandleType::PIPE` * * `HandleType::TCP` * * `HandleType::TTY` * * `HandleType::UDP` * * `HandleType::FILE` */ static HandleType guessHandle(FileHandle file) { auto type = uv_guess_handle(file); switch(type) { case UV_ASYNC: return HandleType::ASYNC; case UV_CHECK: return HandleType::CHECK; case UV_FS_EVENT: return HandleType::FS_EVENT; case UV_FS_POLL: return HandleType::FS_POLL; case UV_HANDLE: return HandleType::HANDLE; case UV_IDLE: return HandleType::IDLE; case UV_NAMED_PIPE: return HandleType::PIPE; case UV_POLL: return HandleType::POLL; case UV_PREPARE: return HandleType::PREPARE; case UV_PROCESS: return HandleType::PROCESS; case UV_STREAM: return HandleType::STREAM; case UV_TCP: return HandleType::TCP; case UV_TIMER: return HandleType::TIMER; case UV_TTY: return HandleType::TTY; case UV_UDP: return HandleType::UDP; case UV_SIGNAL: return HandleType::SIGNAL; case UV_FILE: return HandleType::FILE; default: return HandleType::UNKNOWN; } } /** * @brief Gets a set of descriptors of all the available interfaces. * * This function can be used to query the underlying system and get a set of * descriptors of all the available interfaces, either internal or not. * * @return A set of descriptors of all the available interfaces. */ static std::vector<Interface> interfaces() noexcept { std::vector<Interface> interfaces; uv_interface_address_t *ifaces; int count; uv_interface_addresses(&ifaces, &count); std::for_each(ifaces, ifaces+count, [&interfaces](const auto &iface) { Interface interface; interface.name = iface.name; interface.physical = iface.phys_addr; interface.internal = iface.is_internal; if(iface.address.address4.sin_family == AF_INET) { interface.address = details::address<IPv4>(&iface.address.address4); interface.netmask = details::address<IPv4>(&iface.netmask.netmask4); } else if(iface.address.address4.sin_family == AF_INET6) { interface.address = details::address<IPv6>(&iface.address.address6); interface.netmask = details::address<IPv6>(&iface.netmask.netmask6); } interfaces.push_back(std::move(interface)); }); uv_free_interface_addresses(ifaces, count); return interfaces; } }; /** * TODO * * * uv_replace_allocator * * uv_uptime * * uv_getrusage * * uv_cpu_info * * uv_free_cpu_info * * uv_loadavg * * uv_exepath * * uv_cwd * * uv_chdir * * uv_os_homedir * * uv_os_tmpdir * * uv_os_get_passwd * * uv_os_free_passwd * * uv_get_total_memory * * uv_hrtime */ } <commit_msg>added Utilities::replaceAllocator<commit_after>#pragma once #include <type_traits> #include <algorithm> #include <stdexcept> #include <cstddef> #include <utility> #include <string> #include <vector> #include <uv.h> namespace uvw { namespace details { enum class UVHandleType: std::underlying_type_t<uv_handle_type> { UNKNOWN = UV_UNKNOWN_HANDLE, ASYNC = UV_ASYNC, CHECK = UV_CHECK, FS_EVENT = UV_FS_EVENT, FS_POLL = UV_FS_POLL, HANDLE = UV_HANDLE, IDLE = UV_IDLE, PIPE = UV_NAMED_PIPE, POLL = UV_POLL, PREPARE = UV_PREPARE, PROCESS = UV_PROCESS, STREAM = UV_STREAM, TCP = UV_TCP, TIMER = UV_TIMER, TTY = UV_TTY, UDP = UV_UDP, SIGNAL = UV_SIGNAL, FILE = UV_FILE }; template<typename T> struct UVTypeWrapper { using Type = T; constexpr UVTypeWrapper(Type val): value{val} { } constexpr operator Type() const noexcept { return value; } private: const Type value; }; } /** * @brief Utility class to handle flags. * * This class can be used to handle flags of a same enumeration type.<br/> * It is meant to be used as an argument for functions and member methods and * as part of events.<br/> * `Flags<E>` objects can be easily _or-ed_ and _and-ed_ with other instances of * the same type or with instances of the type `E` (that is, the actual flag * type), thus converted to the underlying type when needed. */ template<typename E> class Flags final { using InnerType = std::underlying_type_t<E>; constexpr InnerType toInnerType(E flag) const noexcept { return static_cast<InnerType>(flag); } public: using Type = InnerType; /** * @brief Constructs a Flags object from a value of the enum `E`. * @param flag An value of the enum `E`. */ constexpr Flags(E flag) noexcept: flags{toInnerType(flag)} { } /** * @brief Constructs a Flags object from an instance of the underlying type * of the enum `E`. * @param f An instance of the underlying type of the enum `E`. */ constexpr Flags(Type f): flags{f} { } /** * @brief Constructs an uninitialized Flags object. */ constexpr Flags(): flags{} { } constexpr Flags(const Flags &f) noexcept: flags{f.flags} { } constexpr Flags(Flags &&f) noexcept: flags{std::move(f.flags)} { } ~Flags() noexcept { static_assert(std::is_enum<E>::value, "!"); } constexpr Flags& operator=(const Flags &f) noexcept { flags = f.flags; return *this; } constexpr Flags& operator=(Flags &&f) noexcept { flags = std::move(f.flags); return *this; } /** * @brief Or operator. * @param f A valid instance of Flags. * @return This instance _or-ed_ with `f`. */ constexpr Flags operator|(const Flags &f) const noexcept { return Flags(flags | f.flags); } /** * @brief Or operator. * @param flag A value of the enum `E`. * @return This instance _or-ed_ with `flag`. */ constexpr Flags operator|(E flag) const noexcept { return Flags(flags | toInnerType(flag)); } /** * @brief And operator. * @param f A valid instance of Flags. * @return This instance _and-ed_ with `f`. */ constexpr Flags operator&(const Flags &f) const noexcept { return Flags(flags & f.flags); } /** * @brief And operator. * @param flag A value of the enum `E`. * @return This instance _and-ed_ with `flag`. */ constexpr Flags operator&(E flag) const noexcept { return Flags(flags & toInnerType(flag)); } /** * @brief Checks if this instance is initialized. * @return False if it's uninitialized, true otherwise. */ explicit constexpr operator bool() const noexcept { return !(flags == InnerType{}); } /** * @brief Casts the instance to the underlying type of `E`. * @return An integral representation of the contained flags. */ constexpr operator Type() const noexcept { return flags; } private: InnerType flags; }; /** * @brief Windows size representation. */ struct WinSize { int width; /*!< The _width_ of the given window. */ int height; /*!< The _height_ of the given window. */ }; using HandleType = details::UVHandleType; using FileHandle = details::UVTypeWrapper<uv_file>; using OSSocketHandle = details::UVTypeWrapper<uv_os_sock_t>; using OSFileDescriptor = details::UVTypeWrapper<uv_os_fd_t>; using TimeSpec = uv_timespec_t; using Stat = uv_stat_t; using Uid = uv_uid_t; using Gid = uv_gid_t; /** * @brief The IPv4 tag. * * To be used as template parameter to switch between IPv4 and IPv6. */ struct IPv4 { }; /** * @brief The IPv6 tag. * * To be used as template parameter to switch between IPv4 and IPv6. */ struct IPv6 { }; /** * @brief Address representation. */ struct Addr { std::string ip; /*!< Either an IPv4 or an IPv6. */ unsigned int port; /*!< A valid service identifier. */ }; /** * \brief Interface address. */ struct Interface { std::string name; /*!< The name of the interface (as an example _eth0_). */ std::string physical; /*!< The physical address. */ bool internal; /*!< True if it is an internal interface (as an example _loopback_), false otherwise. */ Addr address; /*!< The address of the given interface. */ Addr netmask; /*!< The netmask of the given interface. */ }; namespace details { template<typename> struct IpTraits; template<> struct IpTraits<IPv4> { using Type = sockaddr_in; using AddrFuncType = int(*)(const char *, int, Type *); using NameFuncType = int(*)(const Type *, char *, std::size_t); static constexpr AddrFuncType addrFunc = &uv_ip4_addr; static constexpr NameFuncType nameFunc = &uv_ip4_name; static constexpr auto sinPort(const Type *addr) { return addr->sin_port; } }; template<> struct IpTraits<IPv6> { using Type = sockaddr_in6; using AddrFuncType = int(*)(const char *, int, Type *); using NameFuncType = int(*)(const Type *, char *, std::size_t); static constexpr AddrFuncType addrFunc = &uv_ip6_addr; static constexpr NameFuncType nameFunc = &uv_ip6_name; static constexpr auto sinPort(const Type *addr) { return addr->sin6_port; } }; template<typename I, typename..., std::size_t N = 128> Addr address(const typename details::IpTraits<I>::Type *aptr) noexcept { Addr addr; char name[N]; int err = details::IpTraits<I>::nameFunc(aptr, name, N); if(0 == err) { addr.port = ntohs(details::IpTraits<I>::sinPort(aptr)); addr.ip = std::string{name}; } return addr; } template<typename I, typename F, typename H> Addr address(F &&f, const H *handle) noexcept { sockaddr_storage ssto; int len = sizeof(ssto); Addr addr{}; int err = std::forward<F>(f)(handle, reinterpret_cast<sockaddr *>(&ssto), &len); if(0 == err) { typename IpTraits<I>::Type *aptr = reinterpret_cast<typename IpTraits<I>::Type *>(&ssto); addr = address<I>(aptr); } return addr; } template<typename F, typename H, typename..., std::size_t N = 128> std::string path(F &&f, H *handle) noexcept { std::size_t size = N; char buf[size]; std::string str{}; auto err = std::forward<F>(f)(handle, buf, &size); if(UV_ENOBUFS == err) { std::unique_ptr<char[]> data{new char[size]}; err = std::forward<F>(f)(handle, data.get(), &size); if(0 == err) { str = data.get(); } } else { str.assign(buf, size); } return str; } } /** * @brief Miscellaneous utilities. * * Miscellaneous functions that don’t really belong to any other class. */ struct Utilities { using MallocFuncType = void*(*)(size_t); using ReallocFuncType = void*(*)(void*, size_t); using CallocFuncType = void*(*)(size_t, size_t); using FreeFuncType = void(*)(void*); /** * @brief Gets the type of the stream to be used with the given descriptor. * * Returns the type of stream that should be used with a given file * descriptor.<br/> * Usually this will be used during initialization to guess the type of the * stdio streams. * * @param file A valid descriptor. * @return One of the following types: * * * `HandleType::UNKNOWN` * * `HandleType::PIPE` * * `HandleType::TCP` * * `HandleType::TTY` * * `HandleType::UDP` * * `HandleType::FILE` */ static HandleType guessHandle(FileHandle file) { auto type = uv_guess_handle(file); switch(type) { case UV_ASYNC: return HandleType::ASYNC; case UV_CHECK: return HandleType::CHECK; case UV_FS_EVENT: return HandleType::FS_EVENT; case UV_FS_POLL: return HandleType::FS_POLL; case UV_HANDLE: return HandleType::HANDLE; case UV_IDLE: return HandleType::IDLE; case UV_NAMED_PIPE: return HandleType::PIPE; case UV_POLL: return HandleType::POLL; case UV_PREPARE: return HandleType::PREPARE; case UV_PROCESS: return HandleType::PROCESS; case UV_STREAM: return HandleType::STREAM; case UV_TCP: return HandleType::TCP; case UV_TIMER: return HandleType::TIMER; case UV_TTY: return HandleType::TTY; case UV_UDP: return HandleType::UDP; case UV_SIGNAL: return HandleType::SIGNAL; case UV_FILE: return HandleType::FILE; default: return HandleType::UNKNOWN; } } /** * @brief Gets a set of descriptors of all the available interfaces. * * This function can be used to query the underlying system and get a set of * descriptors of all the available interfaces, either internal or not. * * @return A set of descriptors of all the available interfaces. */ static std::vector<Interface> interfaces() noexcept { std::vector<Interface> interfaces; uv_interface_address_t *ifaces; int count; uv_interface_addresses(&ifaces, &count); std::for_each(ifaces, ifaces+count, [&interfaces](const auto &iface) { Interface interface; interface.name = iface.name; interface.physical = iface.phys_addr; interface.internal = iface.is_internal; if(iface.address.address4.sin_family == AF_INET) { interface.address = details::address<IPv4>(&iface.address.address4); interface.netmask = details::address<IPv4>(&iface.netmask.netmask4); } else if(iface.address.address4.sin_family == AF_INET6) { interface.address = details::address<IPv6>(&iface.address.address6); interface.netmask = details::address<IPv6>(&iface.netmask.netmask6); } interfaces.push_back(std::move(interface)); }); uv_free_interface_addresses(ifaces, count); return interfaces; } /** * @brief Override the use of some standard library’s functions. * * Override the use of the standard library’s memory allocation * functions.<br/> * This method must be invoked before any other `uvw` function is called or * after all resources have been freed and thus the underlying library * doesn’t reference any allocated memory chunk. * * If any of the function pointers is _null_, the invokation will fail. * * **Note**: there is no protection against changing the allocator multiple * times. If the user changes it they are responsible for making sure the * allocator is changed while no memory was allocated with the previous * allocator, or that they are compatible. * * @param mallocFunc Replacement function for _malloc_. * @param reallocFunc Replacement function for _realloc_. * @param callocFunc Replacement function for _calloc_. * @param freeFunc Replacement function for _free_. * @return True in case of success, false otherwise. */ static bool replaceAllocator(MallocFuncType mallocFunc, ReallocFuncType reallocFunc, CallocFuncType callocFunc, FreeFuncType freeFunc) { return (0 == uv_replace_allocator(mallocFunc, reallocFunc, callocFunc, freeFunc)); } }; /** * TODO * * * uv_uptime * * uv_getrusage * * uv_cpu_info * * uv_free_cpu_info * * uv_loadavg * * uv_exepath * * uv_cwd * * uv_chdir * * uv_os_homedir * * uv_os_tmpdir * * uv_os_get_passwd * * uv_os_free_passwd * * uv_get_total_memory * * uv_hrtime */ } <|endoftext|>
<commit_before>#include "client/keyboard/keyid.h" #include "client/keyboard/keytable.h" #include "client/ui/event.hpp" #include "client/ui/menu.hpp" #include "client/ui/window.hpp" #include "sys/path.hpp" #include "sys/rand.hpp" #include <windows.h> #include <gl\gl.h> #include <gl\glu.h> #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glu32.lib") class WinWindow : public UI::Window { public: virtual void close(); }; void WinWindow::close() { PostQuitMessage(0); } static HDC hDC; static HGLRC hRC; static HWND hWnd; static HINSTANCE hInstance; static bool inactive; static WinWindow *gWindow; static LRESULT CALLBACK wndProc(HWND, UINT, WPARAM, LPARAM); static void errorBox(const char *str) { MessageBox(NULL, str, "ERROR", MB_OK | MB_ICONEXCLAMATION); } static void serrorBox(const char *str) { MessageBox(NULL, str, "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION); } static void handleResize(int width, int height) { if (!height) height = 1; if (!width) width = 1; glViewport(0, 0, width, height); gWindow->setSize(width, height); } static void killGLWindow() { if (hRC) { if (!wglMakeCurrent(NULL, NULL)) serrorBox("Release of DC and RC failed."); if (!wglDeleteContext(hRC)) serrorBox("Release rendering context failed."); } hRC = NULL; if (hDC && !ReleaseDC(hWnd, hDC)) serrorBox("Release device context failed."); hDC = NULL; if (hWnd && !DestroyWindow(hWnd)) serrorBox("Could not release window."); hWnd = NULL; if (!UnregisterClass("OpenGL", hInstance)) serrorBox("Could not unregister class"); hInstance = NULL; } BOOL createWindow(const char *title, int width, int height) { GLuint pixelFormat; WNDCLASS wc; DWORD dwExStyle; DWORD dwStyle; RECT windowRect; windowRect.left = 0; windowRect.right = width; windowRect.top = 0; windowRect.bottom = height; hInstance = GetModuleHandle(NULL); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (WNDPROC) wndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = "OpenGL"; if (!RegisterClass(&wc)) { errorBox("Failed to register window class."); return FALSE; } dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPEDWINDOW; dwStyle |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN; AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle); hWnd = CreateWindowEx(dwExStyle, "OpenGL", title, dwStyle, 0, 0, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, NULL, NULL, hInstance, NULL); if (!hWnd) { killGLWindow(); errorBox("Window creation error."); return FALSE; } static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, // color bits 0, // alpha 0, // shift 0, 0, 0, 0, 0, // accumulation 16, // depth buffer 0, // stencil 0, // auxiliary PFD_MAIN_PLANE, // drawing layer 0, //reserved 0, 0, 0 // layer masks }; hDC = GetDC(hWnd); if (!hDC) { killGLWindow(); errorBox("Can't create OpenGL device context."); return FALSE; } pixelFormat = ChoosePixelFormat(hDC, &pfd); if (!pixelFormat) { killGLWindow(); errorBox("Can't find a suitable pixel format."); return FALSE; } if (!SetPixelFormat(hDC, pixelFormat, &pfd)) { killGLWindow(); errorBox("Can't set pixel format."); return FALSE; } hRC = wglCreateContext(hDC); if (!hRC) { killGLWindow(); errorBox("Can't create OpenGL rendering context."); return FALSE; } if (!wglMakeCurrent(hDC, hRC)) { killGLWindow(); errorBox("Can't activate OpenGL rendering context."); return FALSE; } ShowWindow(hWnd, SW_SHOW); SetForegroundWindow(hWnd); SetFocus(hWnd); handleResize(width, height); return TRUE; } static void handleKey(int code, UI::EventType t) { if (code < 0 || code > 255) return; int hcode = WIN_NATIVE_TO_HID[code]; if (hcode == 255) return; char buf[64]; _snprintf(buf, sizeof(buf), "key: %s\n", keyid_name_from_code(hcode)); buf[63] = '\0'; OutputDebugString(buf); UI::KeyEvent e(t, hcode); gWindow->handleEvent(e); } static LRESULT CALLBACK wndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_ACTIVATE: inactive = HIWORD(wParam) != 0; return 0; case WM_SYSCOMMAND: switch (wParam) { case SC_SCREENSAVE: case SC_MONITORPOWER: return 0; } break; case WM_CLOSE: PostQuitMessage(0); return 0; case WM_KEYDOWN: handleKey(wParam, UI::KeyDown); return 0; case WM_KEYUP: handleKey(wParam, UI::KeyUp); return 0; case WM_SIZE: handleResize(LOWORD(lParam), HIWORD(lParam)); return 0; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow) { MSG msg; WinWindow w; gWindow = &w; Path::init(); Rand::global.seed(); w.setScreen(new UI::Menu); if (!createWindow("Game", 768, 480)) return 0; while (1) { while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) goto done; TranslateMessage(&msg); DispatchMessage(&msg); } if (!inactive) { w.draw(); SwapBuffers(hDC); } } done: killGLWindow(); return 0; } <commit_msg>Add mouse event handling to Windows port<commit_after>#include "client/keyboard/keyid.h" #include "client/keyboard/keytable.h" #include "client/ui/event.hpp" #include "client/ui/menu.hpp" #include "client/ui/window.hpp" #include "sys/path.hpp" #include "sys/rand.hpp" #include <windows.h> #include <gl\gl.h> #include <gl\glu.h> #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glu32.lib") class WinWindow : public UI::Window { public: virtual void close(); }; void WinWindow::close() { PostQuitMessage(0); } static HDC hDC; static HGLRC hRC; static HWND hWnd; static HINSTANCE hInstance; static bool inactive; static WinWindow *gWindow; static LRESULT CALLBACK wndProc(HWND, UINT, WPARAM, LPARAM); static void errorBox(const char *str) { MessageBox(NULL, str, "ERROR", MB_OK | MB_ICONEXCLAMATION); } static void serrorBox(const char *str) { MessageBox(NULL, str, "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION); } static void handleResize(int width, int height) { if (!height) height = 1; if (!width) width = 1; glViewport(0, 0, width, height); gWindow->setSize(width, height); } static void killGLWindow() { if (hRC) { if (!wglMakeCurrent(NULL, NULL)) serrorBox("Release of DC and RC failed."); if (!wglDeleteContext(hRC)) serrorBox("Release rendering context failed."); } hRC = NULL; if (hDC && !ReleaseDC(hWnd, hDC)) serrorBox("Release device context failed."); hDC = NULL; if (hWnd && !DestroyWindow(hWnd)) serrorBox("Could not release window."); hWnd = NULL; if (!UnregisterClass("OpenGL", hInstance)) serrorBox("Could not unregister class"); hInstance = NULL; } BOOL createWindow(const char *title, int width, int height) { GLuint pixelFormat; WNDCLASS wc; DWORD dwExStyle; DWORD dwStyle; RECT windowRect; windowRect.left = 0; windowRect.right = width; windowRect.top = 0; windowRect.bottom = height; hInstance = GetModuleHandle(NULL); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (WNDPROC) wndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = "OpenGL"; if (!RegisterClass(&wc)) { errorBox("Failed to register window class."); return FALSE; } dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPEDWINDOW; dwStyle |= WS_CLIPSIBLINGS | WS_CLIPCHILDREN; AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle); hWnd = CreateWindowEx(dwExStyle, "OpenGL", title, dwStyle, 0, 0, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, NULL, NULL, hInstance, NULL); if (!hWnd) { killGLWindow(); errorBox("Window creation error."); return FALSE; } static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, // color bits 0, // alpha 0, // shift 0, 0, 0, 0, 0, // accumulation 16, // depth buffer 0, // stencil 0, // auxiliary PFD_MAIN_PLANE, // drawing layer 0, //reserved 0, 0, 0 // layer masks }; hDC = GetDC(hWnd); if (!hDC) { killGLWindow(); errorBox("Can't create OpenGL device context."); return FALSE; } pixelFormat = ChoosePixelFormat(hDC, &pfd); if (!pixelFormat) { killGLWindow(); errorBox("Can't find a suitable pixel format."); return FALSE; } if (!SetPixelFormat(hDC, pixelFormat, &pfd)) { killGLWindow(); errorBox("Can't set pixel format."); return FALSE; } hRC = wglCreateContext(hDC); if (!hRC) { killGLWindow(); errorBox("Can't create OpenGL rendering context."); return FALSE; } if (!wglMakeCurrent(hDC, hRC)) { killGLWindow(); errorBox("Can't activate OpenGL rendering context."); return FALSE; } ShowWindow(hWnd, SW_SHOW); SetForegroundWindow(hWnd); SetFocus(hWnd); handleResize(width, height); return TRUE; } static void handleKey(int code, UI::EventType t) { if (code < 0 || code > 255) return; int hcode = WIN_NATIVE_TO_HID[code]; if (hcode == 255) return; char buf[64]; _snprintf(buf, sizeof(buf), "key: %s\n", keyid_name_from_code(hcode)); buf[63] = '\0'; OutputDebugString(buf); UI::KeyEvent e(t, hcode); gWindow->handleEvent(e); } static void handleMouse(int param, UI::EventType t, int button) { int x = LOWORD(param), y = HIWORD(param); UI::MouseEvent e(t, button, x, gWindow->height() - 1 - y); gWindow->handleEvent(e); } static LRESULT CALLBACK wndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_ACTIVATE: inactive = HIWORD(wParam) != 0; return 0; case WM_SYSCOMMAND: switch (wParam) { case SC_SCREENSAVE: case SC_MONITORPOWER: return 0; } break; case WM_CLOSE: PostQuitMessage(0); return 0; case WM_KEYDOWN: handleKey(wParam, UI::KeyDown); return 0; case WM_KEYUP: handleKey(wParam, UI::KeyUp); return 0; case WM_LBUTTONDOWN: handleMouse(lParam, UI::MouseDown, UI::ButtonLeft); return 0; case WM_RBUTTONDOWN: handleMouse(lParam, UI::MouseDown, UI::ButtonRight); return 0; case WM_MBUTTONDOWN: handleMouse(lParam, UI::MouseDown, UI::ButtonMiddle); return 0; case WM_LBUTTONUP: handleMouse(lParam, UI::MouseUp, UI::ButtonLeft); return 0; case WM_RBUTTONUP: handleMouse(lParam, UI::MouseUp, UI::ButtonRight); return 0; case WM_MBUTTONUP: handleMouse(lParam, UI::MouseUp, UI::ButtonMiddle); return 0; case WM_MOUSEMOVE: handleMouse(lParam, UI::MouseMove, -1); return 0; case WM_SIZE: handleResize(LOWORD(lParam), HIWORD(lParam)); return 0; } return DefWindowProc(hWnd, uMsg, wParam, lParam); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iCmdShow) { MSG msg; WinWindow w; gWindow = &w; Path::init(); Rand::global.seed(); w.setScreen(new UI::Menu); if (!createWindow("Game", 768, 480)) return 0; while (1) { while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) goto done; TranslateMessage(&msg); DispatchMessage(&msg); } if (!inactive) { w.draw(); SwapBuffers(hDC); } } done: killGLWindow(); return 0; } <|endoftext|>
<commit_before>/* * mkSVG.cpp * MonkSVG * * Created by Micah Pearlman on 8/2/10. * Copyright 2010 Zero Vision. All rights reserved. * */ #include "mkSVG.h" #include "tinyxml.h" #include <map> #include <iterator> #include <boost/foreach.hpp> #include <boost/tokenizer.hpp> using namespace boost; namespace MonkSVG { bool SVG::initialize( ISVGHandler* handler ) { _handler = handler; return true; } bool SVG::read( const char* data ) { TiXmlDocument doc; doc.Parse( data ); TiXmlElement* root = doc.FirstChild( "svg" )->ToElement(); recursive_parse( &doc, root ); return true; } bool SVG::read( string& data ) { return read( data.c_str() ); } void SVG::recursive_parse( TiXmlDocument* doc, TiXmlElement* element ) { if ( element ) { TiXmlElement* child = element->FirstChildElement(); recursive_parse( doc, child ); } if ( element ) { for ( TiXmlElement* sibbling = element; sibbling != 0; sibbling = sibbling->NextSiblingElement() ) { string type = sibbling->Value(); if ( type == "g" ) { handle_path( sibbling->FirstChildElement() ); } if ( type == "path" ) { handle_path( sibbling ); } } } } float SVG::d_string_to_float( char *c, char** str ) { while ( isspace(*c) ) { c++; (*str)++; } while ( *c == ',' ) { c++; (*str)++; } return strtof( c, str ); } uint32_t SVG::string_hex_color_to_uint( string& hexstring ) { uint32_t color = strtol( hexstring.c_str() + 1, 0, 16 ); if ( hexstring.length() == 7 ) { // fix up to rgba if the color is only rgb color = color << 8; color |= 0x000000ff; } return color; } void SVG::handle_path( TiXmlElement* pathElement ) { _handler->onPathBegin(); string d = pathElement->Attribute( "d" ); parse_path_d( d ); _handler->onPathEnd(); string fill; if ( pathElement->QueryStringAttribute( "fill", &fill ) == TIXML_SUCCESS ) { _handler->onPathFillColor( string_hex_color_to_uint( fill ) ); } string stroke; if ( pathElement->QueryStringAttribute( "stroke", &stroke) == TIXML_SUCCESS ) { _handler->onPathStrokeColor( string_hex_color_to_uint( stroke ) ); } string stroke_width; if ( pathElement->QueryStringAttribute( "stroke-width", &stroke_width) == TIXML_SUCCESS ) { float width = atof( stroke_width.c_str() ); _handler->onPathStrokeWidth( width ); } string style; if ( pathElement->QueryStringAttribute( "style", &style) == TIXML_SUCCESS ) { parse_path_style( style ); } } void SVG::nextState( char** c, char* state ) { while ( isspace(**c) ) { (*c)++; } if ( isalpha( **c ) ) { *state = **c; (*c)++; if ( islower(*state) ) { // if lower case then relative coords (see SVG spec) _handler->setRelative( true ); } else { _handler->setRelative( false ); } } } void SVG::parse_path_d( string& d ) { char* c = const_cast<char*>( d.c_str() ); char state = *c; nextState( &c, &state ); while ( *c && state != 'z' ) { switch ( state ) { case 'm': case 'M': { //c++; float x = d_string_to_float( c, &c ); float y = d_string_to_float( c, &c ); _handler->onPathMoveTo( x, y ); nextState(&c, &state); } break; case 'l': case 'L': { //c++; float x = d_string_to_float( c, &c ); float y = d_string_to_float( c, &c ); _handler->onPathLineTo( x, y ); nextState(&c, &state); } break; case 'c': case 'C': { //c++; float x1 = d_string_to_float( c, &c ); float y1 = d_string_to_float( c, &c ); float x2 = d_string_to_float( c, &c ); float y2 = d_string_to_float( c, &c ); float x3 = d_string_to_float( c, &c ); float y3 = d_string_to_float( c, &c ); _handler->onPathCubic(x1, y1, x2, y2, x3, y3); nextState(&c, &state); } break; case 'z': case 'Z': { //c++; _handler->onPathEnd(); nextState(&c, &state); } break; default: c++; break; } } } // semicolon-separated property declarations of the form "name : value" within the ‘style’ attribute void SVG::parse_path_style( string& ps ) { map< string, string > style_key_values; char_separator<char> values_seperator(";"); char_separator<char> key_value_seperator(":"); tokenizer<char_separator<char> > values_tokens( ps, values_seperator ); BOOST_FOREACH( string values, values_tokens ) { tokenizer<char_separator<char> > key_value_tokens( values, key_value_seperator ); tokenizer<char_separator<char> >::iterator k = key_value_tokens.begin(); tokenizer<char_separator<char> >::iterator v = k; v++; //cout << *k << ":" << *v << endl; style_key_values[*k] = *v; } map<string, string>::iterator kv = style_key_values.find( string("fill") ); if ( kv != style_key_values.end() ) { _handler->onPathFillColor( string_hex_color_to_uint( kv->second ) ); } kv = style_key_values.find( "stroke" ); if ( kv != style_key_values.end() ) { _handler->onPathStrokeColor( string_hex_color_to_uint( kv->second ) ); } kv = style_key_values.find( "stroke-width" ); if ( kv != style_key_values.end() ) { float width = atof( kv->second.c_str() ); _handler->onPathStrokeWidth( width ); } } };<commit_msg>handles multiple paths in a group<commit_after>/* * mkSVG.cpp * MonkSVG * * Created by Micah Pearlman on 8/2/10. * Copyright 2010 Zero Vision. All rights reserved. * */ #include "mkSVG.h" #include "tinyxml.h" #include <map> #include <iterator> #include <boost/foreach.hpp> #include <boost/tokenizer.hpp> using namespace boost; namespace MonkSVG { bool SVG::initialize( ISVGHandler* handler ) { _handler = handler; return true; } bool SVG::read( const char* data ) { TiXmlDocument doc; doc.Parse( data ); TiXmlElement* root = doc.FirstChild( "svg" )->ToElement(); recursive_parse( &doc, root ); return true; } bool SVG::read( string& data ) { return read( data.c_str() ); } void SVG::recursive_parse( TiXmlDocument* doc, TiXmlElement* element ) { if ( element ) { TiXmlElement* child = element->FirstChildElement(); recursive_parse( doc, child ); } if ( element ) { for ( TiXmlElement* sibbling = element; sibbling != 0; sibbling = sibbling->NextSiblingElement() ) { string type = sibbling->Value(); if ( type == "g" ) { // go through each child path for ( TiXmlElement* child = sibbling->FirstChildElement(); child != 0; child = child->NextSiblingElement() ) { handle_path( child ); } } if ( type == "path" ) { handle_path( sibbling ); } } } } float SVG::d_string_to_float( char *c, char** str ) { while ( isspace(*c) ) { c++; (*str)++; } while ( *c == ',' ) { c++; (*str)++; } return strtof( c, str ); } uint32_t SVG::string_hex_color_to_uint( string& hexstring ) { uint32_t color = strtol( hexstring.c_str() + 1, 0, 16 ); if ( hexstring.length() == 7 ) { // fix up to rgba if the color is only rgb color = color << 8; color |= 0x000000ff; } return color; } void SVG::handle_path( TiXmlElement* pathElement ) { _handler->onPathBegin(); string d = pathElement->Attribute( "d" ); parse_path_d( d ); _handler->onPathEnd(); string fill; if ( pathElement->QueryStringAttribute( "fill", &fill ) == TIXML_SUCCESS ) { _handler->onPathFillColor( string_hex_color_to_uint( fill ) ); } string stroke; if ( pathElement->QueryStringAttribute( "stroke", &stroke) == TIXML_SUCCESS ) { _handler->onPathStrokeColor( string_hex_color_to_uint( stroke ) ); } string stroke_width; if ( pathElement->QueryStringAttribute( "stroke-width", &stroke_width) == TIXML_SUCCESS ) { float width = atof( stroke_width.c_str() ); _handler->onPathStrokeWidth( width ); } string style; if ( pathElement->QueryStringAttribute( "style", &style) == TIXML_SUCCESS ) { parse_path_style( style ); } } void SVG::nextState( char** c, char* state ) { while ( isspace(**c) ) { (*c)++; } if ( isalpha( **c ) ) { *state = **c; (*c)++; if ( islower(*state) ) { // if lower case then relative coords (see SVG spec) _handler->setRelative( true ); } else { _handler->setRelative( false ); } } } void SVG::parse_path_d( string& d ) { char* c = const_cast<char*>( d.c_str() ); char state = *c; nextState( &c, &state ); while ( *c && state != 'z' ) { switch ( state ) { case 'm': case 'M': { //c++; float x = d_string_to_float( c, &c ); float y = d_string_to_float( c, &c ); _handler->onPathMoveTo( x, y ); nextState(&c, &state); } break; case 'l': case 'L': { //c++; float x = d_string_to_float( c, &c ); float y = d_string_to_float( c, &c ); _handler->onPathLineTo( x, y ); nextState(&c, &state); } break; case 'c': case 'C': { //c++; float x1 = d_string_to_float( c, &c ); float y1 = d_string_to_float( c, &c ); float x2 = d_string_to_float( c, &c ); float y2 = d_string_to_float( c, &c ); float x3 = d_string_to_float( c, &c ); float y3 = d_string_to_float( c, &c ); _handler->onPathCubic(x1, y1, x2, y2, x3, y3); nextState(&c, &state); } break; case 'z': case 'Z': { //c++; _handler->onPathEnd(); nextState(&c, &state); } break; default: c++; break; } } } // semicolon-separated property declarations of the form "name : value" within the ‘style’ attribute void SVG::parse_path_style( string& ps ) { map< string, string > style_key_values; char_separator<char> values_seperator(";"); char_separator<char> key_value_seperator(":"); tokenizer<char_separator<char> > values_tokens( ps, values_seperator ); BOOST_FOREACH( string values, values_tokens ) { tokenizer<char_separator<char> > key_value_tokens( values, key_value_seperator ); tokenizer<char_separator<char> >::iterator k = key_value_tokens.begin(); tokenizer<char_separator<char> >::iterator v = k; v++; //cout << *k << ":" << *v << endl; style_key_values[*k] = *v; } map<string, string>::iterator kv = style_key_values.find( string("fill") ); if ( kv != style_key_values.end() ) { _handler->onPathFillColor( string_hex_color_to_uint( kv->second ) ); } kv = style_key_values.find( "stroke" ); if ( kv != style_key_values.end() ) { _handler->onPathStrokeColor( string_hex_color_to_uint( kv->second ) ); } kv = style_key_values.find( "stroke-width" ); if ( kv != style_key_values.end() ) { float width = atof( kv->second.c_str() ); _handler->onPathStrokeWidth( width ); } } };<|endoftext|>
<commit_before>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010 Belledonne Communications SARL. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "agent.hh" #include "entryfilter.hh" #include <algorithm> using namespace::std; Module *ModuleInfoBase::create(Agent *ag){ Module *mod=_create(ag); mod->setInfo(this); return mod; } ModuleFactory * ModuleFactory::sInstance=NULL; ModuleFactory *ModuleFactory::get(){ if (sInstance==NULL){ sInstance=new ModuleFactory(); } return sInstance; } struct hasName{ hasName(const std::string &ref) : match(ref){ } bool operator()(ModuleInfoBase *info){ return info->getModuleName()==match; } const std::string &match; }; Module *ModuleFactory::createModuleInstance(Agent *ag, const std::string &modname){ list<ModuleInfoBase*>::iterator it; it=find_if(mModules.begin(), mModules.end(), hasName(modname)); if (it!=mModules.end()){ Module *m; ModuleInfoBase *i=*it; m=i->create(ag); LOGI("Creating module instance for [%s]",m->getModuleName().c_str()); return m; } LOGE("Could not find any registered module with name %s",modname.c_str()); return NULL; } void ModuleFactory::registerModule(ModuleInfoBase *m){ LOGI("Registering module %s",m->getModuleName().c_str()); mModules.push_back(m); } Module::Module(Agent *ag ) : mAgent(ag){ mFilter=new ConfigEntryFilter(); } Module::~Module(){ } void Module::setInfo(ModuleInfoBase *i){ mInfo=i; } Agent *Module::getAgent()const{ return mAgent; } nta_agent_t *Module::getSofiaAgent()const{ return mAgent->getSofiaAgent(); } void Module::declare(ConfigStruct *root){ mModuleConfig=new ConfigStruct("module::"+getModuleName(),mInfo->getModuleHelp()); root->addChild(mModuleConfig); mFilter->declareConfig(mModuleConfig); onDeclare(mModuleConfig); } void Module::load(Agent *agent){ mFilter->loadConfig(mModuleConfig); if (mFilter->isEnabled()) onLoad(agent,mModuleConfig); } void Module::processRequest(SipEvent *ev){ if (mFilter->canEnter(ev->mSip)){ LOGD("Invoking onRequest() on module %s",getModuleName().c_str()); onRequest(ev); } } void Module::processResponse(SipEvent *ev){ if (mFilter->canEnter(ev->mSip)){ LOGD("Invoking onResponse() on module %s",getModuleName().c_str()); onResponse(ev); } } void Module::idle(){ onIdle(); } const std::string &Module::getModuleName(){ return mInfo->getModuleName(); } bool ModuleToolbox::sipPortEquals(const char *p1, const char *p2){ int n1,n2; n1=n2=5060; if (p1 && p1[0]!='\0') n1=atoi(p1); if (p2 && p2[0]!='\0') n2=atoi(p2); return n1==n2; } int ModuleToolbox::sipPortToInt(const char *port){ if (port==NULL || port[0]=='\0') return 5060; else return atoi(port); } void ModuleToolbox::addRecordRoute(su_home_t *home, Agent *ag, sip_t *sip){ sip_via_t *via=sip->sip_via; sip_record_route_t *rr; if (strcasecmp(sip_via_transport(via),"TCP")) rr=sip_record_route_format(home,"<sip:%s:%i;lr;transport=TCP>",ag->getLocAddr().c_str(),ag->getPort()); else rr=sip_record_route_format(home,"<sip:%s:%i;lr>",ag->getLocAddr().c_str(),ag->getPort()); if (sip->sip_record_route==NULL){ sip->sip_record_route=rr; }else{ sip_record_route_t *it,*last_it=NULL; for(it=sip->sip_record_route;it!=NULL;it=it->r_next){ /*make sure we are not already in*/ if (strcmp(it->r_url->url_host,ag->getLocAddr().c_str())==0 && sipPortToInt(it->r_url->url_port)==ag->getPort()) return; last_it=it; } last_it->r_next=rr; } } bool ModuleToolbox::fromMatch(const sip_from_t *from1, const sip_from_t *from2){ if (url_cmp(from1->a_url,from2->a_url)==0){ if (from1->a_tag && from2->a_tag && strcmp(from1->a_tag,from2->a_tag)==0) return true; if (from1->a_tag==NULL && from2->a_tag==NULL) return true; } return false; } bool ModuleToolbox::matchesOneOf(const char *item, const std::list<std::string> &set){ list<string>::const_iterator it; for(it=set.begin();it!=set.end();++it){ const char *tmp=(*it).c_str(); if (tmp[0]=='*'){ /*the wildcard matches everything*/ return true; }else{ if (strcmp(item,tmp)==0) return true; } } return false; } <commit_msg>fix incorrect record route<commit_after>/* Flexisip, a flexible SIP proxy server with media capabilities. Copyright (C) 2010 Belledonne Communications SARL. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "agent.hh" #include "entryfilter.hh" #include <algorithm> using namespace::std; Module *ModuleInfoBase::create(Agent *ag){ Module *mod=_create(ag); mod->setInfo(this); return mod; } ModuleFactory * ModuleFactory::sInstance=NULL; ModuleFactory *ModuleFactory::get(){ if (sInstance==NULL){ sInstance=new ModuleFactory(); } return sInstance; } struct hasName{ hasName(const std::string &ref) : match(ref){ } bool operator()(ModuleInfoBase *info){ return info->getModuleName()==match; } const std::string &match; }; Module *ModuleFactory::createModuleInstance(Agent *ag, const std::string &modname){ list<ModuleInfoBase*>::iterator it; it=find_if(mModules.begin(), mModules.end(), hasName(modname)); if (it!=mModules.end()){ Module *m; ModuleInfoBase *i=*it; m=i->create(ag); LOGI("Creating module instance for [%s]",m->getModuleName().c_str()); return m; } LOGE("Could not find any registered module with name %s",modname.c_str()); return NULL; } void ModuleFactory::registerModule(ModuleInfoBase *m){ LOGI("Registering module %s",m->getModuleName().c_str()); mModules.push_back(m); } Module::Module(Agent *ag ) : mAgent(ag){ mFilter=new ConfigEntryFilter(); } Module::~Module(){ } void Module::setInfo(ModuleInfoBase *i){ mInfo=i; } Agent *Module::getAgent()const{ return mAgent; } nta_agent_t *Module::getSofiaAgent()const{ return mAgent->getSofiaAgent(); } void Module::declare(ConfigStruct *root){ mModuleConfig=new ConfigStruct("module::"+getModuleName(),mInfo->getModuleHelp()); root->addChild(mModuleConfig); mFilter->declareConfig(mModuleConfig); onDeclare(mModuleConfig); } void Module::load(Agent *agent){ mFilter->loadConfig(mModuleConfig); if (mFilter->isEnabled()) onLoad(agent,mModuleConfig); } void Module::processRequest(SipEvent *ev){ if (mFilter->canEnter(ev->mSip)){ LOGD("Invoking onRequest() on module %s",getModuleName().c_str()); onRequest(ev); } } void Module::processResponse(SipEvent *ev){ if (mFilter->canEnter(ev->mSip)){ LOGD("Invoking onResponse() on module %s",getModuleName().c_str()); onResponse(ev); } } void Module::idle(){ onIdle(); } const std::string &Module::getModuleName(){ return mInfo->getModuleName(); } bool ModuleToolbox::sipPortEquals(const char *p1, const char *p2){ int n1,n2; n1=n2=5060; if (p1 && p1[0]!='\0') n1=atoi(p1); if (p2 && p2[0]!='\0') n2=atoi(p2); return n1==n2; } int ModuleToolbox::sipPortToInt(const char *port){ if (port==NULL || port[0]=='\0') return 5060; else return atoi(port); } void ModuleToolbox::addRecordRoute(su_home_t *home, Agent *ag, sip_t *sip){ sip_via_t *via=sip->sip_via; sip_record_route_t *rr; if (strcasecmp(sip_via_transport(via),"TCP")==0) rr=sip_record_route_format(home,"<sip:%s:%i;lr;transport=TCP>",ag->getLocAddr().c_str(),ag->getPort()); else rr=sip_record_route_format(home,"<sip:%s:%i;lr>",ag->getLocAddr().c_str(),ag->getPort()); if (sip->sip_record_route==NULL){ sip->sip_record_route=rr; }else{ sip_record_route_t *it,*last_it=NULL; for(it=sip->sip_record_route;it!=NULL;it=it->r_next){ /*make sure we are not already in*/ if (strcmp(it->r_url->url_host,ag->getLocAddr().c_str())==0 && sipPortToInt(it->r_url->url_port)==ag->getPort()) return; last_it=it; } last_it->r_next=rr; } } bool ModuleToolbox::fromMatch(const sip_from_t *from1, const sip_from_t *from2){ if (url_cmp(from1->a_url,from2->a_url)==0){ if (from1->a_tag && from2->a_tag && strcmp(from1->a_tag,from2->a_tag)==0) return true; if (from1->a_tag==NULL && from2->a_tag==NULL) return true; } return false; } bool ModuleToolbox::matchesOneOf(const char *item, const std::list<std::string> &set){ list<string>::const_iterator it; for(it=set.begin();it!=set.end();++it){ const char *tmp=(*it).c_str(); if (tmp[0]=='*'){ /*the wildcard matches everything*/ return true; }else{ if (strcmp(item,tmp)==0) return true; } } return false; } <|endoftext|>
<commit_before>#include "myers.h" #include <stdint.h> #include <cstdio> using namespace std; typedef uint64_t Word; static const int WORD_SIZE = sizeof(Word) * 8; // Size of Word in bits static const Word HIGH_BIT_MASK = ((Word)1) << (WORD_SIZE-1); static int myersCalcEditDistanceSemiGlobal(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks, const unsigned char* query, int queryLength, const unsigned char* target, int targetLength, int alphabetLength, int k, int mode, int* bestScore, int* position); static int myersCalcEditDistanceNW(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks, const unsigned char* query, int queryLength, const unsigned char* target, int targetLength, int alphabetLength, int k, int* bestScore, int* position); static inline int ceilDiv(int x, int y); int myersCalcEditDistance(const unsigned char* query, int queryLength, const unsigned char* target, int targetLength, int alphabetLength, int k, int mode, int* bestScore, int* position) { /*--------------------- INITIALIZATION ------------------*/ int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE); // bmax in Myers Word* P = new Word[maxNumBlocks]; // Contains Pvin for each block (column is divided into blocks) Word* M = new Word[maxNumBlocks]; // Contains Mvin for each block int* score = new int[maxNumBlocks]; // Contains score for each block Word** Peq = new Word*[alphabetLength+1]; // [alphabetLength+1][maxNumBlocks]. Last symbol is wildcard. int W = maxNumBlocks * WORD_SIZE - queryLength; // number of redundant cells in last level blocks // Build Peq (1 is match, 0 is mismatch). NOTE: last column is wildcard(symbol that matches anything) with just 1s for (int symbol = 0; symbol <= alphabetLength; symbol++) { Peq[symbol] = new Word[maxNumBlocks]; for (int b = 0; b < maxNumBlocks; b++) { if (symbol < alphabetLength) { Peq[symbol][b] = 0; for (int r = (b+1) * WORD_SIZE - 1; r >= b * WORD_SIZE; r--) { Peq[symbol][b] <<= 1; // NOTE: We pretend like query is padded at the end with W wildcard symbols if (r >= queryLength || query[r] == symbol) Peq[symbol][b] += 1; } } else { // Last symbol is wildcard, so it is all 1s Peq[symbol][b] = (Word)-1; } } } /*-------------------------------------------------------*/ /*------------------ MAIN CALCULATION -------------------*/ *bestScore = -1; *position = -1; if (k < 0) { // If valid k is not given, auto-adjust k until solution is found. k = WORD_SIZE; // Gives better results then smaller k while (*bestScore == -1) { if (mode == MYERS_MODE_HW || mode == MYERS_MODE_SHW) myersCalcEditDistanceSemiGlobal(P, M, score, Peq, W, maxNumBlocks, query, queryLength, target, targetLength, alphabetLength, k, mode, bestScore, position); else // mode == MYERS_MODE_NW myersCalcEditDistanceNW(P, M, score, Peq, W, maxNumBlocks, query, queryLength, target, targetLength, alphabetLength, k, bestScore, position); k *= 2; } } else { if (mode == MYERS_MODE_HW || mode == MYERS_MODE_SHW) myersCalcEditDistanceSemiGlobal(P, M, score, Peq, W, maxNumBlocks, query, queryLength, target, targetLength, alphabetLength, k, mode, bestScore, position); else // mode == MYERS_MODE_NW myersCalcEditDistanceNW(P, M, score, Peq, W, maxNumBlocks, query, queryLength, target, targetLength, alphabetLength, k, bestScore, position); } /*-------------------------------------------------------*/ //--- Free memory ---// delete[] P; delete[] M; delete[] score; for (int i = 0; i < alphabetLength+1; i++) delete[] Peq[i]; delete[] Peq; //-------------------// return MYERS_STATUS_OK; } /** * Corresponds to Advance_Block function from Myers. * Calculates one word(block), which is part of a column. * Highest bit of word is most bottom cell of block from column. * @param [in] Pv Bitset, Pv[i] == 1 if vin is +1, otherwise Pv[i] == 0. * @param [in] Mv Bitset, Mv[i] == 1 if vin is -1, otherwise Mv[i] == 0. * @param [in] Eq Bitset, Eq[i] == 1 if match, 0 if mismatch. * @param [in] hin Will be +1, 0 or -1. * @param [out] PvOut Bitset, PvOut[i] == 1 if vout is +1, otherwise PvOut[i] == 0. * @param [out] MvOut Bitset, MvOut[i] == 1 if vout is -1, otherwise MvOut[i] == 0. * @param [out] hout Will be +1, 0 or -1. */ static inline int calculateBlock(Word Pv, Word Mv, Word Eq, const int hin, Word &PvOut, Word &MvOut) { Word Xv = Eq | Mv; if (hin < 0) Eq |= (Word)1; Word Xh = (((Eq & Pv) + Pv) ^ Pv) | Eq; Word Ph = Mv | ~(Xh | Pv); Word Mh = Pv & Xh; int hout = 0; if (Ph & HIGH_BIT_MASK) hout = 1; else if (Mh & HIGH_BIT_MASK) hout = -1; Ph <<= 1; Mh <<= 1; if (hin < 0) Mh |= (Word)1; else if (hin > 0) Ph |= (Word)1; PvOut = Mh | ~(Xv | Ph); MvOut = Ph & Xv; return hout; } /** * Does ceiling division x / y. * Note: x and y must be non-negative and x + y must not overflow. */ static inline int ceilDiv(int x, int y) { return x % y ? x / y + 1 : x / y; } static inline int min(int x, int y) { return x < y ? x : y; } static inline int max(int x, int y) { return x > y ? x : y; } static inline int abs(int x) { return x < 0 ? -1 * x : x; } /** * @param [in] mode MYERS_MODE_HW or MYERS_MODE_SHW */ static int myersCalcEditDistanceSemiGlobal(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks, const unsigned char* query, int queryLength, const unsigned char* target, int targetLength, int alphabetLength, int k, int mode, int* bestScore_, int* position_) { // firstBlock is 0-based index of first block in Ukkonen band. // lastBlock is 0-based index of block AFTER last block in Ukkonen band. <- WATCH OUT! int firstBlock = 0; int lastBlock = min(ceilDiv(k + 1, WORD_SIZE), maxNumBlocks); // y in Myers // Initialize P, M and score for (int b = 0; b < lastBlock; b++) { score[b] = (b+1) * WORD_SIZE; P[b] = (Word)-1; // All 1s M[b] = (Word)0; } int bestScore = -1; int position = -1; for (int c = 0; c < targetLength + W; c++) { // for each column // We pretend like target is padded at end with W wildcard symbols Word* Peq_c = c < targetLength ? Peq[target[c]] : Peq[alphabetLength]; //----------------------- Calculate column -------------------------// int hout = mode == MYERS_MODE_HW ? 0 : 1; // If 0 then gap before query is not penalized for (int b = firstBlock; b < lastBlock; b++) { hout = calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]); score[b] += hout; } //------------------------------------------------------------------// //---------- Adjust number of blocks according to Ukkonen ----------// if (mode != MYERS_MODE_HW) if (score[firstBlock] >= k + WORD_SIZE) { firstBlock++; } if ((score[lastBlock-1] - hout <= k) && (lastBlock < maxNumBlocks) && ((Peq_c[lastBlock] & (Word)1) || hout < 0)) { // If score of left block is not too big, calculate one more block lastBlock++; int b = lastBlock-1; // index of last block (one we just added) P[b] = (Word)-1; // All 1s M[b] = (Word)0; score[b] = score[b-1] - hout + WORD_SIZE + calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]); } else { while (lastBlock > 0 && score[lastBlock-1] >= k + WORD_SIZE) lastBlock--; } // If band stops to exist finish if (lastBlock <= firstBlock) { *bestScore_ = bestScore; *position_ = position; return MYERS_STATUS_OK; } //------------------------------------------------------------------// //------------------------- Update best score ----------------------// if (c >= W && lastBlock == maxNumBlocks) { // We ignore scores from first W columns, they are not relevant. int colScore = score[maxNumBlocks-1]; if (colScore <= k) { // Scores > k dont have correct values (so we cannot use them), but are certainly > k. // NOTE: Score that I find in column c is actually score from column c-W if (bestScore == -1 || colScore < bestScore) { bestScore = colScore; position = c - W; k = bestScore - 1; // Change k so we will look only for better scores then the best found so far. } } } //------------------------------------------------------------------// } *bestScore_ = bestScore; *position_ = position; return MYERS_STATUS_OK; } static int myersCalcEditDistanceNW(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks, const unsigned char* query, int queryLength, const unsigned char* target, int targetLength, int alphabetLength, int k, int* bestScore_, int* position_) { if (k < abs(targetLength - queryLength)) { *bestScore_ = *position_ = -1; return MYERS_STATUS_OK; } // firstBlock is 0-based index of first block in Ukkonen band. // lastBlock is 0-based index of block AFTER last block in Ukkonen band. <- WATCH OUT! int firstBlock = 0; // This is optimal now, by my formula. int lastBlock = min(maxNumBlocks, ceilDiv(min(k, (k + queryLength - targetLength) / 2) + 1, WORD_SIZE)); // y in Myers // Initialize P, M and score for (int b = 0; b < lastBlock; b++) { score[b] = (b+1) * WORD_SIZE; P[b] = (Word)-1; // All 1s M[b] = (Word)0; } for (int c = 0; c < targetLength; c++) { // for each column Word* Peq_c = Peq[target[c]]; //----------------------- Calculate column -------------------------// int hout = 1; for (int b = firstBlock; b < lastBlock; b++) { hout = calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]); score[b] += hout; } //------------------------------------------------------------------// //---------- Adjust number of blocks according to Ukkonen ----------// // Adjust first block - this is optimal now, by my formula. // While outside of band, advance block while (score[firstBlock] >= k + WORD_SIZE || (firstBlock + 1) * WORD_SIZE - 1 < score[firstBlock] - k - targetLength + queryLength + c) { firstBlock++; } // Adjust last block // While block is not out of band, calculate next block while (lastBlock < maxNumBlocks && !(score[lastBlock - 1] >= k + WORD_SIZE || (lastBlock * WORD_SIZE - 1 > k - score[lastBlock - 1] + 2 * WORD_SIZE - 2 - targetLength + c + queryLength))) { lastBlock++; int b = lastBlock-1; // index of last block (one we just added) P[b] = (Word)-1; // All 1s M[b] = (Word)0; int newHout = calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]); score[b] = score[b-1] - hout + WORD_SIZE + newHout; hout = newHout; } // While block is out of band, move one block up. - This is optimal now, by my formula. // NOT WORKING! /* while (lastBlock > 0 && (score[lastBlock - 1] >= k + WORD_SIZE || (lastBlock * WORD_SIZE - 1 > k - score[lastBlock - 1] + 2 * WORD_SIZE - 2 - targetLength + c + queryLength))) { lastBlock--; // PROBLEM: Cini se da cesto/uvijek smanji za 1 previse! }*/ while (lastBlock > 0 && score[lastBlock-1] >= k + WORD_SIZE) { // TODO: put some stronger constraint lastBlock--; } // If band stops to exist finish if (lastBlock <= firstBlock) { *bestScore_ = *position_ = -1; return MYERS_STATUS_OK; } //------------------------------------------------------------------// } if (lastBlock == maxNumBlocks) { // If last block of last column was calculated int bestScore = score[maxNumBlocks-1]; for (int i = 0; i < W; i++) { if (P[maxNumBlocks-1] & HIGH_BIT_MASK) bestScore--; if (M[maxNumBlocks-1] & HIGH_BIT_MASK) bestScore++; P[maxNumBlocks-1] <<= 1; M[maxNumBlocks-1] <<= 1; } if (bestScore <= k) { *bestScore_ = bestScore; *position_ = targetLength - 1; return MYERS_STATUS_OK; } } *bestScore_ = *position_ = -1; return MYERS_STATUS_OK; } <commit_msg>Some fixes, optimal boundary still not working<commit_after>#include "myers.h" #include <stdint.h> using namespace std; typedef uint64_t Word; static const int WORD_SIZE = sizeof(Word) * 8; // Size of Word in bits static const Word HIGH_BIT_MASK = ((Word)1) << (WORD_SIZE-1); static int myersCalcEditDistanceSemiGlobal(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks, const unsigned char* query, int queryLength, const unsigned char* target, int targetLength, int alphabetLength, int k, int mode, int* bestScore, int* position); static int myersCalcEditDistanceNW(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks, const unsigned char* query, int queryLength, const unsigned char* target, int targetLength, int alphabetLength, int k, int* bestScore, int* position); static inline int ceilDiv(int x, int y); int myersCalcEditDistance(const unsigned char* query, int queryLength, const unsigned char* target, int targetLength, int alphabetLength, int k, int mode, int* bestScore, int* position) { /*--------------------- INITIALIZATION ------------------*/ int maxNumBlocks = ceilDiv(queryLength, WORD_SIZE); // bmax in Myers Word* P = new Word[maxNumBlocks]; // Contains Pvin for each block (column is divided into blocks) Word* M = new Word[maxNumBlocks]; // Contains Mvin for each block int* score = new int[maxNumBlocks]; // Contains score for each block Word** Peq = new Word*[alphabetLength+1]; // [alphabetLength+1][maxNumBlocks]. Last symbol is wildcard. int W = maxNumBlocks * WORD_SIZE - queryLength; // number of redundant cells in last level blocks // Build Peq (1 is match, 0 is mismatch). NOTE: last column is wildcard(symbol that matches anything) with just 1s for (int symbol = 0; symbol <= alphabetLength; symbol++) { Peq[symbol] = new Word[maxNumBlocks]; for (int b = 0; b < maxNumBlocks; b++) { if (symbol < alphabetLength) { Peq[symbol][b] = 0; for (int r = (b+1) * WORD_SIZE - 1; r >= b * WORD_SIZE; r--) { Peq[symbol][b] <<= 1; // NOTE: We pretend like query is padded at the end with W wildcard symbols if (r >= queryLength || query[r] == symbol) Peq[symbol][b] += 1; } } else { // Last symbol is wildcard, so it is all 1s Peq[symbol][b] = (Word)-1; } } } /*-------------------------------------------------------*/ /*------------------ MAIN CALCULATION -------------------*/ *bestScore = -1; *position = -1; if (k < 0) { // If valid k is not given, auto-adjust k until solution is found. k = WORD_SIZE; // Gives better results then smaller k while (*bestScore == -1) { if (mode == MYERS_MODE_HW || mode == MYERS_MODE_SHW) myersCalcEditDistanceSemiGlobal(P, M, score, Peq, W, maxNumBlocks, query, queryLength, target, targetLength, alphabetLength, k, mode, bestScore, position); else // mode == MYERS_MODE_NW myersCalcEditDistanceNW(P, M, score, Peq, W, maxNumBlocks, query, queryLength, target, targetLength, alphabetLength, k, bestScore, position); k *= 2; } } else { if (mode == MYERS_MODE_HW || mode == MYERS_MODE_SHW) myersCalcEditDistanceSemiGlobal(P, M, score, Peq, W, maxNumBlocks, query, queryLength, target, targetLength, alphabetLength, k, mode, bestScore, position); else // mode == MYERS_MODE_NW myersCalcEditDistanceNW(P, M, score, Peq, W, maxNumBlocks, query, queryLength, target, targetLength, alphabetLength, k, bestScore, position); } /*-------------------------------------------------------*/ //--- Free memory ---// delete[] P; delete[] M; delete[] score; for (int i = 0; i < alphabetLength+1; i++) delete[] Peq[i]; delete[] Peq; //-------------------// return MYERS_STATUS_OK; } /** * Corresponds to Advance_Block function from Myers. * Calculates one word(block), which is part of a column. * Highest bit of word is most bottom cell of block from column. * @param [in] Pv Bitset, Pv[i] == 1 if vin is +1, otherwise Pv[i] == 0. * @param [in] Mv Bitset, Mv[i] == 1 if vin is -1, otherwise Mv[i] == 0. * @param [in] Eq Bitset, Eq[i] == 1 if match, 0 if mismatch. * @param [in] hin Will be +1, 0 or -1. * @param [out] PvOut Bitset, PvOut[i] == 1 if vout is +1, otherwise PvOut[i] == 0. * @param [out] MvOut Bitset, MvOut[i] == 1 if vout is -1, otherwise MvOut[i] == 0. * @param [out] hout Will be +1, 0 or -1. */ static inline int calculateBlock(Word Pv, Word Mv, Word Eq, const int hin, Word &PvOut, Word &MvOut) { Word Xv = Eq | Mv; if (hin < 0) Eq |= (Word)1; Word Xh = (((Eq & Pv) + Pv) ^ Pv) | Eq; Word Ph = Mv | ~(Xh | Pv); Word Mh = Pv & Xh; int hout = 0; if (Ph & HIGH_BIT_MASK) hout = 1; else if (Mh & HIGH_BIT_MASK) hout = -1; Ph <<= 1; Mh <<= 1; if (hin < 0) Mh |= (Word)1; else if (hin > 0) Ph |= (Word)1; PvOut = Mh | ~(Xv | Ph); MvOut = Ph & Xv; return hout; } /** * Does ceiling division x / y. * Note: x and y must be non-negative and x + y must not overflow. */ static inline int ceilDiv(int x, int y) { return x % y ? x / y + 1 : x / y; } static inline int min(int x, int y) { return x < y ? x : y; } static inline int max(int x, int y) { return x > y ? x : y; } static inline int abs(int x) { return x < 0 ? -1 * x : x; } /** * @param [in] mode MYERS_MODE_HW or MYERS_MODE_SHW */ static int myersCalcEditDistanceSemiGlobal(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks, const unsigned char* query, int queryLength, const unsigned char* target, int targetLength, int alphabetLength, int k, int mode, int* bestScore_, int* position_) { // firstBlock is 0-based index of first block in Ukkonen band. // lastBlock is 0-based index of block AFTER last block in Ukkonen band. <- WATCH OUT! int firstBlock = 0; int lastBlock = min(ceilDiv(k + 1, WORD_SIZE), maxNumBlocks); // y in Myers // Initialize P, M and score for (int b = 0; b < lastBlock; b++) { score[b] = (b+1) * WORD_SIZE; P[b] = (Word)-1; // All 1s M[b] = (Word)0; } int bestScore = -1; int position = -1; for (int c = 0; c < targetLength + W; c++) { // for each column // We pretend like target is padded at end with W wildcard symbols Word* Peq_c = c < targetLength ? Peq[target[c]] : Peq[alphabetLength]; //----------------------- Calculate column -------------------------// int hout = mode == MYERS_MODE_HW ? 0 : 1; // If 0 then gap before query is not penalized for (int b = firstBlock; b < lastBlock; b++) { hout = calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]); score[b] += hout; } //------------------------------------------------------------------// //---------- Adjust number of blocks according to Ukkonen ----------// if (mode != MYERS_MODE_HW) if (score[firstBlock] >= k + WORD_SIZE) { firstBlock++; } if ((score[lastBlock-1] - hout <= k) && (lastBlock < maxNumBlocks) && ((Peq_c[lastBlock] & (Word)1) || hout < 0)) { // If score of left block is not too big, calculate one more block lastBlock++; int b = lastBlock-1; // index of last block (one we just added) P[b] = (Word)-1; // All 1s M[b] = (Word)0; score[b] = score[b-1] - hout + WORD_SIZE + calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]); } else { while (lastBlock > 0 && score[lastBlock-1] >= k + WORD_SIZE) lastBlock--; } // If band stops to exist finish if (lastBlock <= firstBlock) { *bestScore_ = bestScore; *position_ = position; return MYERS_STATUS_OK; } //------------------------------------------------------------------// //------------------------- Update best score ----------------------// if (c >= W && lastBlock == maxNumBlocks) { // We ignore scores from first W columns, they are not relevant. int colScore = score[maxNumBlocks-1]; if (colScore <= k) { // Scores > k dont have correct values (so we cannot use them), but are certainly > k. // NOTE: Score that I find in column c is actually score from column c-W if (bestScore == -1 || colScore < bestScore) { bestScore = colScore; position = c - W; k = bestScore - 1; // Change k so we will look only for better scores then the best found so far. } } } //------------------------------------------------------------------// } *bestScore_ = bestScore; *position_ = position; return MYERS_STATUS_OK; } static int myersCalcEditDistanceNW(Word* P, Word* M, int* score, Word** Peq, int W, int maxNumBlocks, const unsigned char* query, int queryLength, const unsigned char* target, int targetLength, int alphabetLength, int k, int* bestScore_, int* position_) { targetLength += W; queryLength += W; if (k < abs(targetLength - queryLength)) { *bestScore_ = *position_ = -1; return MYERS_STATUS_OK; } // firstBlock is 0-based index of first block in Ukkonen band. // lastBlock is 0-based index of block AFTER last block in Ukkonen band. <- WATCH OUT! int firstBlock = 0; // This is optimal now, by my formula. int lastBlock = min(maxNumBlocks, ceilDiv(min(k, (k + queryLength - targetLength) / 2) + 1, WORD_SIZE)); // y in Myers // Initialize P, M and score for (int b = 0; b < lastBlock; b++) { score[b] = (b+1) * WORD_SIZE; P[b] = (Word)-1; // All 1s M[b] = (Word)0; } for (int c = 0; c < targetLength; c++) { // for each column Word* Peq_c = c < targetLength - W ? Peq[target[c]] : Peq[alphabetLength]; //----------------------- Calculate column -------------------------// int hout = 1; for (int b = firstBlock; b < lastBlock; b++) { hout = calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]); score[b] += hout; } //------------------------------------------------------------------// //---------- Adjust number of blocks according to Ukkonen ----------// // Adjust first block - this is optimal now, by my formula. // While outside of band, advance block while (score[firstBlock] >= k + WORD_SIZE || (firstBlock + 1) * WORD_SIZE - 1 < score[firstBlock] - k - targetLength + queryLength + c) { firstBlock++; } // if (firstBlock == lastBlock) // printf("Ohohoho\n"); //--- Adjust last block ---// // While block is not beneath band, calculate next block while (lastBlock < maxNumBlocks && (firstBlock == lastBlock // If above band || !(score[lastBlock - 1] >= k + WORD_SIZE || (lastBlock * WORD_SIZE - 1 > k - score[lastBlock - 1] + 2 * WORD_SIZE - 2 - targetLength + c + queryLength))) ) { lastBlock++; int b = lastBlock-1; // index of last block (one we just added) P[b] = (Word)-1; // All 1s M[b] = (Word)0; int newHout = calculateBlock(P[b], M[b], Peq_c[b], hout, P[b], M[b]); score[b] = score[b-1] - hout + WORD_SIZE + newHout; hout = newHout; } // While block is out of band, move one block up. - This is optimal now, by my formula. // NOT WORKING! /*while (lastBlock > 0 && (score[lastBlock - 1] >= k + WORD_SIZE || (lastBlock * WORD_SIZE - 1 > k - score[lastBlock - 1] + 2 * WORD_SIZE - 2 - targetLength + c + queryLength))) { lastBlock--; // PROBLEM: Cini se da cesto/uvijek smanji za 1 previse! }*/ while (lastBlock > 0 && score[lastBlock-1] >= k + WORD_SIZE) { // TODO: put some stronger constraint lastBlock--; } //-------------------------// // If band stops to exist finish if (lastBlock <= firstBlock) { //printf("Stopped to exist\n"); *bestScore_ = *position_ = -1; return MYERS_STATUS_OK; } //------------------------------------------------------------------// } if (lastBlock == maxNumBlocks) { // If last block of last column was calculated int bestScore = score[maxNumBlocks-1]; /* for (int i = 0; i < W; i++) { if (P[maxNumBlocks-1] & HIGH_BIT_MASK) bestScore--; if (M[maxNumBlocks-1] & HIGH_BIT_MASK) bestScore++; P[maxNumBlocks-1] <<= 1; M[maxNumBlocks-1] <<= 1; } */ if (bestScore <= k) { *bestScore_ = bestScore; *position_ = targetLength - 1 - W; return MYERS_STATUS_OK; } } *bestScore_ = *position_ = -1; return MYERS_STATUS_OK; } <|endoftext|>
<commit_before>#include "ofApp.h" #include "utils.h" //-------------------------------------------------------------- void ofApp::setup(){ myKinect.open(); faces.setup(&myKinect); //bodies.setup(&myKinect); ofSetWindowShape(640 * 2, 480 * 2); } //-------------------------------------------------------------- void ofApp::update(){ //faces.baseline(); faces.update(); //bodies.update(); #if sample //-- //Getting joint positions (skeleton tracking) //-- // { auto bodies = kinect.getBodySource()->getBodies(); for (auto body : bodies) { for (auto joint : body.joints) { //now do something with the joints } } } // //-- //-- //Getting bones (connected joints) //-- // { // Note that for this we need a reference of which joints are connected to each other. // We call this the 'boneAtlas', and you can ask for a reference to this atlas whenever you like auto bodies = kinect.getBodySource()->getBodies(); auto boneAtlas = ofxKinectForWindows2::Data::Body::getBonesAtlas(); for (auto body : bodies) { for (auto bone : boneAtlas) { auto firstJointInBone = body.joints[bone.first]; auto secondJointInBone = body.joints[bone.second]; //now do something with the joints } } } // //-- #endif } //-------------------------------------------------------------- void ofApp::draw(){ /* kinect.getDepthSource()->draw(0, 0, previewWidth, previewHeight); // note that the depth texture is RAW so may appear dark // Color is at 1920x1080 instead of 512x424 so we should fix aspect ratio kinect.getColorSource()->draw(previewWidth, 0 + colorTop, previewWidth, colorHeight); kinect.getBodySource()->drawProjected(previewWidth, 0 + colorTop, previewWidth, colorHeight); kinect.getInfraredSource()->draw(0, previewHeight, previewWidth, previewHeight); kinect.getBodyIndexSource()->draw(previewWidth, previewHeight, previewWidth, previewHeight); kinect.getBodySource()->drawProjected(previewWidth, previewHeight, previewWidth, previewHeight, ofxKFW2::ProjectionCoordinates::DepthCamera); */ //float colorHeight = previewWidth * (kinect.getColorSource()->getHeight() / kinect.getColorSource()->getWidth()); //float colorTop = (previewHeight - colorHeight) / 2.0; //kinect.getBodySource()->drawProjected(previewWidth, 0 + colorTop, previewWidth, colorHeight, ofxKFW2::ProjectionCoordinates::DepthCamera); //faces.drawProjected(kinect.getBodySource()->getBodies(), previewWidth, 0 + colorTop, previewWidth, colorHeight, ofxKFW2::ProjectionCoordinates::DepthCamera); faces.draw(); //bodies.draw(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <commit_msg>face, joints work separately<commit_after>#include "ofApp.h" #include "utils.h" //-------------------------------------------------------------- void ofApp::setup(){ myKinect.open(); //faces.setup(&myKinect); bodies.setup(&myKinect); ofSetWindowShape(640 * 2, 480 * 2); } //-------------------------------------------------------------- void ofApp::update(){ //faces.baseline(); //faces.update(); bodies.update(); #if sample //-- //Getting joint positions (skeleton tracking) //-- // { auto bodies = kinect.getBodySource()->getBodies(); for (auto body : bodies) { for (auto joint : body.joints) { //now do something with the joints } } } // //-- //-- //Getting bones (connected joints) //-- // { // Note that for this we need a reference of which joints are connected to each other. // We call this the 'boneAtlas', and you can ask for a reference to this atlas whenever you like auto bodies = kinect.getBodySource()->getBodies(); auto boneAtlas = ofxKinectForWindows2::Data::Body::getBonesAtlas(); for (auto body : bodies) { for (auto bone : boneAtlas) { auto firstJointInBone = body.joints[bone.first]; auto secondJointInBone = body.joints[bone.second]; //now do something with the joints } } } // //-- #endif } //-------------------------------------------------------------- void ofApp::draw(){ /* kinect.getDepthSource()->draw(0, 0, previewWidth, previewHeight); // note that the depth texture is RAW so may appear dark // Color is at 1920x1080 instead of 512x424 so we should fix aspect ratio kinect.getColorSource()->draw(previewWidth, 0 + colorTop, previewWidth, colorHeight); kinect.getBodySource()->drawProjected(previewWidth, 0 + colorTop, previewWidth, colorHeight); kinect.getInfraredSource()->draw(0, previewHeight, previewWidth, previewHeight); kinect.getBodyIndexSource()->draw(previewWidth, previewHeight, previewWidth, previewHeight); kinect.getBodySource()->drawProjected(previewWidth, previewHeight, previewWidth, previewHeight, ofxKFW2::ProjectionCoordinates::DepthCamera); */ //float colorHeight = previewWidth * (kinect.getColorSource()->getHeight() / kinect.getColorSource()->getWidth()); //float colorTop = (previewHeight - colorHeight) / 2.0; //kinect.getBodySource()->drawProjected(previewWidth, 0 + colorTop, previewWidth, colorHeight, ofxKFW2::ProjectionCoordinates::DepthCamera); //faces.drawProjected(kinect.getBodySource()->getBodies(), previewWidth, 0 + colorTop, previewWidth, colorHeight, ofxKFW2::ProjectionCoordinates::DepthCamera); //faces.draw(); bodies.draw(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ } <|endoftext|>
<commit_before>#include "ofApp.h" #define kVolHistorySize (400) #define kNumberOfBands (32) //-------------------------------------------------------------- void ofApp::setup(){ ofBackground(0, 0, 0); loudest_band_ = 0; sample_rate_ = 44100; // 0 output channels, // 2 input channels // 44100 samples per second // N samples per buffer // 4 num buffers (latency) ofSoundStreamSetup(0, 2, this, sample_rate_, beat_.getBufferSize(), 4); // configure Gist. gist_.setUseForOnsetDetection(GIST_PEAK_ENERGY); gist_.setThreshold(GIST_PEAK_ENERGY, .05); // detect all Gist features gist_.setDetect(GIST_PITCH); gist_.setDetect(GIST_NOTE); gist_.setDetect(GIST_ROOT_MEAN_SQUARE); gist_.setDetect(GIST_PEAK_ENERGY); gist_.setDetect(GIST_SPECTRAL_CREST); gist_.setDetect(GIST_ZERO_CROSSING_RATE); gist_.setDetect(GIST_SPECTRAL_CENTROID); gist_.setDetect(GIST_SPECTRAL_FLATNESS); gist_.setDetect(GIST_SPECTRAL_DIFFERENCE); gist_.setDetect(GIST_SPECTRAL_DIFFERENCE_COMPLEX); gist_.setDetect(GIST_SPECTRAL_DIFFERENCE_HALFWAY); gist_.setDetect(GIST_HIGH_FREQUENCY_CONTENT); // Volume left.assign(beat_.getBufferSize(), 0.0); right.assign(beat_.getBufferSize(), 0.0); vol_history_.assign(kVolHistorySize, 0.0); current_vol_ = 0; smoothed_vol_ = 0.0; scaled_vol_ = 0.0; // Enable beat detection beat_.enableBeatDetect(); // Listen to Gist events ofAddListener(GistEvent::ON,this,&ofApp::onNoteOn); ofAddListener(GistEvent::OFF,this,&ofApp::onNoteOff); // onset detection onset_decay_rate_ = 0.05; onset_minimum_threshold_ = 0.1; onset_threshold_ = onset_minimum_threshold_; // setup fonts ofTrueTypeFont::setGlobalDpi(72); hudFont.loadFont("verdana.ttf", 12, true, true); //hudFont.setLineHeight(14.0f); //hudFont.setLetterSpacing(1.037); setup_done_ = true; } //-------------------------------------------------------------- void ofApp::update(){ beat_.update(ofGetElapsedTimeMillis()); //lets scale the vol up to a 0-1 range scaled_vol_ = ofMap(smoothed_vol_, 0.0, 0.17, 0.0, 1.0, true); //lets record the volume into an array vol_history_.push_back(scaled_vol_); //if we are bigger the the size we want to record - lets drop the oldest value if( vol_history_.size() >= kVolHistorySize ){ vol_history_.erase(vol_history_.begin(), vol_history_.begin()+1); } // find loudest band float max = 0; int new_loudest = -1; for (int i = 0; i < kNumberOfBands; i++) { float selectedBand = beat_.getBand(i); if (selectedBand > max) { max = selectedBand; new_loudest = i; } } loudest_band_ = new_loudest; } //-------------------------------------------------------------- void ofApp::draw(){ // Draw black background ofSetColor(255, 255, 255); ofFill(); if (draw_hud_) { drawHUD(); } } void ofApp::drawHUD() { // FIXME: show beat ranges too (have couple of predefined ranges or // something, for example 0-10, 20-32 etc. // draw debug variables hudFont.drawString("onset threshold: "+ofToString(onset_threshold_), 10, 20); hudFont.drawString("kick: "+ofToString(beat_.kick()), 10, 40); hudFont.drawString("snare: "+ofToString(beat_.snare()), 10, 60); hudFont.drawString("hihat: "+ofToString(beat_.hihat()), 10, 80); hudFont.drawString("current vol: "+ofToString(current_vol_), 10, 100); hudFont.drawString("smoothed vol: "+ofToString(smoothed_vol_), 10, 120); // kick bar ofSetColor(102, 102, 255); ofNoFill(); ofRect(150, 30, 100, 10); ofFill(); ofRect(150, 30, ofMap(beat_.kick(), 0, 1, 0, 100), 10); // snare bar ofSetColor(102, 102, 255); ofNoFill(); ofRect(150, 50, 100, 10); ofFill(); ofRect(150, 50, ofMap(beat_.snare(), 0, 1, 0, 100), 10); // hihat bar ofSetColor(102, 102, 255); ofNoFill(); ofRect(150, 70, 100, 10); ofFill(); ofRect(150, 70, ofMap(beat_.hihat(), 0, 1, 0, 100), 10); // Draw Gist onset event info ofSetColor(255, 255, 255); hudFont.drawString("GIST ONSET EVENT", 300, 20); hudFont.drawString("energy: "+ofToString(gist_event_energy_), 300, 40); hudFont.drawString("frequency: "+ofToString(gist_event_frequency_), 300, 60); hudFont.drawString("onset amount: "+ofToString(gist_event_onset_amount_), 300, 80); hudFont.drawString("note on: "+ofToString(gist_event_note_on_), 300, 100); // Key hints hudFont.drawString("press 'h' to toggle HUD", 300, 140); // Draw Gist info ofSetColor(255, 255, 255); hudFont.drawString("GIST FEATURES", 300, 180); hudFont.drawString("pitch: "+ofToString(gist_.getValue(GIST_PITCH)), 300, 200); hudFont.drawString("note: "+ofToString(gist_.getValue(GIST_NOTE)), 300, 220); hudFont.drawString("root mean square: "+ofToString(gist_.getValue(GIST_ROOT_MEAN_SQUARE)), 300, 240); hudFont.drawString("peak energy: "+ofToString(gist_.getValue(GIST_PEAK_ENERGY)), 300, 260); hudFont.drawString("special crest: "+ofToString(gist_.getValue(GIST_SPECTRAL_CREST)), 300, 280); hudFont.drawString("zero crossing rate: "+ofToString(gist_.getValue(GIST_ZERO_CROSSING_RATE)), 300, 300); hudFont.drawString("SPECTRAL FEATURES", 300, 320); hudFont.drawString("centroid: "+ofToString(gist_.getValue(GIST_SPECTRAL_CENTROID)), 300, 340); hudFont.drawString("flatness: "+ofToString(gist_.getValue(GIST_SPECTRAL_FLATNESS)), 300, 360); hudFont.drawString("difference: "+ofToString(gist_.getValue(GIST_SPECTRAL_DIFFERENCE)), 300, 380); hudFont.drawString("difference complex: "+ofToString(gist_.getValue(GIST_SPECTRAL_DIFFERENCE_COMPLEX)), 300, 400); hudFont.drawString("difference halfway: "+ofToString(gist_.getValue(GIST_SPECTRAL_DIFFERENCE_HALFWAY)), 300, 420); hudFont.drawString("high freq. content: "+ofToString(gist_.getValue(GIST_HIGH_FREQUENCY_CONTENT)), 300, 440); // Draw individual bands as bars, also show frequencies and values // for each band. ofPushStyle(); ofSetRectMode(OF_RECTMODE_CORNER); ofSetLineWidth(2); const int kVolumeRange = 1; for (int i = 0; i < kNumberOfBands; i++) { float selectedBand = beat_.getBand(i); ofSetColor(255, 255, 255); float hz = ((i+1) * sample_rate_) / beat_.getBufferSize(); std::string text = ofToString(i) + ") " + ofToString(hz) + " hz " + ofToString(selectedBand); hudFont.drawString(text, 10, 140 + (20*i)); if (i== loudest_band_) { ofSetColor(255, 0, 10); } else { ofSetColor(51, 204, 51); } if (beat_.isBeat(i)) { ofFill(); } else { ofNoFill(); } float x = ofGetWidth()*((float)i/kNumberOfBands); float y = ofGetHeight()-20; float w = ofGetWidth()/kNumberOfBands; float h = -ofMap(selectedBand, 0, kVolumeRange, 0, ofGetHeight() / 10); ofRect(x, y, w, h); } ofPopStyle(); ofNoFill(); // draw the left channel: ofPushStyle(); ofPushMatrix(); ofTranslate(565, 20, 0); ofSetColor(225); hudFont.drawString("Left Channel", 4, 18); ofSetLineWidth(1); ofRect(0, 0, 440, 200); ofSetColor(245, 58, 135); ofSetLineWidth(3); ofBeginShape(); for (unsigned int i = 0; i < left.size(); i++){ ofVertex(i*2, 100 -left[i]*180.0f); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); // draw the right channel: ofPushStyle(); ofPushMatrix(); ofTranslate(565, 220, 0); ofSetColor(225); hudFont.drawString("Right Channel", 4, 18); ofSetLineWidth(1); ofRect(0, 0, 440, 200); ofSetColor(245, 58, 135); ofSetLineWidth(3); ofBeginShape(); for (unsigned int i = 0; i < right.size(); i++){ ofVertex(i*2, 100 -right[i]*180.0f); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); // draw the average volume: ofPushStyle(); ofPushMatrix(); ofTranslate(565, 420, 0); ofSetColor(225); hudFont.drawString("Scaled average vol (0-100): " + ofToString(scaled_vol_ * 100.0, 0), 4, 18); ofSetColor(245, 58, 135); ofFill(); ofCircle(200, 100, scaled_vol_ * 100.0f); //lets draw the volume history as a graph ofNoFill(); ofBeginShape(); for (unsigned int i = 0; i < vol_history_.size(); i++){ if( i == 0 ) ofVertex(i, 300); ofVertex(i, 300 - vol_history_[i] * 70); if( i == vol_history_.size() -1 ) ofVertex(i, 300); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); } void ofApp::audioReceived(float* input, int bufferSize, int nChannels) { if (!setup_done_) { return; } beat_.audioReceived(input, bufferSize, channel_count_); channel_count_ = nChannels; //convert float array to vector vector<float>buffer; buffer.assign(&input[0],&input[bufferSize]); gist_.processAudio(buffer, bufferSize, nChannels, sample_rate_); calculateVolume(input, bufferSize); // detect onset onset_threshold_ = ofLerp(onset_threshold_, onset_minimum_threshold_, onset_decay_rate_); if (current_vol_ > onset_threshold_) { // onset detected! onset_threshold_ = current_vol_; } } void ofApp::calculateVolume(float *input, int bufferSize) { // samples are "interleaved" int numCounted = 0; //lets go through each sample and calculate the root mean square which is a rough way to calculate volume for (int i = 0; i < bufferSize; i++){ left[i] = input[i*2]*0.5; right[i] = input[i*2+1]*0.5; current_vol_ += left[i] * left[i]; current_vol_ += right[i] * right[i]; numCounted+=2; } //this is how we get the mean of rms :) current_vol_ /= (float)numCounted; // this is how we get the root of rms :) current_vol_ = sqrt( current_vol_ ); smoothed_vol_ *= 0.93; smoothed_vol_ += 0.07 * current_vol_; } void ofApp::onNoteOn(GistEvent &e){ gist_event_energy_ = e.energy; gist_event_frequency_ = e.frequency; gist_event_note_ = e.note; gist_event_onset_amount_ = e.onsetAmount; gist_event_note_on_ = true; }; void ofApp::onNoteOff(GistEvent &e){ gist_event_energy_ = e.energy; gist_event_frequency_ = e.frequency; gist_event_note_ = e.note; gist_event_onset_amount_ = e.onsetAmount; gist_event_note_on_ = false; }; //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if ('h' == key) { draw_hud_ = !draw_hud_; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }<commit_msg>draw using fbo<commit_after>#include "ofApp.h" #define kVolHistorySize (400) #define kNumberOfBands (32) //-------------------------------------------------------------- void ofApp::setup(){ ofBackground(0, 0, 0); loudest_band_ = 0; sample_rate_ = 44100; // 0 output channels, // 2 input channels // 44100 samples per second // N samples per buffer // 4 num buffers (latency) ofSoundStreamSetup(0, 2, this, sample_rate_, beat_.getBufferSize(), 4); // configure Gist. gist_.setUseForOnsetDetection(GIST_PEAK_ENERGY); gist_.setThreshold(GIST_PEAK_ENERGY, .05); // detect all Gist features gist_.setDetect(GIST_PITCH); gist_.setDetect(GIST_NOTE); gist_.setDetect(GIST_ROOT_MEAN_SQUARE); gist_.setDetect(GIST_PEAK_ENERGY); gist_.setDetect(GIST_SPECTRAL_CREST); gist_.setDetect(GIST_ZERO_CROSSING_RATE); gist_.setDetect(GIST_SPECTRAL_CENTROID); gist_.setDetect(GIST_SPECTRAL_FLATNESS); gist_.setDetect(GIST_SPECTRAL_DIFFERENCE); gist_.setDetect(GIST_SPECTRAL_DIFFERENCE_COMPLEX); gist_.setDetect(GIST_SPECTRAL_DIFFERENCE_HALFWAY); gist_.setDetect(GIST_HIGH_FREQUENCY_CONTENT); // Volume left.assign(beat_.getBufferSize(), 0.0); right.assign(beat_.getBufferSize(), 0.0); vol_history_.assign(kVolHistorySize, 0.0); current_vol_ = 0; smoothed_vol_ = 0.0; scaled_vol_ = 0.0; // Enable beat detection beat_.enableBeatDetect(); // Listen to Gist events ofAddListener(GistEvent::ON,this,&ofApp::onNoteOn); ofAddListener(GistEvent::OFF,this,&ofApp::onNoteOff); // onset detection onset_decay_rate_ = 0.05; onset_minimum_threshold_ = 0.1; onset_threshold_ = onset_minimum_threshold_; // setup fonts ofTrueTypeFont::setGlobalDpi(72); hudFont.loadFont("cooperBlack.ttf", 14, true, true); //hudFont.setLineHeight(14.0f); //hudFont.setLetterSpacing(1.037); // allocate FBO fbo.allocate(ofGetWidth(), ofGetHeight()); setup_done_ = true; } //-------------------------------------------------------------- void ofApp::update(){ beat_.update(ofGetElapsedTimeMillis()); //lets scale the vol up to a 0-1 range scaled_vol_ = ofMap(smoothed_vol_, 0.0, 0.17, 0.0, 1.0, true); //lets record the volume into an array vol_history_.push_back(scaled_vol_); //if we are bigger the the size we want to record - lets drop the oldest value if( vol_history_.size() >= kVolHistorySize ){ vol_history_.erase(vol_history_.begin(), vol_history_.begin()+1); } // find loudest band float max = 0; int new_loudest = -1; for (int i = 0; i < kNumberOfBands; i++) { float selectedBand = beat_.getBand(i); if (selectedBand > max) { max = selectedBand; new_loudest = i; } } loudest_band_ = new_loudest; } //-------------------------------------------------------------- void ofApp::draw(){ fbo.begin(); ofClear(255, 0); // Draw black background ofSetColor(255, 255, 255); ofFill(); if (draw_hud_) { drawHUD(); } fbo.end(); fbo.draw(0, 0); } void ofApp::drawHUD() { // FIXME: show beat ranges too (have couple of predefined ranges or // something, for example 0-10, 20-32 etc. // draw debug variables hudFont.drawString("onset threshold: "+ofToString(onset_threshold_), 10, 20); hudFont.drawString("kick: "+ofToString(beat_.kick()), 10, 40); hudFont.drawString("snare: "+ofToString(beat_.snare()), 10, 60); hudFont.drawString("hihat: "+ofToString(beat_.hihat()), 10, 80); hudFont.drawString("current vol: "+ofToString(current_vol_), 10, 100); hudFont.drawString("smoothed vol: "+ofToString(smoothed_vol_), 10, 120); // kick bar ofSetColor(102, 102, 255); ofNoFill(); ofRect(150, 30, 100, 10); ofFill(); ofRect(150, 30, ofMap(beat_.kick(), 0, 1, 0, 100), 10); // snare bar ofSetColor(102, 102, 255); ofNoFill(); ofRect(150, 50, 100, 10); ofFill(); ofRect(150, 50, ofMap(beat_.snare(), 0, 1, 0, 100), 10); // hihat bar ofSetColor(102, 102, 255); ofNoFill(); ofRect(150, 70, 100, 10); ofFill(); ofRect(150, 70, ofMap(beat_.hihat(), 0, 1, 0, 100), 10); // Draw Gist onset event info ofSetColor(255, 255, 255); hudFont.drawString("GIST ONSET EVENT", 300, 20); hudFont.drawString("energy: "+ofToString(gist_event_energy_), 300, 40); hudFont.drawString("frequency: "+ofToString(gist_event_frequency_), 300, 60); hudFont.drawString("onset amount: "+ofToString(gist_event_onset_amount_), 300, 80); hudFont.drawString("note on: "+ofToString(gist_event_note_on_), 300, 100); // Key hints hudFont.drawString("press 'h' to toggle HUD", 300, 140); // Draw Gist info ofSetColor(255, 255, 255); hudFont.drawString("GIST FEATURES", 300, 180); hudFont.drawString("pitch: "+ofToString(gist_.getValue(GIST_PITCH)), 300, 200); hudFont.drawString("note: "+ofToString(gist_.getValue(GIST_NOTE)), 300, 220); hudFont.drawString("root mean square: "+ofToString(gist_.getValue(GIST_ROOT_MEAN_SQUARE)), 300, 240); hudFont.drawString("peak energy: "+ofToString(gist_.getValue(GIST_PEAK_ENERGY)), 300, 260); hudFont.drawString("special crest: "+ofToString(gist_.getValue(GIST_SPECTRAL_CREST)), 300, 280); hudFont.drawString("zero crossing rate: "+ofToString(gist_.getValue(GIST_ZERO_CROSSING_RATE)), 300, 300); hudFont.drawString("SPECTRAL FEATURES", 300, 320); hudFont.drawString("centroid: "+ofToString(gist_.getValue(GIST_SPECTRAL_CENTROID)), 300, 340); hudFont.drawString("flatness: "+ofToString(gist_.getValue(GIST_SPECTRAL_FLATNESS)), 300, 360); hudFont.drawString("difference: "+ofToString(gist_.getValue(GIST_SPECTRAL_DIFFERENCE)), 300, 380); hudFont.drawString("difference complex: "+ofToString(gist_.getValue(GIST_SPECTRAL_DIFFERENCE_COMPLEX)), 300, 400); hudFont.drawString("difference halfway: "+ofToString(gist_.getValue(GIST_SPECTRAL_DIFFERENCE_HALFWAY)), 300, 420); hudFont.drawString("high freq. content: "+ofToString(gist_.getValue(GIST_HIGH_FREQUENCY_CONTENT)), 300, 440); // Draw individual bands as bars, also show frequencies and values // for each band. ofPushStyle(); ofSetRectMode(OF_RECTMODE_CORNER); ofSetLineWidth(2); const int kVolumeRange = 1; for (int i = 0; i < kNumberOfBands; i++) { float selectedBand = beat_.getBand(i); ofSetColor(255, 255, 255); float hz = ((i+1) * sample_rate_) / beat_.getBufferSize(); std::string text = ofToString(i) + ") " + ofToString(hz) + " hz " + ofToString(selectedBand); hudFont.drawString(text, 10, 140 + (20*i)); if (i== loudest_band_) { ofSetColor(255, 0, 10); } else { ofSetColor(51, 204, 51); } if (beat_.isBeat(i)) { ofFill(); } else { ofNoFill(); } float x = ofGetWidth()*((float)i/kNumberOfBands); float y = ofGetHeight()-20; float w = ofGetWidth()/kNumberOfBands; float h = -ofMap(selectedBand, 0, kVolumeRange, 0, ofGetHeight() / 10); ofRect(x, y, w, h); } ofPopStyle(); ofNoFill(); // draw the left channel: ofPushStyle(); ofPushMatrix(); ofTranslate(565, 20, 0); ofSetColor(225); hudFont.drawString("Left Channel", 4, 18); ofSetLineWidth(1); ofRect(0, 0, 440, 200); ofSetColor(245, 58, 135); ofSetLineWidth(3); ofBeginShape(); for (unsigned int i = 0; i < left.size(); i++){ ofVertex(i*2, 100 -left[i]*180.0f); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); // draw the right channel: ofPushStyle(); ofPushMatrix(); ofTranslate(565, 220, 0); ofSetColor(225); hudFont.drawString("Right Channel", 4, 18); ofSetLineWidth(1); ofRect(0, 0, 440, 200); ofSetColor(245, 58, 135); ofSetLineWidth(3); ofBeginShape(); for (unsigned int i = 0; i < right.size(); i++){ ofVertex(i*2, 100 -right[i]*180.0f); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); // draw the average volume: ofPushStyle(); ofPushMatrix(); ofTranslate(565, 420, 0); ofSetColor(225); hudFont.drawString("Scaled average vol (0-100): " + ofToString(scaled_vol_ * 100.0, 0), 4, 18); ofSetColor(245, 58, 135); ofFill(); ofCircle(200, 100, scaled_vol_ * 100.0f); //lets draw the volume history as a graph ofNoFill(); ofBeginShape(); for (unsigned int i = 0; i < vol_history_.size(); i++){ if( i == 0 ) ofVertex(i, 300); ofVertex(i, 300 - vol_history_[i] * 70); if( i == vol_history_.size() -1 ) ofVertex(i, 300); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); } void ofApp::audioReceived(float* input, int bufferSize, int nChannels) { if (!setup_done_) { return; } beat_.audioReceived(input, bufferSize, channel_count_); channel_count_ = nChannels; //convert float array to vector vector<float>buffer; buffer.assign(&input[0],&input[bufferSize]); gist_.processAudio(buffer, bufferSize, nChannels, sample_rate_); calculateVolume(input, bufferSize); // detect onset onset_threshold_ = ofLerp(onset_threshold_, onset_minimum_threshold_, onset_decay_rate_); if (current_vol_ > onset_threshold_) { // onset detected! onset_threshold_ = current_vol_; } } void ofApp::calculateVolume(float *input, int bufferSize) { // samples are "interleaved" int numCounted = 0; //lets go through each sample and calculate the root mean square which is a rough way to calculate volume for (int i = 0; i < bufferSize; i++){ left[i] = input[i*2]*0.5; right[i] = input[i*2+1]*0.5; current_vol_ += left[i] * left[i]; current_vol_ += right[i] * right[i]; numCounted+=2; } //this is how we get the mean of rms :) current_vol_ /= (float)numCounted; // this is how we get the root of rms :) current_vol_ = sqrt( current_vol_ ); smoothed_vol_ *= 0.93; smoothed_vol_ += 0.07 * current_vol_; } void ofApp::onNoteOn(GistEvent &e){ gist_event_energy_ = e.energy; gist_event_frequency_ = e.frequency; gist_event_note_ = e.note; gist_event_onset_amount_ = e.onsetAmount; gist_event_note_on_ = true; }; void ofApp::onNoteOff(GistEvent &e){ gist_event_energy_ = e.energy; gist_event_frequency_ = e.frequency; gist_event_note_ = e.note; gist_event_onset_amount_ = e.onsetAmount; gist_event_note_on_ = false; }; //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if ('h' == key) { draw_hud_ = !draw_hud_; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }<|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" //#include "SkParsePath.h" #include "SkPath.h" //#include "SkRandom.h" namespace skiagm { static const SkColor gPathColor = SK_ColorBLACK; static const SkColor gClipAColor = SK_ColorBLUE; static const SkColor gClipBColor = SK_ColorRED; class ComplexClipGM : public GM { bool fDoAAClip; bool fSaveLayer; public: ComplexClipGM(bool aaclip, bool saveLayer) : fDoAAClip(aaclip) , fSaveLayer(saveLayer) { this->setBGColor(0xFFDDDDDD); // this->setBGColor(SkColorSetRGB(0xB0,0xDD,0xB0)); } protected: SkString onShortName() { SkString str; str.printf("complexclip_%s%s", fDoAAClip ? "aa" : "bw", fSaveLayer ? "_layer" : ""); return str; } SkISize onISize() { return make_isize(970, 780); } virtual void onDraw(SkCanvas* canvas) { SkPath path; path.moveTo(SkIntToScalar(0), SkIntToScalar(50)); path.quadTo(SkIntToScalar(0), SkIntToScalar(0), SkIntToScalar(50), SkIntToScalar(0)); path.lineTo(SkIntToScalar(175), SkIntToScalar(0)); path.quadTo(SkIntToScalar(200), SkIntToScalar(0), SkIntToScalar(200), SkIntToScalar(25)); path.lineTo(SkIntToScalar(200), SkIntToScalar(150)); path.quadTo(SkIntToScalar(200), SkIntToScalar(200), SkIntToScalar(150), SkIntToScalar(200)); path.lineTo(SkIntToScalar(0), SkIntToScalar(200)); path.close(); path.moveTo(SkIntToScalar(50), SkIntToScalar(50)); path.lineTo(SkIntToScalar(150), SkIntToScalar(50)); path.lineTo(SkIntToScalar(150), SkIntToScalar(125)); path.quadTo(SkIntToScalar(150), SkIntToScalar(150), SkIntToScalar(125), SkIntToScalar(150)); path.lineTo(SkIntToScalar(50), SkIntToScalar(150)); path.close(); path.setFillType(SkPath::kEvenOdd_FillType); SkPaint pathPaint; pathPaint.setAntiAlias(true); pathPaint.setColor(gPathColor); SkPath clipA; clipA.moveTo(SkIntToScalar(10), SkIntToScalar(20)); clipA.lineTo(SkIntToScalar(165), SkIntToScalar(22)); clipA.lineTo(SkIntToScalar(70), SkIntToScalar(105)); clipA.lineTo(SkIntToScalar(165), SkIntToScalar(177)); clipA.lineTo(SkIntToScalar(-5), SkIntToScalar(180)); clipA.close(); SkPath clipB; clipB.moveTo(SkIntToScalar(40), SkIntToScalar(10)); clipB.lineTo(SkIntToScalar(190), SkIntToScalar(15)); clipB.lineTo(SkIntToScalar(195), SkIntToScalar(190)); clipB.lineTo(SkIntToScalar(40), SkIntToScalar(185)); clipB.lineTo(SkIntToScalar(155), SkIntToScalar(100)); clipB.close(); SkPaint paint; paint.setAntiAlias(true); paint.setTextSize(SkIntToScalar(20)); static const struct { SkRegion::Op fOp; const char* fName; } gOps[] = { //extra spaces in names for measureText {SkRegion::kIntersect_Op, "Isect "}, {SkRegion::kDifference_Op, "Diff " }, {SkRegion::kUnion_Op, "Union "}, {SkRegion::kXOR_Op, "Xor " }, {SkRegion::kReverseDifference_Op, "RDiff "} }; canvas->translate(SkIntToScalar(20), SkIntToScalar(20)); canvas->scale(3 * SK_Scalar1 / 4, 3 * SK_Scalar1 / 4); if (fSaveLayer) { SkRect bounds = SkRect::MakeXYWH(100, 100, 1000, 750); SkPaint boundPaint; boundPaint.setColor(SK_ColorRED); boundPaint.setStyle(SkPaint::kStroke_Style); canvas->drawRect(bounds, boundPaint); canvas->saveLayer(&bounds, NULL); } for (int invBits = 0; invBits < 4; ++invBits) { canvas->save(); for (size_t op = 0; op < SK_ARRAY_COUNT(gOps); ++op) { this->drawHairlines(canvas, path, clipA, clipB); bool doInvA = SkToBool(invBits & 1); bool doInvB = SkToBool(invBits & 2); canvas->save(); // set clip clipA.setFillType(doInvA ? SkPath::kInverseEvenOdd_FillType : SkPath::kEvenOdd_FillType); clipB.setFillType(doInvB ? SkPath::kInverseEvenOdd_FillType : SkPath::kEvenOdd_FillType); canvas->clipPath(clipA, SkRegion::kIntersect_Op, fDoAAClip); canvas->clipPath(clipB, gOps[op].fOp, fDoAAClip); // draw path clipped canvas->drawPath(path, pathPaint); canvas->restore(); SkScalar txtX = SkIntToScalar(45); paint.setColor(gClipAColor); const char* aTxt = doInvA ? "InvA " : "A "; canvas->drawText(aTxt, strlen(aTxt), txtX, SkIntToScalar(220), paint); txtX += paint.measureText(aTxt, strlen(aTxt)); paint.setColor(SK_ColorBLACK); canvas->drawText(gOps[op].fName, strlen(gOps[op].fName), txtX, SkIntToScalar(220), paint); txtX += paint.measureText(gOps[op].fName, strlen(gOps[op].fName)); paint.setColor(gClipBColor); const char* bTxt = doInvB ? "InvB " : "B "; canvas->drawText(bTxt, strlen(bTxt), txtX, SkIntToScalar(220), paint); canvas->translate(SkIntToScalar(250),0); } canvas->restore(); canvas->translate(0, SkIntToScalar(250)); } if (fSaveLayer) { canvas->restore(); } } private: void drawHairlines(SkCanvas* canvas, const SkPath& path, const SkPath& clipA, const SkPath& clipB) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); const SkAlpha fade = 0x33; // draw path in hairline paint.setColor(gPathColor); paint.setAlpha(fade); canvas->drawPath(path, paint); // draw clips in hair line paint.setColor(gClipAColor); paint.setAlpha(fade); canvas->drawPath(clipA, paint); paint.setColor(gClipBColor); paint.setAlpha(fade); canvas->drawPath(clipB, paint); } typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// // aliased and anti-aliased w/o a layer static GM* gFact0(void*) { return new ComplexClipGM(false, false); } static GM* gFact1(void*) { return new ComplexClipGM(true, false); } // aliased and anti-aliased w/ a layer static GM* gFact2(void*) { return new ComplexClipGM(false, true); } static GM* gFact3(void*) { return new ComplexClipGM(true, true); } static GMRegistry gReg0(gFact0); static GMRegistry gReg1(gFact1); static GMRegistry gReg2(gFact2); static GMRegistry gReg3(gFact3); } <commit_msg>Improved clarity of complexclip GM<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" //#include "SkParsePath.h" #include "SkPath.h" //#include "SkRandom.h" namespace skiagm { static const SkColor gPathColor = SK_ColorBLACK; static const SkColor gClipAColor = SK_ColorBLUE; static const SkColor gClipBColor = SK_ColorRED; class ComplexClipGM : public GM { bool fDoAAClip; bool fDoSaveLayer; public: ComplexClipGM(bool aaclip, bool saveLayer) : fDoAAClip(aaclip) , fDoSaveLayer(saveLayer) { this->setBGColor(0xFFDDDDDD); // this->setBGColor(SkColorSetRGB(0xB0,0xDD,0xB0)); } protected: SkString onShortName() { SkString str; str.printf("complexclip_%s%s", fDoAAClip ? "aa" : "bw", fDoSaveLayer ? "_layer" : ""); return str; } SkISize onISize() { return make_isize(970, 780); } virtual void onDraw(SkCanvas* canvas) { SkPath path; path.moveTo(SkIntToScalar(0), SkIntToScalar(50)); path.quadTo(SkIntToScalar(0), SkIntToScalar(0), SkIntToScalar(50), SkIntToScalar(0)); path.lineTo(SkIntToScalar(175), SkIntToScalar(0)); path.quadTo(SkIntToScalar(200), SkIntToScalar(0), SkIntToScalar(200), SkIntToScalar(25)); path.lineTo(SkIntToScalar(200), SkIntToScalar(150)); path.quadTo(SkIntToScalar(200), SkIntToScalar(200), SkIntToScalar(150), SkIntToScalar(200)); path.lineTo(SkIntToScalar(0), SkIntToScalar(200)); path.close(); path.moveTo(SkIntToScalar(50), SkIntToScalar(50)); path.lineTo(SkIntToScalar(150), SkIntToScalar(50)); path.lineTo(SkIntToScalar(150), SkIntToScalar(125)); path.quadTo(SkIntToScalar(150), SkIntToScalar(150), SkIntToScalar(125), SkIntToScalar(150)); path.lineTo(SkIntToScalar(50), SkIntToScalar(150)); path.close(); path.setFillType(SkPath::kEvenOdd_FillType); SkPaint pathPaint; pathPaint.setAntiAlias(true); pathPaint.setColor(gPathColor); SkPath clipA; clipA.moveTo(SkIntToScalar(10), SkIntToScalar(20)); clipA.lineTo(SkIntToScalar(165), SkIntToScalar(22)); clipA.lineTo(SkIntToScalar(70), SkIntToScalar(105)); clipA.lineTo(SkIntToScalar(165), SkIntToScalar(177)); clipA.lineTo(SkIntToScalar(-5), SkIntToScalar(180)); clipA.close(); SkPath clipB; clipB.moveTo(SkIntToScalar(40), SkIntToScalar(10)); clipB.lineTo(SkIntToScalar(190), SkIntToScalar(15)); clipB.lineTo(SkIntToScalar(195), SkIntToScalar(190)); clipB.lineTo(SkIntToScalar(40), SkIntToScalar(185)); clipB.lineTo(SkIntToScalar(155), SkIntToScalar(100)); clipB.close(); SkPaint paint; paint.setAntiAlias(true); paint.setTextSize(SkIntToScalar(20)); static const struct { SkRegion::Op fOp; const char* fName; } gOps[] = { //extra spaces in names for measureText {SkRegion::kIntersect_Op, "Isect "}, {SkRegion::kDifference_Op, "Diff " }, {SkRegion::kUnion_Op, "Union "}, {SkRegion::kXOR_Op, "Xor " }, {SkRegion::kReverseDifference_Op, "RDiff "} }; canvas->translate(SkIntToScalar(20), SkIntToScalar(20)); canvas->scale(3 * SK_Scalar1 / 4, 3 * SK_Scalar1 / 4); if (fDoSaveLayer) { // We want the layer to appear symmetric relative to actual // device boundaries so we need to "undo" the effect of the // scale and translate SkRect bounds = SkRect::MakeLTRB( SkIntToScalar(4.0f/3.0f * -20), SkIntToScalar(4.0f/3.0f * -20), SkFloatToScalar(4.0f/3.0f * (this->getISize().fWidth - 20)), SkFloatToScalar(4.0f/3.0f * (this->getISize().fHeight - 20))); bounds.inset(SkIntToScalar(100), SkIntToScalar(100)); SkPaint boundPaint; boundPaint.setColor(SK_ColorRED); boundPaint.setStyle(SkPaint::kStroke_Style); canvas->drawRect(bounds, boundPaint); canvas->saveLayer(&bounds, NULL); } for (int invBits = 0; invBits < 4; ++invBits) { canvas->save(); for (size_t op = 0; op < SK_ARRAY_COUNT(gOps); ++op) { this->drawHairlines(canvas, path, clipA, clipB); bool doInvA = SkToBool(invBits & 1); bool doInvB = SkToBool(invBits & 2); canvas->save(); // set clip clipA.setFillType(doInvA ? SkPath::kInverseEvenOdd_FillType : SkPath::kEvenOdd_FillType); clipB.setFillType(doInvB ? SkPath::kInverseEvenOdd_FillType : SkPath::kEvenOdd_FillType); canvas->clipPath(clipA, SkRegion::kIntersect_Op, fDoAAClip); canvas->clipPath(clipB, gOps[op].fOp, fDoAAClip); // draw path clipped canvas->drawPath(path, pathPaint); canvas->restore(); SkScalar txtX = SkIntToScalar(45); paint.setColor(gClipAColor); const char* aTxt = doInvA ? "InvA " : "A "; canvas->drawText(aTxt, strlen(aTxt), txtX, SkIntToScalar(220), paint); txtX += paint.measureText(aTxt, strlen(aTxt)); paint.setColor(SK_ColorBLACK); canvas->drawText(gOps[op].fName, strlen(gOps[op].fName), txtX, SkIntToScalar(220), paint); txtX += paint.measureText(gOps[op].fName, strlen(gOps[op].fName)); paint.setColor(gClipBColor); const char* bTxt = doInvB ? "InvB " : "B "; canvas->drawText(bTxt, strlen(bTxt), txtX, SkIntToScalar(220), paint); canvas->translate(SkIntToScalar(250),0); } canvas->restore(); canvas->translate(0, SkIntToScalar(250)); } if (fDoSaveLayer) { canvas->restore(); } } private: void drawHairlines(SkCanvas* canvas, const SkPath& path, const SkPath& clipA, const SkPath& clipB) { SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); const SkAlpha fade = 0x33; // draw path in hairline paint.setColor(gPathColor); paint.setAlpha(fade); canvas->drawPath(path, paint); // draw clips in hair line paint.setColor(gClipAColor); paint.setAlpha(fade); canvas->drawPath(clipA, paint); paint.setColor(gClipBColor); paint.setAlpha(fade); canvas->drawPath(clipB, paint); } typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// // aliased and anti-aliased w/o a layer static GM* gFact0(void*) { return new ComplexClipGM(false, false); } static GM* gFact1(void*) { return new ComplexClipGM(true, false); } // aliased and anti-aliased w/ a layer static GM* gFact2(void*) { return new ComplexClipGM(false, true); } static GM* gFact3(void*) { return new ComplexClipGM(true, true); } static GMRegistry gReg0(gFact0); static GMRegistry gReg1(gFact1); static GMRegistry gReg2(gFact2); static GMRegistry gReg3(gFact3); } <|endoftext|>
<commit_before>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkColorPriv.h" #include "SkShader.h" /* * Want to ensure that our bitmap sampler (in bitmap shader) keeps plenty of * precision when scaling very large images (where the dx might get very small. */ #define W 2560 #define H 1600 class GiantBitmapGM : public skiagm::GM { SkBitmap* fBM; SkShader::TileMode fMode; const SkBitmap& getBitmap() { if (NULL == fBM) { fBM = new SkBitmap; fBM->setConfig(SkBitmap::kARGB_8888_Config, W, H); fBM->allocPixels(); fBM->eraseColor(SK_ColorWHITE); const SkColor colors[] = { SK_ColorBLUE, SK_ColorRED, SK_ColorBLACK, SK_ColorGREEN }; SkCanvas canvas(*fBM); SkPaint paint; paint.setAntiAlias(true); paint.setStrokeWidth(SkIntToScalar(30)); for (int y = -H; y < H; y += 80) { SkScalar yy = SkIntToScalar(y); paint.setColor(colors[y/80 & 0x3]); canvas.drawLine(0, yy, SkIntToScalar(W), yy + SkIntToScalar(W), paint); } } return *fBM; } public: GiantBitmapGM(SkShader::TileMode mode) : fBM(NULL), fMode(mode) {} virtual ~GiantBitmapGM() { SkDELETE(fBM); } protected: // work-around for bug http://code.google.com/p/skia/issues/detail?id=520 // virtual uint32_t onGetFlags() const { return kSkipPDF_Flag; } virtual SkString onShortName() { SkString str("giantbitmap_"); switch (fMode) { case SkShader::kClamp_TileMode: str.append("clamp"); break; case SkShader::kRepeat_TileMode: str.append("repeat"); break; case SkShader::kMirror_TileMode: str.append("mirror"); break; default: break; } return str; } virtual SkISize onISize() { return SkISize::Make(640, 480); } virtual void onDraw(SkCanvas* canvas) { SkPaint paint; SkShader* s = SkShader::CreateBitmapShader(getBitmap(), fMode, fMode); SkMatrix m; m.setScale(2*SK_Scalar1/3, 2*SK_Scalar1/3); s->setLocalMatrix(m); paint.setShader(s)->unref(); canvas->drawPaint(paint); } private: typedef GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static skiagm::GM* G0(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode); } static skiagm::GM* G1(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode); } static skiagm::GM* G2(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode); } static skiagm::GMRegistry reg0(G0); static skiagm::GMRegistry reg1(G1); static skiagm::GMRegistry reg2(G2); <commit_msg>add more modes/flags to giantbitmap test<commit_after>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "SkCanvas.h" #include "SkColorPriv.h" #include "SkShader.h" /* * Want to ensure that our bitmap sampler (in bitmap shader) keeps plenty of * precision when scaling very large images (where the dx might get very small. */ #define W 256 #define H 160 class GiantBitmapGM : public skiagm::GM { SkBitmap* fBM; SkShader::TileMode fMode; bool fDoFilter; bool fDoRotate; const SkBitmap& getBitmap() { if (NULL == fBM) { fBM = new SkBitmap; fBM->setConfig(SkBitmap::kARGB_8888_Config, W, H); fBM->allocPixels(); fBM->eraseColor(SK_ColorWHITE); const SkColor colors[] = { SK_ColorBLUE, SK_ColorRED, SK_ColorBLACK, SK_ColorGREEN }; SkCanvas canvas(*fBM); SkPaint paint; paint.setAntiAlias(true); paint.setStrokeWidth(SkIntToScalar(30)); for (int y = -H*2; y < H; y += 80) { SkScalar yy = SkIntToScalar(y); paint.setColor(colors[y/80 & 0x3]); canvas.drawLine(0, yy, SkIntToScalar(W), yy + SkIntToScalar(W), paint); } } return *fBM; } public: GiantBitmapGM(SkShader::TileMode mode, bool doFilter, bool doRotate) : fBM(NULL) { fMode = mode; fDoFilter = doFilter; fDoRotate = doRotate; } virtual ~GiantBitmapGM() { SkDELETE(fBM); } protected: // work-around for bug http://code.google.com/p/skia/issues/detail?id=520 // virtual uint32_t onGetFlags() const { return kSkipPDF_Flag; } virtual SkString onShortName() { SkString str("giantbitmap_"); switch (fMode) { case SkShader::kClamp_TileMode: str.append("clamp"); break; case SkShader::kRepeat_TileMode: str.append("repeat"); break; case SkShader::kMirror_TileMode: str.append("mirror"); break; default: break; } str.append(fDoFilter ? "_bilerp" : "_point"); str.append(fDoRotate ? "_rotate" : "_scale"); return str; } virtual SkISize onISize() { return SkISize::Make(640, 480); } virtual void onDraw(SkCanvas* canvas) { SkPaint paint; SkShader* s = SkShader::CreateBitmapShader(getBitmap(), fMode, fMode); SkMatrix m; if (fDoRotate) { // m.setRotate(SkIntToScalar(30), 0, 0); m.setSkew(SK_Scalar1, 0, 0, 0); m.postScale(2*SK_Scalar1/3, 2*SK_Scalar1/3); } else { m.setScale(2*SK_Scalar1/3, 2*SK_Scalar1/3); } s->setLocalMatrix(m); paint.setShader(s)->unref(); paint.setFilterBitmap(fDoFilter); canvas->translate(SkIntToScalar(50), SkIntToScalar(50)); canvas->drawPaint(paint); } private: typedef GM INHERITED; }; /////////////////////////////////////////////////////////////////////////////// static skiagm::GM* G000(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, false); } static skiagm::GM* G100(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, false); } static skiagm::GM* G200(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, false); } static skiagm::GM* G010(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, false); } static skiagm::GM* G110(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, false); } static skiagm::GM* G210(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, false); } static skiagm::GM* G001(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, false, true); } static skiagm::GM* G101(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, false, true); } static skiagm::GM* G201(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, false, true); } static skiagm::GM* G011(void*) { return new GiantBitmapGM(SkShader::kClamp_TileMode, true, true); } static skiagm::GM* G111(void*) { return new GiantBitmapGM(SkShader::kRepeat_TileMode, true, true); } static skiagm::GM* G211(void*) { return new GiantBitmapGM(SkShader::kMirror_TileMode, true, true); } static skiagm::GMRegistry reg000(G000); static skiagm::GMRegistry reg100(G100); static skiagm::GMRegistry reg200(G200); static skiagm::GMRegistry reg010(G010); static skiagm::GMRegistry reg110(G110); static skiagm::GMRegistry reg210(G210); static skiagm::GMRegistry reg001(G001); static skiagm::GMRegistry reg101(G101); static skiagm::GMRegistry reg201(G201); static skiagm::GMRegistry reg011(G011); static skiagm::GMRegistry reg111(G111); static skiagm::GMRegistry reg211(G211); <|endoftext|>
<commit_before> /* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkObjectParser.h" /* TODO(chudy): Replace all std::strings with char */ SkString* SkObjectParser::BitmapToString(const SkBitmap& bitmap) { SkString* mBitmap = new SkString("SkBitmap: Data unavailable"); return mBitmap; } SkString* SkObjectParser::BoolToString(bool doAA) { SkString* mBool = new SkString("Bool doAA: "); if (doAA) { mBool->append("True"); } else { mBool->append("False"); } return mBool; } SkString* SkObjectParser::CustomTextToString(const char* text) { SkString* mText = new SkString(text); return mText; } SkString* SkObjectParser::IntToString(int x, const char* text) { SkString* mInt = new SkString(text); mInt->append(" "); mInt->appendScalar(SkIntToScalar(x)); return mInt; } SkString* SkObjectParser::IRectToString(const SkIRect& rect) { SkString* mRect = new SkString("SkIRect: "); mRect->append("L: "); mRect->appendScalar(SkIntToScalar(rect.left())); mRect->append(", T: "); mRect->appendScalar(SkIntToScalar(rect.top())); mRect->append(", R: "); mRect->appendScalar(SkIntToScalar(rect.right())); mRect->append(", B: "); mRect->appendScalar(SkIntToScalar(rect.bottom())); return mRect; } SkString* SkObjectParser::MatrixToString(const SkMatrix& matrix) { SkString* mMatrix = new SkString("SkMatrix: ("); for (int i = 0; i < 8; i++) { mMatrix->appendScalar(matrix.get(i)); mMatrix->append("), ("); } mMatrix->appendScalar(matrix.get(8)); mMatrix->append(")"); return mMatrix; } SkString* SkObjectParser::PaintToString(const SkPaint& paint) { SkColor color = paint.getColor(); SkString* mPaint = new SkString("SkPaint: 0x"); mPaint->appendHex(color); return mPaint; } SkString* SkObjectParser::PathToString(const SkPath& path) { SkString* mPath = new SkString("Path ("); static const char* gConvexityStrings[] = { "Unknown", "Convex", "Concave" }; SkASSERT(SkPath::kConcave_Convexity == 2); mPath->append(gConvexityStrings[path.getConvexity()]); mPath->append(", "); mPath->appendS32(path.countVerbs()); mPath->append("V, "); mPath->appendS32(path.countPoints()); mPath->append("P): "); static const char* gVerbStrings[] = { "Move", "Line", "Quad", "Cubic", "Close", "Done" }; static const int gPtsPerVerb[] = { 1, 1, 2, 3, 0, 0 }; static const int gPtOffsetPerVerb[] = { 0, 1, 1, 1, 0, 0 }; SkASSERT(SkPath::kDone_Verb == 5); SkPath::Iter iter(const_cast<SkPath&>(path), false); SkPath::Verb verb; SkPoint points[4]; for(verb = iter.next(points, false); verb != SkPath::kDone_Verb; verb = iter.next(points, false)) { mPath->append(gVerbStrings[verb]); mPath->append(" "); for (int i = 0; i < gPtsPerVerb[verb]; ++i) { mPath->append("("); mPath->appendScalar(points[gPtOffsetPerVerb[verb]+i].fX); mPath->append(", "); mPath->appendScalar(points[gPtOffsetPerVerb[verb]+i].fY); mPath->append(") "); } } return mPath; } SkString* SkObjectParser::PointsToString(const SkPoint pts[], size_t count) { SkString* mPoints = new SkString("SkPoints pts[]: "); for (unsigned int i = 0; i < count; i++) { mPoints->append("("); mPoints->appendScalar(pts[i].fX); mPoints->append(","); mPoints->appendScalar(pts[i].fY); mPoints->append(")"); } return mPoints; } SkString* SkObjectParser::PointModeToString(SkCanvas::PointMode mode) { SkString* mMode = new SkString("SkCanvas::PointMode: "); if (mode == SkCanvas::kPoints_PointMode) { mMode->append("kPoints_PointMode"); } else if (mode == SkCanvas::kLines_PointMode) { mMode->append("kLines_Mode"); } else if (mode == SkCanvas::kPolygon_PointMode) { mMode->append("kPolygon_PointMode"); } return mMode; } SkString* SkObjectParser::RectToString(const SkRect& rect) { SkString* mRect = new SkString("SkRect: "); mRect->append("("); mRect->appendScalar(rect.left()); mRect->append(", "); mRect->appendScalar(rect.top()); mRect->append(", "); mRect->appendScalar(rect.right()); mRect->append(", "); mRect->appendScalar(rect.bottom()); mRect->append(")"); return mRect; } SkString* SkObjectParser::RegionOpToString(SkRegion::Op op) { SkString* mOp = new SkString("SkRegion::Op: "); if (op == SkRegion::kDifference_Op) { mOp->append("kDifference_Op"); } else if (op == SkRegion::kIntersect_Op) { mOp->append("kIntersect_Op"); } else if (op == SkRegion::kUnion_Op) { mOp->append("kUnion_Op"); } else if (op == SkRegion::kXOR_Op) { mOp->append("kXOR_Op"); } else if (op == SkRegion::kReverseDifference_Op) { mOp->append("kReverseDifference_Op"); } else if (op == SkRegion::kReplace_Op) { mOp->append("kReplace_Op"); } else { mOp->append("Unknown Type"); } return mOp; } SkString* SkObjectParser::RegionToString(const SkRegion& region) { SkString* mRegion = new SkString("SkRegion: Data unavailable."); return mRegion; } SkString* SkObjectParser::SaveFlagsToString(SkCanvas::SaveFlags flags) { SkString* mFlags = new SkString("SkCanvas::SaveFlags: "); if(flags == SkCanvas::kMatrixClip_SaveFlag) { mFlags->append("kMatrixClip_SaveFlag"); } else if (flags == SkCanvas::kClip_SaveFlag) { mFlags->append("kClip_SaveFlag"); } else if (flags == SkCanvas::kHasAlphaLayer_SaveFlag) { mFlags->append("kHasAlphaLayer_SaveFlag"); } else if (flags == SkCanvas::kFullColorLayer_SaveFlag) { mFlags->append("kFullColorLayer_SaveFlag"); } else if (flags == SkCanvas::kClipToLayer_SaveFlag) { mFlags->append("kClipToLayer_SaveFlag"); } else if (flags == SkCanvas::kMatrixClip_SaveFlag) { mFlags->append("kMatrixClip_SaveFlag"); } else if (flags == SkCanvas::kARGB_NoClipLayer_SaveFlag) { mFlags->append("kARGB_NoClipLayer_SaveFlag"); } else if (flags == SkCanvas::kARGB_ClipLayer_SaveFlag) { mFlags->append("kARGB_ClipLayer_SaveFlag"); } else { mFlags->append("Data Unavailable"); } return mFlags; } SkString* SkObjectParser::ScalarToString(SkScalar x, const char* text) { SkString* mScalar = new SkString(text); mScalar->append(" "); mScalar->appendScalar(x); return mScalar; } SkString* SkObjectParser::TextToString(const void* text, size_t byteLength) { SkString* mText = new SkString(6+byteLength+1); mText->append("Text: "); mText->append((char*) text, byteLength); return mText; } <commit_msg>Make Debugger print out more information (mainly w.r.t. SkBitmap)<commit_after> /* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkObjectParser.h" /* TODO(chudy): Replace all std::strings with char */ SkString* SkObjectParser::BitmapToString(const SkBitmap& bitmap) { SkString* mBitmap = new SkString("SkBitmap: "); mBitmap->append("W: "); mBitmap->appendS32(bitmap.width()); mBitmap->append(" H: "); mBitmap->appendS32(bitmap.height()); const char* gConfigStrings[] = { "None", "A1", "A8", "Index8", "RGB565", "ARGB4444", "ARGB8888", "RLE8" }; SkASSERT(SkBitmap::kConfigCount == 8); mBitmap->append(" Config: "); mBitmap->append(gConfigStrings[bitmap.getConfig()]); if (bitmap.isOpaque()) { mBitmap->append(" opaque"); } else { mBitmap->append(" not-opaque"); } if (bitmap.isImmutable()) { mBitmap->append(" immutable"); } else { mBitmap->append(" not-immutable"); } if (bitmap.isVolatile()) { mBitmap->append(" volatile"); } else { mBitmap->append(" not-volatile"); } mBitmap->append(" genID: "); mBitmap->appendS32(bitmap.getGenerationID()); return mBitmap; } SkString* SkObjectParser::BoolToString(bool doAA) { SkString* mBool = new SkString("Bool doAA: "); if (doAA) { mBool->append("True"); } else { mBool->append("False"); } return mBool; } SkString* SkObjectParser::CustomTextToString(const char* text) { SkString* mText = new SkString(text); return mText; } SkString* SkObjectParser::IntToString(int x, const char* text) { SkString* mInt = new SkString(text); mInt->append(" "); mInt->appendScalar(SkIntToScalar(x)); return mInt; } SkString* SkObjectParser::IRectToString(const SkIRect& rect) { SkString* mRect = new SkString("SkIRect: "); mRect->append("L: "); mRect->appendS32(rect.left()); mRect->append(", T: "); mRect->appendS32(rect.top()); mRect->append(", R: "); mRect->appendS32(rect.right()); mRect->append(", B: "); mRect->appendS32(rect.bottom()); return mRect; } SkString* SkObjectParser::MatrixToString(const SkMatrix& matrix) { SkString* mMatrix = new SkString("SkMatrix: ("); for (int i = 0; i < 8; i++) { mMatrix->appendScalar(matrix.get(i)); mMatrix->append("), ("); } mMatrix->appendScalar(matrix.get(8)); mMatrix->append(")"); return mMatrix; } SkString* SkObjectParser::PaintToString(const SkPaint& paint) { SkColor color = paint.getColor(); SkString* mPaint = new SkString("SkPaint: Color: 0x"); mPaint->appendHex(color); return mPaint; } SkString* SkObjectParser::PathToString(const SkPath& path) { SkString* mPath = new SkString("Path ("); static const char* gConvexityStrings[] = { "Unknown", "Convex", "Concave" }; SkASSERT(SkPath::kConcave_Convexity == 2); mPath->append(gConvexityStrings[path.getConvexity()]); mPath->append(", "); if (path.isRect(NULL)) { mPath->append("isRect, "); } else { mPath->append("isNotRect, "); } mPath->appendS32(path.countVerbs()); mPath->append("V, "); mPath->appendS32(path.countPoints()); mPath->append("P): "); static const char* gVerbStrings[] = { "Move", "Line", "Quad", "Cubic", "Close", "Done" }; static const int gPtsPerVerb[] = { 1, 1, 2, 3, 0, 0 }; static const int gPtOffsetPerVerb[] = { 0, 1, 1, 1, 0, 0 }; SkASSERT(SkPath::kDone_Verb == 5); SkPath::Iter iter(const_cast<SkPath&>(path), false); SkPath::Verb verb; SkPoint points[4]; for(verb = iter.next(points, false); verb != SkPath::kDone_Verb; verb = iter.next(points, false)) { mPath->append(gVerbStrings[verb]); mPath->append(" "); for (int i = 0; i < gPtsPerVerb[verb]; ++i) { mPath->append("("); mPath->appendScalar(points[gPtOffsetPerVerb[verb]+i].fX); mPath->append(", "); mPath->appendScalar(points[gPtOffsetPerVerb[verb]+i].fY); mPath->append(") "); } } return mPath; } SkString* SkObjectParser::PointsToString(const SkPoint pts[], size_t count) { SkString* mPoints = new SkString("SkPoints pts[]: "); for (unsigned int i = 0; i < count; i++) { mPoints->append("("); mPoints->appendScalar(pts[i].fX); mPoints->append(","); mPoints->appendScalar(pts[i].fY); mPoints->append(")"); } return mPoints; } SkString* SkObjectParser::PointModeToString(SkCanvas::PointMode mode) { SkString* mMode = new SkString("SkCanvas::PointMode: "); if (mode == SkCanvas::kPoints_PointMode) { mMode->append("kPoints_PointMode"); } else if (mode == SkCanvas::kLines_PointMode) { mMode->append("kLines_Mode"); } else if (mode == SkCanvas::kPolygon_PointMode) { mMode->append("kPolygon_PointMode"); } return mMode; } SkString* SkObjectParser::RectToString(const SkRect& rect) { SkString* mRect = new SkString("SkRect: "); mRect->append("("); mRect->appendScalar(rect.left()); mRect->append(", "); mRect->appendScalar(rect.top()); mRect->append(", "); mRect->appendScalar(rect.right()); mRect->append(", "); mRect->appendScalar(rect.bottom()); mRect->append(")"); return mRect; } SkString* SkObjectParser::RegionOpToString(SkRegion::Op op) { SkString* mOp = new SkString("SkRegion::Op: "); if (op == SkRegion::kDifference_Op) { mOp->append("kDifference_Op"); } else if (op == SkRegion::kIntersect_Op) { mOp->append("kIntersect_Op"); } else if (op == SkRegion::kUnion_Op) { mOp->append("kUnion_Op"); } else if (op == SkRegion::kXOR_Op) { mOp->append("kXOR_Op"); } else if (op == SkRegion::kReverseDifference_Op) { mOp->append("kReverseDifference_Op"); } else if (op == SkRegion::kReplace_Op) { mOp->append("kReplace_Op"); } else { mOp->append("Unknown Type"); } return mOp; } SkString* SkObjectParser::RegionToString(const SkRegion& region) { SkString* mRegion = new SkString("SkRegion: Data unavailable."); return mRegion; } SkString* SkObjectParser::SaveFlagsToString(SkCanvas::SaveFlags flags) { SkString* mFlags = new SkString("SkCanvas::SaveFlags: "); if(flags == SkCanvas::kMatrixClip_SaveFlag) { mFlags->append("kMatrixClip_SaveFlag"); } else if (flags == SkCanvas::kClip_SaveFlag) { mFlags->append("kClip_SaveFlag"); } else if (flags == SkCanvas::kHasAlphaLayer_SaveFlag) { mFlags->append("kHasAlphaLayer_SaveFlag"); } else if (flags == SkCanvas::kFullColorLayer_SaveFlag) { mFlags->append("kFullColorLayer_SaveFlag"); } else if (flags == SkCanvas::kClipToLayer_SaveFlag) { mFlags->append("kClipToLayer_SaveFlag"); } else if (flags == SkCanvas::kMatrixClip_SaveFlag) { mFlags->append("kMatrixClip_SaveFlag"); } else if (flags == SkCanvas::kARGB_NoClipLayer_SaveFlag) { mFlags->append("kARGB_NoClipLayer_SaveFlag"); } else if (flags == SkCanvas::kARGB_ClipLayer_SaveFlag) { mFlags->append("kARGB_ClipLayer_SaveFlag"); } else { mFlags->append("Data Unavailable"); } return mFlags; } SkString* SkObjectParser::ScalarToString(SkScalar x, const char* text) { SkString* mScalar = new SkString(text); mScalar->append(" "); mScalar->appendScalar(x); return mScalar; } SkString* SkObjectParser::TextToString(const void* text, size_t byteLength) { SkString* mText = new SkString(6+byteLength+1); mText->append("Text: "); mText->append((char*) text, byteLength); return mText; } <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * (C) 2019 Eddie Hung <eddie@fpgeh.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 "kernel/yosys.h" #include "kernel/sigtools.h" #include "kernel/timinginfo.h" #include <deque> USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct StaWorker { Design *design; Module *module; SigMap sigmap; struct t_data { Cell* driver; IdString dst_port, src_port; vector<tuple<SigBit,int,IdString>> fanouts; SigBit backtrack; t_data() : driver(nullptr) {} }; dict<SigBit, t_data> data; std::deque<SigBit> queue; struct t_endpoint { Cell *sink; IdString port; int required; t_endpoint() : sink(nullptr), required(0) {} }; dict<SigBit, t_endpoint> endpoints; int maxarrival; SigBit maxbit; pool<SigBit> driven; StaWorker(RTLIL::Module *module) : design(module->design), module(module), sigmap(module), maxarrival(0) { TimingInfo timing; for (auto cell : module->cells()) { Module *inst_module = design->module(cell->type); if (!inst_module) { log_warning("Cell type '%s' not recognised! Ignoring.\n", log_id(cell->type)); continue; } if (!inst_module->get_blackbox_attribute()) { log_warning("Cell type '%s' is not a black- nor white-box! Ignoring.\n", log_id(cell->type)); continue; } IdString derived_type = inst_module->derive(design, cell->parameters); inst_module = design->module(derived_type); log_assert(inst_module); if (!timing.count(derived_type)) { auto &t = timing.setup_module(inst_module); if (t.has_inputs && t.comb.empty() && t.arrival.empty() && t.required.empty()) log_warning("Module '%s' has no timing arcs!\n", log_id(cell->type)); } auto &t = timing.at(derived_type); if (t.comb.empty() && t.arrival.empty() && t.required.empty()) continue; pool<std::pair<SigBit,TimingInfo::NameBit>> src_bits, dst_bits; for (auto &conn : cell->connections()) { auto rhs = sigmap(conn.second); for (auto i = 0; i < GetSize(rhs); i++) { const auto &bit = rhs[i]; if (!bit.wire) continue; TimingInfo::NameBit namebit(conn.first,i); if (cell->input(conn.first)) { src_bits.insert(std::make_pair(bit,namebit)); auto it = t.required.find(namebit); if (it == t.required.end()) continue; auto r = endpoints.insert(bit); if (r.second || r.first->second.required < it->second.first) { r.first->second.sink = cell; r.first->second.port = conn.first; r.first->second.required = it->second.first; } } if (cell->output(conn.first)) { dst_bits.insert(std::make_pair(bit,namebit)); auto &d = data[bit]; d.driver = cell; d.dst_port = conn.first; driven.insert(bit); auto it = t.arrival.find(namebit); if (it == t.arrival.end()) continue; const auto &s = it->second.second; if (cell->hasPort(s.name)) { auto s_bit = sigmap(cell->getPort(s.name)[s.offset]); if (s_bit.wire) data[s_bit].fanouts.emplace_back(bit,it->second.first,s.name); } } } } for (const auto &s : src_bits) for (const auto &d : dst_bits) { auto it = t.comb.find(TimingInfo::BitBit(s.second,d.second)); if (it == t.comb.end()) continue; data[s.first].fanouts.emplace_back(d.first,it->second,s.second.name); } } for (auto port_name : module->ports) { auto wire = module->wire(port_name); if (wire->port_input) { for (const auto &b : sigmap(wire)) { queue.emplace_back(b); driven.insert(b); } // All primary inputs to arrive at time zero wire->set_intvec_attribute(ID::sta_arrival, std::vector<int>(GetSize(wire), 0)); } if (wire->port_output) for (const auto &b : sigmap(wire)) if (b.wire) endpoints.insert(b); } } void run() { while (!queue.empty()) { auto b = queue.front(); queue.pop_front(); auto it = data.find(b); if (it == data.end()) continue; const auto& src_arrivals = b.wire->get_intvec_attribute(ID::sta_arrival); log_assert(GetSize(src_arrivals) == GetSize(b.wire)); auto src_arrival = src_arrivals[b.offset]; for (const auto &d : it->second.fanouts) { const auto &dst_bit = std::get<0>(d); auto dst_arrivals = dst_bit.wire->get_intvec_attribute(ID::sta_arrival); if (dst_arrivals.empty()) dst_arrivals = std::vector<int>(GetSize(dst_bit.wire), -1); else log_assert(GetSize(dst_arrivals) == GetSize(dst_bit.wire)); auto &dst_arrival = dst_arrivals[dst_bit.offset]; auto new_arrival = src_arrival + std::get<1>(d); if (dst_arrival < new_arrival) { auto dst_wire = dst_bit.wire; dst_arrival = std::max(dst_arrival, new_arrival); dst_wire->set_intvec_attribute(ID::sta_arrival, dst_arrivals); queue.emplace_back(dst_bit); data[dst_bit].backtrack = b; data[dst_bit].src_port = std::get<2>(d); auto it = endpoints.find(dst_bit); if (it != endpoints.end()) new_arrival += it->second.required; if (new_arrival > maxarrival && driven.count(b)) { maxarrival = new_arrival; maxbit = dst_bit; } } } } auto b = maxbit; if (b == SigBit()) { log("No timing paths found.\n"); return; } log("Latest arrival time in '%s' is %d:\n", log_id(module), maxarrival); auto it = endpoints.find(maxbit); if (it != endpoints.end() && it->second.sink) log(" %6d %s (%s.%s)\n", maxarrival, log_id(it->second.sink), log_id(it->second.sink->type), log_id(it->second.port)); else { log(" %6d (%s)\n", maxarrival, b.wire->port_output ? "<primary output>" : "<unknown>"); if (!b.wire->port_output) log_warning("Critical-path does not terminate in a recognised endpoint.\n"); } auto jt = data.find(b); while (jt != data.end()) { int arrival = b.wire->get_intvec_attribute(ID::sta_arrival)[b.offset]; if (jt->second.driver) { log(" %s\n", log_signal(b)); log(" %6d %s (%s.%s->%s)\n", arrival, log_id(jt->second.driver), log_id(jt->second.driver->type), log_id(jt->second.src_port), log_id(jt->second.dst_port)); } else if (b.wire->port_input) log(" %6d %s (%s)\n", arrival, log_signal(b), "<primary input>"); else log_abort(); b = jt->second.backtrack; jt = data.find(b); } std::map<int, unsigned> arrival_histogram; for (const auto &i : endpoints) { const auto &b = i.first; if (!driven.count(b)) continue; if (!b.wire->attributes.count(ID::sta_arrival)) { log_warning("Endpoint %s.%s has no (* sta_arrival *) value.\n", log_id(module), log_signal(b)); continue; } auto arrival = b.wire->get_intvec_attribute(ID::sta_arrival)[b.offset]; if (arrival < 0) { log_warning("Endpoint %s.%s has no (* sta_arrival *) value.\n", log_id(module), log_signal(b)); continue; } arrival += i.second.required; arrival_histogram[arrival]++; } // Adapted from https://github.com/YosysHQ/nextpnr/blob/affb12cc27ebf409eade062c4c59bb98569d8147/common/timing.cc#L946-L969 if (arrival_histogram.size() > 0) { unsigned num_bins = 20; unsigned bar_width = 60; auto min_arrival = arrival_histogram.begin()->first; auto max_arrival = arrival_histogram.rbegin()->first; auto bin_size = std::max<unsigned>(1, ceil((max_arrival - min_arrival + 1) / float(num_bins))); std::vector<unsigned> bins(num_bins); unsigned max_freq = 0; for (const auto &i : arrival_histogram) { auto &bin = bins[(i.first - min_arrival) / bin_size]; bin += i.second; max_freq = std::max(max_freq, bin); } bar_width = std::min(bar_width, max_freq); log("\n"); log("Arrival histogram:\n"); log(" legend: * represents %d endpoint(s)\n", max_freq / bar_width); log(" + represents [1,%d) endpoint(s)\n", max_freq / bar_width); for (int i = num_bins-1; i >= 0; --i) log("(%6d, %6d] |%s%c\n", min_arrival + bin_size * (i + 1), min_arrival + bin_size * i, std::string(bins[i] * bar_width / max_freq, '*').c_str(), (bins[i] * bar_width) % max_freq > 0 ? '+' : ' '); } } }; struct StaPass : public Pass { StaPass() : Pass("sta", "perform static timing analysis") { } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" sta [options] [selection]\n"); log("\n"); log("This command performs static timing analysis on the design. (Only considers\n"); log("paths within a single module, so the design must be flattened.)\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) override { log_header(design, "Executing STA pass (static timing analysis).\n"); /* size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-TODO") { continue; } break; } */ extra_args(args, 1, design); for (Module *module : design->selected_modules()) { if (module->has_processes_warn()) continue; StaWorker worker(module); worker.run(); } } } StaPass; PRIVATE_NAMESPACE_END <commit_msg>sta: warn on unrecognised cells only once<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * (C) 2019 Eddie Hung <eddie@fpgeh.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 "kernel/yosys.h" #include "kernel/sigtools.h" #include "kernel/timinginfo.h" #include <deque> USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN struct StaWorker { Design *design; Module *module; SigMap sigmap; struct t_data { Cell* driver; IdString dst_port, src_port; vector<tuple<SigBit,int,IdString>> fanouts; SigBit backtrack; t_data() : driver(nullptr) {} }; dict<SigBit, t_data> data; std::deque<SigBit> queue; struct t_endpoint { Cell *sink; IdString port; int required; t_endpoint() : sink(nullptr), required(0) {} }; dict<SigBit, t_endpoint> endpoints; int maxarrival; SigBit maxbit; pool<SigBit> driven; StaWorker(RTLIL::Module *module) : design(module->design), module(module), sigmap(module), maxarrival(0) { TimingInfo timing; pool<IdString> unrecognised_cells; for (auto cell : module->cells()) { Module *inst_module = design->module(cell->type); if (!inst_module) { if (unrecognised_cells.insert(cell->type).second) log_warning("Cell type '%s' not recognised! Ignoring.\n", log_id(cell->type)); continue; } if (!inst_module->get_blackbox_attribute()) { log_warning("Cell type '%s' is not a black- nor white-box! Ignoring.\n", log_id(cell->type)); continue; } IdString derived_type = inst_module->derive(design, cell->parameters); inst_module = design->module(derived_type); log_assert(inst_module); if (!timing.count(derived_type)) { auto &t = timing.setup_module(inst_module); if (t.has_inputs && t.comb.empty() && t.arrival.empty() && t.required.empty()) log_warning("Module '%s' has no timing arcs!\n", log_id(cell->type)); } auto &t = timing.at(derived_type); if (t.comb.empty() && t.arrival.empty() && t.required.empty()) continue; pool<std::pair<SigBit,TimingInfo::NameBit>> src_bits, dst_bits; for (auto &conn : cell->connections()) { auto rhs = sigmap(conn.second); for (auto i = 0; i < GetSize(rhs); i++) { const auto &bit = rhs[i]; if (!bit.wire) continue; TimingInfo::NameBit namebit(conn.first,i); if (cell->input(conn.first)) { src_bits.insert(std::make_pair(bit,namebit)); auto it = t.required.find(namebit); if (it == t.required.end()) continue; auto r = endpoints.insert(bit); if (r.second || r.first->second.required < it->second.first) { r.first->second.sink = cell; r.first->second.port = conn.first; r.first->second.required = it->second.first; } } if (cell->output(conn.first)) { dst_bits.insert(std::make_pair(bit,namebit)); auto &d = data[bit]; d.driver = cell; d.dst_port = conn.first; driven.insert(bit); auto it = t.arrival.find(namebit); if (it == t.arrival.end()) continue; const auto &s = it->second.second; if (cell->hasPort(s.name)) { auto s_bit = sigmap(cell->getPort(s.name)[s.offset]); if (s_bit.wire) data[s_bit].fanouts.emplace_back(bit,it->second.first,s.name); } } } } for (const auto &s : src_bits) for (const auto &d : dst_bits) { auto it = t.comb.find(TimingInfo::BitBit(s.second,d.second)); if (it == t.comb.end()) continue; data[s.first].fanouts.emplace_back(d.first,it->second,s.second.name); } } for (auto port_name : module->ports) { auto wire = module->wire(port_name); if (wire->port_input) { for (const auto &b : sigmap(wire)) { queue.emplace_back(b); driven.insert(b); } // All primary inputs to arrive at time zero wire->set_intvec_attribute(ID::sta_arrival, std::vector<int>(GetSize(wire), 0)); } if (wire->port_output) for (const auto &b : sigmap(wire)) if (b.wire) endpoints.insert(b); } } void run() { while (!queue.empty()) { auto b = queue.front(); queue.pop_front(); auto it = data.find(b); if (it == data.end()) continue; const auto& src_arrivals = b.wire->get_intvec_attribute(ID::sta_arrival); log_assert(GetSize(src_arrivals) == GetSize(b.wire)); auto src_arrival = src_arrivals[b.offset]; for (const auto &d : it->second.fanouts) { const auto &dst_bit = std::get<0>(d); auto dst_arrivals = dst_bit.wire->get_intvec_attribute(ID::sta_arrival); if (dst_arrivals.empty()) dst_arrivals = std::vector<int>(GetSize(dst_bit.wire), -1); else log_assert(GetSize(dst_arrivals) == GetSize(dst_bit.wire)); auto &dst_arrival = dst_arrivals[dst_bit.offset]; auto new_arrival = src_arrival + std::get<1>(d); if (dst_arrival < new_arrival) { auto dst_wire = dst_bit.wire; dst_arrival = std::max(dst_arrival, new_arrival); dst_wire->set_intvec_attribute(ID::sta_arrival, dst_arrivals); queue.emplace_back(dst_bit); data[dst_bit].backtrack = b; data[dst_bit].src_port = std::get<2>(d); auto it = endpoints.find(dst_bit); if (it != endpoints.end()) new_arrival += it->second.required; if (new_arrival > maxarrival && driven.count(b)) { maxarrival = new_arrival; maxbit = dst_bit; } } } } auto b = maxbit; if (b == SigBit()) { log("No timing paths found.\n"); return; } log("Latest arrival time in '%s' is %d:\n", log_id(module), maxarrival); auto it = endpoints.find(maxbit); if (it != endpoints.end() && it->second.sink) log(" %6d %s (%s.%s)\n", maxarrival, log_id(it->second.sink), log_id(it->second.sink->type), log_id(it->second.port)); else { log(" %6d (%s)\n", maxarrival, b.wire->port_output ? "<primary output>" : "<unknown>"); if (!b.wire->port_output) log_warning("Critical-path does not terminate in a recognised endpoint.\n"); } auto jt = data.find(b); while (jt != data.end()) { int arrival = b.wire->get_intvec_attribute(ID::sta_arrival)[b.offset]; if (jt->second.driver) { log(" %s\n", log_signal(b)); log(" %6d %s (%s.%s->%s)\n", arrival, log_id(jt->second.driver), log_id(jt->second.driver->type), log_id(jt->second.src_port), log_id(jt->second.dst_port)); } else if (b.wire->port_input) log(" %6d %s (%s)\n", arrival, log_signal(b), "<primary input>"); else log_abort(); b = jt->second.backtrack; jt = data.find(b); } std::map<int, unsigned> arrival_histogram; for (const auto &i : endpoints) { const auto &b = i.first; if (!driven.count(b)) continue; if (!b.wire->attributes.count(ID::sta_arrival)) { log_warning("Endpoint %s.%s has no (* sta_arrival *) value.\n", log_id(module), log_signal(b)); continue; } auto arrival = b.wire->get_intvec_attribute(ID::sta_arrival)[b.offset]; if (arrival < 0) { log_warning("Endpoint %s.%s has no (* sta_arrival *) value.\n", log_id(module), log_signal(b)); continue; } arrival += i.second.required; arrival_histogram[arrival]++; } // Adapted from https://github.com/YosysHQ/nextpnr/blob/affb12cc27ebf409eade062c4c59bb98569d8147/common/timing.cc#L946-L969 if (arrival_histogram.size() > 0) { unsigned num_bins = 20; unsigned bar_width = 60; auto min_arrival = arrival_histogram.begin()->first; auto max_arrival = arrival_histogram.rbegin()->first; auto bin_size = std::max<unsigned>(1, ceil((max_arrival - min_arrival + 1) / float(num_bins))); std::vector<unsigned> bins(num_bins); unsigned max_freq = 0; for (const auto &i : arrival_histogram) { auto &bin = bins[(i.first - min_arrival) / bin_size]; bin += i.second; max_freq = std::max(max_freq, bin); } bar_width = std::min(bar_width, max_freq); log("\n"); log("Arrival histogram:\n"); log(" legend: * represents %d endpoint(s)\n", max_freq / bar_width); log(" + represents [1,%d) endpoint(s)\n", max_freq / bar_width); for (int i = num_bins-1; i >= 0; --i) log("(%6d, %6d] |%s%c\n", min_arrival + bin_size * (i + 1), min_arrival + bin_size * i, std::string(bins[i] * bar_width / max_freq, '*').c_str(), (bins[i] * bar_width) % max_freq > 0 ? '+' : ' '); } } }; struct StaPass : public Pass { StaPass() : Pass("sta", "perform static timing analysis") { } void help() override { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" sta [options] [selection]\n"); log("\n"); log("This command performs static timing analysis on the design. (Only considers\n"); log("paths within a single module, so the design must be flattened.)\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design *design) override { log_header(design, "Executing STA pass (static timing analysis).\n"); /* size_t argidx; for (argidx = 1; argidx < args.size(); argidx++) { if (args[argidx] == "-TODO") { continue; } break; } */ extra_args(args, 1, design); for (Module *module : design->selected_modules()) { if (module->has_processes_warn()) continue; StaWorker worker(module); worker.run(); } } } StaPass; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2013-2015 Imperial College London * Copyright 2013-2015 Andreas Schuh * * 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 "mirtk/NiftiImageInfo.h" // ============================================================================= // Enumerations -- **BEFORE** including nifti2_io.h which defines macros!!! // ============================================================================= namespace mirtk { // ----------------------------------------------------------------------------- template <> bool FromString(const char *str, NiftiIntent &value) { string lstr = Trim(ToLower(str)); if (lstr.rfind(" distribution") == lstr.length() - 13) { lstr = lstr.substr(0, lstr.length() - 13); } else if (lstr.rfind(" statistic") == lstr.length() - 10) { lstr = lstr.substr(0, lstr.length() - 10); } if (lstr == "unknown" || lstr == "none") value = NIFTI_INTENT_NONE; else if (lstr == "correlation") value = NIFTI_INTENT_CORREL; else if (lstr == "t-statistic" || lstr == "t-test") value = NIFTI_INTENT_TTEST; else if (lstr == "f-statistic" || lstr == "f-test") value = NIFTI_INTENT_FTEST; else if (lstr == "z-score") value = NIFTI_INTENT_ZSCORE; else if (lstr == "f-statistic noncentral") value = NIFTI_INTENT_FTEST_NONC; else if (lstr == "chi-squared noncentral") value = NIFTI_INTENT_CHISQ_NONC; else if (lstr == "t-statistic noncentral") value = NIFTI_INTENT_TTEST_NONC; else if (lstr == "chi-squared") value = NIFTI_INTENT_CHISQ; else if (lstr == "beta") value = NIFTI_INTENT_BETA; else if (lstr == "gamma") value = NIFTI_INTENT_GAMMA; else if (lstr == "poisson") value = NIFTI_INTENT_POISSON; else if (lstr == "normal") value = NIFTI_INTENT_NORMAL; else if (lstr == "logistic") value = NIFTI_INTENT_LOGISTIC; else if (lstr == "laplace") value = NIFTI_INTENT_LAPLACE; else if (lstr == "uniform") value = NIFTI_INTENT_UNIFORM; else if (lstr == "weibull") value = NIFTI_INTENT_WEIBULL; else if (lstr == "chi") value = NIFTI_INTENT_CHI; else if (lstr == "inverse gaussian") value = NIFTI_INTENT_INVGAUSS; else if (lstr == "extreme value") value = NIFTI_INTENT_EXTVAL; else if (lstr == "p-value") value = NIFTI_INTENT_PVAL; else if (lstr == "log p-value") value = NIFTI_INTENT_LOGPVAL; else if (lstr == "log10 p-value") value = NIFTI_INTENT_LOG10PVAL; else if (lstr == "estimate") value = NIFTI_INTENT_ESTIMATE; else if (lstr == "label index" || lstr == "label") value = NIFTI_INTENT_LABEL; else if (lstr == "neuronames index" || lstr == "neuroname") value = NIFTI_INTENT_NEURONAME; else if (lstr == "general matrix") value = NIFTI_INTENT_GENMATRIX; else if (lstr == "symmetric matrix") value = NIFTI_INTENT_SYMMATRIX; else if (lstr == "displacement vector") value = NIFTI_INTENT_DISPVECT; else if (lstr == "vector") value = NIFTI_INTENT_VECTOR; else if (lstr == "pointset") value = NIFTI_INTENT_POINTSET; else if (lstr == "triangle") value = NIFTI_INTENT_TRIANGLE; else if (lstr == "quaternion") value = NIFTI_INTENT_QUATERNION; else if (lstr == "time series") value = NIFTI_INTENT_TIME_SERIES; else if (lstr == "node index") value = NIFTI_INTENT_NODE_INDEX; else if (lstr == "shape") value = NIFTI_INTENT_SHAPE; else if (lstr == "rgb") value = NIFTI_INTENT_RGB_VECTOR; else if (lstr == "rgba") value = NIFTI_INTENT_RGBA_VECTOR; else if (lstr == "dimensionless number" || lstr == "dimensionless") { value = NIFTI_INTENT_DIMLESS; } else { return false; } return true; } // ----------------------------------------------------------------------------- template <> string ToString(const NiftiIntent &value, int w, char c, bool left) { const char *str = "Unknown"; switch (value) { case NIFTI_INTENT_NONE: str = "Unknown"; break; case NIFTI_INTENT_CORREL: str = "Correlation statistic"; break; case NIFTI_INTENT_TTEST: str = "T-statistic"; break; case NIFTI_INTENT_FTEST: str = "F-statistic"; break; case NIFTI_INTENT_ZSCORE: str = "Z-score"; break; case NIFTI_INTENT_CHISQ: str = "Chi-squared distribution"; break; case NIFTI_INTENT_BETA: str = "Beta distribution"; break; case NIFTI_INTENT_BINOM: str = "Binomial distribution"; break; case NIFTI_INTENT_GAMMA: str = "Gamma distribution"; break; case NIFTI_INTENT_POISSON: str = "Poisson distribution"; break; case NIFTI_INTENT_NORMAL: str = "Normal distribution"; break; case NIFTI_INTENT_FTEST_NONC: str = "F-statistic noncentral"; break; case NIFTI_INTENT_CHISQ_NONC: str = "Chi-squared noncentral"; break; case NIFTI_INTENT_LOGISTIC: str = "Logistic distribution"; break; case NIFTI_INTENT_LAPLACE: str = "Laplace distribution"; break; case NIFTI_INTENT_UNIFORM: str = "Uniform distribution"; break; case NIFTI_INTENT_TTEST_NONC: str = "T-statistic noncentral"; break; case NIFTI_INTENT_WEIBULL: str = "Weibull distribution"; break; case NIFTI_INTENT_CHI: str = "Chi distribution"; break; case NIFTI_INTENT_INVGAUSS: str = "Inverse Gaussian distribution"; break; case NIFTI_INTENT_EXTVAL: str = "Extreme Value distribution"; break; case NIFTI_INTENT_PVAL: str = "P-value"; break; case NIFTI_INTENT_LOGPVAL: str = "Log P-value"; break; case NIFTI_INTENT_LOG10PVAL: str = "Log10 P-value"; break; case NIFTI_INTENT_ESTIMATE: str = "Estimate"; break; case NIFTI_INTENT_LABEL: str = "Label index"; break; case NIFTI_INTENT_NEURONAME: str = "NeuroNames index"; break; case NIFTI_INTENT_GENMATRIX: str = "General matrix"; break; case NIFTI_INTENT_SYMMATRIX: str = "Symmetric matrix"; break; case NIFTI_INTENT_DISPVECT: str = "Displacement vector"; break; case NIFTI_INTENT_VECTOR: str = "Vector"; break; case NIFTI_INTENT_POINTSET: str = "Pointset"; break; case NIFTI_INTENT_TRIANGLE: str = "Triangle"; break; case NIFTI_INTENT_QUATERNION: str = "Quaternion"; break; case NIFTI_INTENT_DIMLESS: str = "Dimensionless number"; break; case NIFTI_INTENT_TIME_SERIES: str = "Time series"; break; case NIFTI_INTENT_NODE_INDEX: str = "Node index"; break; case NIFTI_INTENT_SHAPE: str = "Shape"; break; case NIFTI_INTENT_RGB_VECTOR: str = "RGB"; break; case NIFTI_INTENT_RGBA_VECTOR: str = "RGBA"; break; } return ToString(str, w, c, left); } // ----------------------------------------------------------------------------- bool FromString(const char *str, NiftiUnits &units) { const string lstr = Trim(ToLower(str)); if (lstr == "m" || lstr == "meter" || lstr == ToString(int(NIFTI_UNITS_METER))) { units = NIFTI_UNITS_METER; } else if (lstr == "mm" || lstr == "millimeter" || lstr == ToString(int(NIFTI_UNITS_MM))) { units = NIFTI_UNITS_MM; } else if (lstr == "mu" || lstr == "micrometer" || lstr == "micron" || lstr == ToString(int(NIFTI_UNITS_MICRON))) { units = NIFTI_UNITS_MICRON; } else { return false; } return true; } } // namespace mirtk // ============================================================================= // Include NIfTI I/O library header // ============================================================================= #include "nifti/nifti2_io.h" namespace mirtk { // ============================================================================= // Auxiliaries // ============================================================================= // ----------------------------------------------------------------------------- static inline Matrix ToMatrix(const nifti_dmat44 &mat) { Matrix m; for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) { m(i, j) = mat.m[i][j]; } return m; } // ----------------------------------------------------------------------------- inline NiftiImageInfo ToNiftiImageInfo(const nifti_image *nim) { NiftiImageInfo info; info.ndim = static_cast<int>(nim->ndim); info.nx = static_cast<int>(nim->nx); info.ny = static_cast<int>(nim->ny); info.nz = static_cast<int>(nim->nz); info.nt = static_cast<int>(nim->nt); info.nu = static_cast<int>(nim->nu); info.nv = static_cast<int>(nim->nv); info.nw = static_cast<int>(nim->nw); info.nvox = static_cast<int>(nim->nvox); info.nbyper = nim->nbyper; info.datatype = nim->datatype; info.dx = nim->dx; info.dy = nim->dy; info.dz = nim->dz; info.dt = nim->dt; info.du = nim->du; info.dv = nim->dv; info.dw = nim->dw; info.scl_slope = nim->scl_slope; info.scl_inter = nim->scl_inter; info.cal_min = nim->cal_min; info.cal_max = nim->cal_max; info.slice_code = nim->slice_code; info.slice_start = static_cast<int>(nim->slice_start); info.slice_end = static_cast<int>(nim->slice_end); info.slice_duration = nim->slice_duration; info.qform_code = nim->qform_code; info.qto_xyz = ToMatrix(nim->qto_xyz); info.qto_ijk = ToMatrix(nim->qto_ijk); info.sform_code = nim->sform_code; info.sto_xyz = ToMatrix(nim->sto_xyz); info.sto_ijk = ToMatrix(nim->sto_ijk); info.toffset = nim->toffset; info.xyz_units = nim->xyz_units; info.time_units = nim->time_units; info.nifti_type = nim->nifti_type; info.intent_code = nim->intent_code; info.intent_p1 = nim->intent_p1; info.intent_p2 = nim->intent_p2; info.intent_p3 = nim->intent_p3; info.intent_name = nim->intent_name; info.descrip = nim->descrip; info.aux_file = nim->aux_file; info.fname = nim->fname; info.iname = nim->iname; info.iname_offset = static_cast<int>(nim->iname_offset); info.swapsize = nim->swapsize; info.byteorder = nim->byteorder; return info; } // ============================================================================= // Construction/Destruction // ============================================================================= // ----------------------------------------------------------------------------- NiftiImageInfo::NiftiImageInfo(const char *fname) { nifti_image *nim; if (fname) { const int read_data = 0; nim = nifti_image_read(fname, read_data); } else { nim = nifti_simple_init_nim(); } *this = ToNiftiImageInfo(nim); nifti_image_free(nim); } } // namespace mirtk <commit_msg>fix: NiftiImageInfo constructor [IO]<commit_after>/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2013-2017 Imperial College London * Copyright 2013-2017 Andreas Schuh * * 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 "mirtk/NiftiImageInfo.h" // ============================================================================= // Enumerations -- **BEFORE** including nifti2_io.h which defines macros!!! // ============================================================================= namespace mirtk { // ----------------------------------------------------------------------------- template <> bool FromString(const char *str, NiftiIntent &value) { string lstr = Trim(ToLower(str)); if (lstr.rfind(" distribution") == lstr.length() - 13) { lstr = lstr.substr(0, lstr.length() - 13); } else if (lstr.rfind(" statistic") == lstr.length() - 10) { lstr = lstr.substr(0, lstr.length() - 10); } if (lstr == "unknown" || lstr == "none") value = NIFTI_INTENT_NONE; else if (lstr == "correlation") value = NIFTI_INTENT_CORREL; else if (lstr == "t-statistic" || lstr == "t-test") value = NIFTI_INTENT_TTEST; else if (lstr == "f-statistic" || lstr == "f-test") value = NIFTI_INTENT_FTEST; else if (lstr == "z-score") value = NIFTI_INTENT_ZSCORE; else if (lstr == "f-statistic noncentral") value = NIFTI_INTENT_FTEST_NONC; else if (lstr == "chi-squared noncentral") value = NIFTI_INTENT_CHISQ_NONC; else if (lstr == "t-statistic noncentral") value = NIFTI_INTENT_TTEST_NONC; else if (lstr == "chi-squared") value = NIFTI_INTENT_CHISQ; else if (lstr == "beta") value = NIFTI_INTENT_BETA; else if (lstr == "gamma") value = NIFTI_INTENT_GAMMA; else if (lstr == "poisson") value = NIFTI_INTENT_POISSON; else if (lstr == "normal") value = NIFTI_INTENT_NORMAL; else if (lstr == "logistic") value = NIFTI_INTENT_LOGISTIC; else if (lstr == "laplace") value = NIFTI_INTENT_LAPLACE; else if (lstr == "uniform") value = NIFTI_INTENT_UNIFORM; else if (lstr == "weibull") value = NIFTI_INTENT_WEIBULL; else if (lstr == "chi") value = NIFTI_INTENT_CHI; else if (lstr == "inverse gaussian") value = NIFTI_INTENT_INVGAUSS; else if (lstr == "extreme value") value = NIFTI_INTENT_EXTVAL; else if (lstr == "p-value") value = NIFTI_INTENT_PVAL; else if (lstr == "log p-value") value = NIFTI_INTENT_LOGPVAL; else if (lstr == "log10 p-value") value = NIFTI_INTENT_LOG10PVAL; else if (lstr == "estimate") value = NIFTI_INTENT_ESTIMATE; else if (lstr == "label index" || lstr == "label") value = NIFTI_INTENT_LABEL; else if (lstr == "neuronames index" || lstr == "neuroname") value = NIFTI_INTENT_NEURONAME; else if (lstr == "general matrix") value = NIFTI_INTENT_GENMATRIX; else if (lstr == "symmetric matrix") value = NIFTI_INTENT_SYMMATRIX; else if (lstr == "displacement vector") value = NIFTI_INTENT_DISPVECT; else if (lstr == "vector") value = NIFTI_INTENT_VECTOR; else if (lstr == "pointset") value = NIFTI_INTENT_POINTSET; else if (lstr == "triangle") value = NIFTI_INTENT_TRIANGLE; else if (lstr == "quaternion") value = NIFTI_INTENT_QUATERNION; else if (lstr == "time series") value = NIFTI_INTENT_TIME_SERIES; else if (lstr == "node index") value = NIFTI_INTENT_NODE_INDEX; else if (lstr == "shape") value = NIFTI_INTENT_SHAPE; else if (lstr == "rgb") value = NIFTI_INTENT_RGB_VECTOR; else if (lstr == "rgba") value = NIFTI_INTENT_RGBA_VECTOR; else if (lstr == "dimensionless number" || lstr == "dimensionless") { value = NIFTI_INTENT_DIMLESS; } else { return false; } return true; } // ----------------------------------------------------------------------------- template <> string ToString(const NiftiIntent &value, int w, char c, bool left) { const char *str = "Unknown"; switch (value) { case NIFTI_INTENT_NONE: str = "Unknown"; break; case NIFTI_INTENT_CORREL: str = "Correlation statistic"; break; case NIFTI_INTENT_TTEST: str = "T-statistic"; break; case NIFTI_INTENT_FTEST: str = "F-statistic"; break; case NIFTI_INTENT_ZSCORE: str = "Z-score"; break; case NIFTI_INTENT_CHISQ: str = "Chi-squared distribution"; break; case NIFTI_INTENT_BETA: str = "Beta distribution"; break; case NIFTI_INTENT_BINOM: str = "Binomial distribution"; break; case NIFTI_INTENT_GAMMA: str = "Gamma distribution"; break; case NIFTI_INTENT_POISSON: str = "Poisson distribution"; break; case NIFTI_INTENT_NORMAL: str = "Normal distribution"; break; case NIFTI_INTENT_FTEST_NONC: str = "F-statistic noncentral"; break; case NIFTI_INTENT_CHISQ_NONC: str = "Chi-squared noncentral"; break; case NIFTI_INTENT_LOGISTIC: str = "Logistic distribution"; break; case NIFTI_INTENT_LAPLACE: str = "Laplace distribution"; break; case NIFTI_INTENT_UNIFORM: str = "Uniform distribution"; break; case NIFTI_INTENT_TTEST_NONC: str = "T-statistic noncentral"; break; case NIFTI_INTENT_WEIBULL: str = "Weibull distribution"; break; case NIFTI_INTENT_CHI: str = "Chi distribution"; break; case NIFTI_INTENT_INVGAUSS: str = "Inverse Gaussian distribution"; break; case NIFTI_INTENT_EXTVAL: str = "Extreme Value distribution"; break; case NIFTI_INTENT_PVAL: str = "P-value"; break; case NIFTI_INTENT_LOGPVAL: str = "Log P-value"; break; case NIFTI_INTENT_LOG10PVAL: str = "Log10 P-value"; break; case NIFTI_INTENT_ESTIMATE: str = "Estimate"; break; case NIFTI_INTENT_LABEL: str = "Label index"; break; case NIFTI_INTENT_NEURONAME: str = "NeuroNames index"; break; case NIFTI_INTENT_GENMATRIX: str = "General matrix"; break; case NIFTI_INTENT_SYMMATRIX: str = "Symmetric matrix"; break; case NIFTI_INTENT_DISPVECT: str = "Displacement vector"; break; case NIFTI_INTENT_VECTOR: str = "Vector"; break; case NIFTI_INTENT_POINTSET: str = "Pointset"; break; case NIFTI_INTENT_TRIANGLE: str = "Triangle"; break; case NIFTI_INTENT_QUATERNION: str = "Quaternion"; break; case NIFTI_INTENT_DIMLESS: str = "Dimensionless number"; break; case NIFTI_INTENT_TIME_SERIES: str = "Time series"; break; case NIFTI_INTENT_NODE_INDEX: str = "Node index"; break; case NIFTI_INTENT_SHAPE: str = "Shape"; break; case NIFTI_INTENT_RGB_VECTOR: str = "RGB"; break; case NIFTI_INTENT_RGBA_VECTOR: str = "RGBA"; break; } return ToString(str, w, c, left); } // ----------------------------------------------------------------------------- bool FromString(const char *str, NiftiUnits &units) { const string lstr = Trim(ToLower(str)); if (lstr == "m" || lstr == "meter" || lstr == ToString(int(NIFTI_UNITS_METER))) { units = NIFTI_UNITS_METER; } else if (lstr == "mm" || lstr == "millimeter" || lstr == ToString(int(NIFTI_UNITS_MM))) { units = NIFTI_UNITS_MM; } else if (lstr == "mu" || lstr == "micrometer" || lstr == "micron" || lstr == ToString(int(NIFTI_UNITS_MICRON))) { units = NIFTI_UNITS_MICRON; } else { return false; } return true; } } // namespace mirtk // ============================================================================= // Include NIfTI I/O library header // ============================================================================= #include "nifti/nifti2_io.h" namespace mirtk { // ============================================================================= // Auxiliaries // ============================================================================= namespace { // ----------------------------------------------------------------------------- static inline Matrix ToMatrix(const nifti_dmat44 &mat) { Matrix m(4, 4); for (int i = 0; i < 4; ++i) for (int j = 0; j < 4; ++j) { m(i, j) = mat.m[i][j]; } return m; } } // namespace // ============================================================================= // Construction/Destruction // ============================================================================= // ----------------------------------------------------------------------------- NiftiImageInfo::NiftiImageInfo(const char *fname) { nifti_image *nim; if (fname) { const int read_data = 0; nim = nifti_image_read(fname, read_data); } else { nim = nifti_simple_init_nim(); } ndim = static_cast<int>(nim->ndim); nx = static_cast<int>(nim->nx); ny = static_cast<int>(nim->ny); nz = static_cast<int>(nim->nz); nt = static_cast<int>(nim->nt); nu = static_cast<int>(nim->nu); nv = static_cast<int>(nim->nv); nw = static_cast<int>(nim->nw); nvox = static_cast<int>(nim->nvox); nbyper = nim->nbyper; datatype = nim->datatype; dx = nim->dx; dy = nim->dy; dz = nim->dz; dt = nim->dt; du = nim->du; dv = nim->dv; dw = nim->dw; scl_slope = nim->scl_slope; scl_inter = nim->scl_inter; cal_min = nim->cal_min; cal_max = nim->cal_max; slice_code = nim->slice_code; slice_start = static_cast<int>(nim->slice_start); slice_end = static_cast<int>(nim->slice_end); slice_duration = nim->slice_duration; qform_code = nim->qform_code; qto_xyz = ToMatrix(nim->qto_xyz); qto_ijk = ToMatrix(nim->qto_ijk); sform_code = nim->sform_code; sto_xyz = ToMatrix(nim->sto_xyz); sto_ijk = ToMatrix(nim->sto_ijk); toffset = nim->toffset; xyz_units = nim->xyz_units; time_units = nim->time_units; nifti_type = nim->nifti_type; intent_code = nim->intent_code; intent_p1 = nim->intent_p1; intent_p2 = nim->intent_p2; intent_p3 = nim->intent_p3; intent_name = nim->intent_name; descrip = nim->descrip; aux_file = nim->aux_file; fname = nim->fname; iname = nim->iname; iname_offset = static_cast<int>(nim->iname_offset); swapsize = nim->swapsize; byteorder = nim->byteorder; nifti_image_free(nim); } } // namespace mirtk <|endoftext|>
<commit_before>/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2013-2016 Imperial College London * Copyright 2013-2016 Andreas Schuh * * 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 "mirtk/Triangle.h" #include "mirtk/Memory.h" #include "vtkLine.h" #include "vtkPlane.h" #include "vtkTriangle.h" namespace mirtk { // ============================================================================= // Triangle/triangle intersection test // ============================================================================= #include "triangle_triangle_intersection.h" // ----------------------------------------------------------------------------- bool Triangle ::TriangleTriangleIntersection(const double a1[3], const double b1[3], const double c1[3], const double a2[3], const double b2[3], const double c2[3]) { return tri_tri_overlap_test_3d(const_cast<double *>(a1), const_cast<double *>(b1), const_cast<double *>(c1), const_cast<double *>(a2), const_cast<double *>(b2), const_cast<double *>(c2)) != 0; } // ============================================================================= // Distance between two triangles // ============================================================================= // Copy 3D point coordinates stored in plain C array #define MIRTK_RETURN_POINT(a, b) if (a) memcpy((a), (b), 3 * sizeof(double)) // ----------------------------------------------------------------------------- // Scaled vector subtraction inline void VmsV(double *Vr, const double *V1, double s2, const double *V2) { Vr[0] = V1[0] - s2 * V2[0]; Vr[1] = V1[1] - s2 * V2[1]; Vr[2] = V1[2] - s2 * V2[2]; } // ----------------------------------------------------------------------------- inline double distance_between_triangles(double a1[3], double b1[3], double c1[3], double n1[3], double a2[3], double b2[3], double c2[3], double n2[3], double *p1, double *p2) { const double TOL = 1e-6; // Tolerance for point coordinate equality check double q1[3], q2[3], t1, t2, d, min = inf; // Point in second triangle closest to any of the corners of the first triangle t2 = vtkPlane::Evaluate(n2, a2, a1); d = abs(t2); if (d < min) { VmsV(q2, a1, t2, n2); if (vtkTriangle::PointInTriangle(q2, a2, b2, c2, TOL)) { MIRTK_RETURN_POINT(p1, a1); MIRTK_RETURN_POINT(p2, q2); min = d; } } t2 = vtkPlane::Evaluate(n2, a2, b1); d = abs(t2); if (d < min) { VmsV(q2, b1, t2, n2); if (vtkTriangle::PointInTriangle(q2, a2, b2, c2, TOL)) { MIRTK_RETURN_POINT(p1, b1); MIRTK_RETURN_POINT(p2, q2); min = d; } } t2 = vtkPlane::Evaluate(n2, a2, c1); d = abs(t2); if (d < min) { VmsV(q2, c1, t2, n2); if (vtkTriangle::PointInTriangle(q2, a2, b2, c2, TOL)) { MIRTK_RETURN_POINT(p1, c1); MIRTK_RETURN_POINT(p2, q2); min = d; } } // Point in first triangle closest to any of the corners of the second triangle t1 = vtkPlane::Evaluate(n1, a1, a2); d = abs(t1); if (d < min) { VmsV(q1, a2, t1, n1); if (vtkTriangle::PointInTriangle(q1, a1, b1, c1, TOL)) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, a2); min = d; } } t1 = vtkPlane::Evaluate(n1, a1, b2); d = abs(t1); if (d < min) { VmsV(q1, b2, t1, n1); if (vtkTriangle::PointInTriangle(q1, a1, b1, c1, TOL)) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, b2); min = d; } } t1 = vtkPlane::Evaluate(n1, a1, c2); d = abs(t1); if (d < min) { VmsV(q1, c2, t1, n1); if (vtkTriangle::PointInTriangle(q1, a1, b1, c1, TOL)) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, c2); min = d; } } // Distance between each pair of edges d = vtkLine::DistanceBetweenLineSegments(a1, b1, a2, b2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(a1, b1, b2, c2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(a1, b1, c2, a2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(b1, c1, a2, b2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(b1, c1, b2, c2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(b1, c1, c2, a2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(c1, a1, a2, b2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(c1, a1, b2, c2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(c1, a1, c2, a2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } return min; } // ----------------------------------------------------------------------------- double Triangle ::DistanceBetweenTriangles( const double a1[3], const double b1[3], const double c1[3], const double n1[3], const double a2[3], const double b2[3], const double c2[3], const double n2[3], double *p1, double *p2 ) { return distance_between_triangles(const_cast<double *>(a1), const_cast<double *>(b1), const_cast<double *>(c1), const_cast<double *>(n1), const_cast<double *>(a2), const_cast<double *>(b2), const_cast<double *>(c2), const_cast<double *>(n2), p1, p2); } } // namespace mirtk <commit_msg>fix: Temporary (slow) fix of triangle-triangle intersection test [PointSet] (#378)<commit_after>/* * Medical Image Registration ToolKit (MIRTK) * * Copyright 2013-2016 Imperial College London * Copyright 2013-2016 Andreas Schuh * * 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 "mirtk/Triangle.h" #include "mirtk/Memory.h" #include "vtkLine.h" #include "vtkPlane.h" #include "vtkTriangle.h" namespace mirtk { // ============================================================================= // Distance between two triangles // ============================================================================= // Copy 3D point coordinates stored in plain C array #define MIRTK_RETURN_POINT(a, b) if (a) memcpy((a), (b), 3 * sizeof(double)) // ----------------------------------------------------------------------------- // Scaled vector subtraction inline void VmsV(double *Vr, const double *V1, double s2, const double *V2) { Vr[0] = V1[0] - s2 * V2[0]; Vr[1] = V1[1] - s2 * V2[1]; Vr[2] = V1[2] - s2 * V2[2]; } // ----------------------------------------------------------------------------- inline double distance_between_triangles(double a1[3], double b1[3], double c1[3], double n1[3], double a2[3], double b2[3], double c2[3], double n2[3], double *p1 = nullptr, double *p2 = nullptr) { const double TOL = 1e-6; // Tolerance for point coordinate equality check double q1[3], q2[3], t1, t2, d, min = inf; // Point in second triangle closest to any of the corners of the first triangle t2 = vtkPlane::Evaluate(n2, a2, a1); d = abs(t2); if (d < min) { VmsV(q2, a1, t2, n2); if (vtkTriangle::PointInTriangle(q2, a2, b2, c2, TOL)) { MIRTK_RETURN_POINT(p1, a1); MIRTK_RETURN_POINT(p2, q2); min = d; } } t2 = vtkPlane::Evaluate(n2, a2, b1); d = abs(t2); if (d < min) { VmsV(q2, b1, t2, n2); if (vtkTriangle::PointInTriangle(q2, a2, b2, c2, TOL)) { MIRTK_RETURN_POINT(p1, b1); MIRTK_RETURN_POINT(p2, q2); min = d; } } t2 = vtkPlane::Evaluate(n2, a2, c1); d = abs(t2); if (d < min) { VmsV(q2, c1, t2, n2); if (vtkTriangle::PointInTriangle(q2, a2, b2, c2, TOL)) { MIRTK_RETURN_POINT(p1, c1); MIRTK_RETURN_POINT(p2, q2); min = d; } } // Point in first triangle closest to any of the corners of the second triangle t1 = vtkPlane::Evaluate(n1, a1, a2); d = abs(t1); if (d < min) { VmsV(q1, a2, t1, n1); if (vtkTriangle::PointInTriangle(q1, a1, b1, c1, TOL)) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, a2); min = d; } } t1 = vtkPlane::Evaluate(n1, a1, b2); d = abs(t1); if (d < min) { VmsV(q1, b2, t1, n1); if (vtkTriangle::PointInTriangle(q1, a1, b1, c1, TOL)) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, b2); min = d; } } t1 = vtkPlane::Evaluate(n1, a1, c2); d = abs(t1); if (d < min) { VmsV(q1, c2, t1, n1); if (vtkTriangle::PointInTriangle(q1, a1, b1, c1, TOL)) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, c2); min = d; } } // Distance between each pair of edges d = vtkLine::DistanceBetweenLineSegments(a1, b1, a2, b2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(a1, b1, b2, c2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(a1, b1, c2, a2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(b1, c1, a2, b2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(b1, c1, b2, c2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(b1, c1, c2, a2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(c1, a1, a2, b2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(c1, a1, b2, c2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } d = vtkLine::DistanceBetweenLineSegments(c1, a1, c2, a2, q1, q2, t1, t2); if (d < min) { MIRTK_RETURN_POINT(p1, q1); MIRTK_RETURN_POINT(p2, q2); min = d; } return min; } // ----------------------------------------------------------------------------- double Triangle ::DistanceBetweenTriangles( const double a1[3], const double b1[3], const double c1[3], const double n1[3], const double a2[3], const double b2[3], const double c2[3], const double n2[3], double *p1, double *p2 ) { return distance_between_triangles(const_cast<double *>(a1), const_cast<double *>(b1), const_cast<double *>(c1), const_cast<double *>(n1), const_cast<double *>(a2), const_cast<double *>(b2), const_cast<double *>(c2), const_cast<double *>(n2), p1, p2); } // ============================================================================= // Triangle/triangle intersection test // ============================================================================= #include "triangle_triangle_intersection.h" // ----------------------------------------------------------------------------- bool Triangle ::TriangleTriangleIntersection(const double a1[3], const double b1[3], const double c1[3], const double a2[3], const double b2[3], const double c2[3]) { if (tri_tri_overlap_test_3d(const_cast<double *>(a1), const_cast<double *>(b1), const_cast<double *>(c1), const_cast<double *>(a2), const_cast<double *>(b2), const_cast<double *>(c2)) != 0) { // FIXME: Yields on occassion false positive intersection tests of nearby, // but not even close to intersecting triangles. Therefore, // this expensive distance computation... should not be needed :-( double n1[3], n2[3]; Triangle::Normal(a1, b1, c1, n1); Triangle::Normal(a2, b2, c2, n2); if (distance_between_triangles(const_cast<double *>(a1), const_cast<double *>(b1), const_cast<double *>(c1), const_cast<double *>(n1), const_cast<double *>(a2), const_cast<double *>(b2), const_cast<double *>(c2), const_cast<double *>(n2)) < 1e-6) { return true; } } return false; } } // namespace mirtk <|endoftext|>
<commit_before>/** * \file logging.hh * \brief logging **/ #ifndef LOGGING_HH_INCLUDED #define LOGGING_HH_INCLUDED #include <fstream> #include <ostream> #include <sstream> #include <ctime> #include <iomanip> #include <map> #include <assert.h> #include "misc.hh" #include "filesystem.hh" class Logging; Logging& Logger (); /** \brief handles all logging **/ class Logging { public: enum LogFlags{ LOG_NONE = 1, LOG_ERR = 2, LOG_INFO = 4, LOG_DEBUG = 8, LOG_CONSOLE = 16, LOG_FILE = 32 }; //! only for logging to a single file which should then be executable by matlab class MatlabLogStream { public: MatlabLogStream( LogFlags loglevel, int& logflags, std::ofstream& logFile ) : matlabLogFile_( logFile ), loglevel_(loglevel), logflags_(logflags), suspended_logflags_(logflags) {} ~MatlabLogStream(){} template < typename T > MatlabLogStream& operator << ( T in ) { if ( logflags_ & loglevel_ ) buffer_ << in; return *this; } MatlabLogStream& operator << ( MatlabLogStream& ( *pf )(MatlabLogStream&) ) { if ( logflags_ & loglevel_ ) buffer_ << pf; return *this; } MatlabLogStream& operator << ( std::ostream& ( *pf )(std::ostream &) ) { if ( logflags_ & loglevel_ ) { if ( pf == (std::ostream& ( * )(std::ostream&))std::endl ) { //flush buffer into stream buffer_ << "\n"; Flush(); } else { buffer_ << pf; } } return *this; } void Flush() { matlabLogFile_ << buffer_.str(); matlabLogFile_.flush(); buffer_.flush(); buffer_.str("");// clear the buffer } void Suspend() { //don't accidentally invalidate flags if already suspended if ( !is_suspended_ ) { suspended_logflags_ = logflags_; logflags_ = 1; } is_suspended_ = true; } void Resume() { if ( is_suspended_ ) logflags_ = suspended_logflags_; is_suspended_ = false; } private: std::stringstream buffer_; std::ofstream& matlabLogFile_; LogFlags loglevel_; int& logflags_; int suspended_logflags_; bool is_suspended_; }; //! ostream compatible class wrapping file and console output class LogStream //: virtual public std::ostream { public: typedef int PriorityType; static const PriorityType default_suspend_priority = 0; protected: LogFlags loglevel_; int& logflags_; int suspended_logflags_; std::stringstream buffer_; std::ofstream& logfile_; std::ofstream& logfileWoTime_; bool is_suspended_; PriorityType suspend_priority_; public: LogStream( LogFlags loglevel, int& logflags, std::ofstream& file, std::ofstream& fileWoTime ) : loglevel_(loglevel), logflags_(logflags), suspended_logflags_(logflags), logfile_(file), logfileWoTime_( fileWoTime ), is_suspended_(false), suspend_priority_( default_suspend_priority ) {} ~LogStream() { Flush(); } template < typename T > LogStream& operator << ( T in ) { SetColor(); if ( logflags_ & loglevel_ ) buffer_ << in; UnsetColor(); return *this; } void Suspend( PriorityType priority = default_suspend_priority ) { //the suspend_priority_ mechanism provides a way to silence streams from 'higher' modules suspend_priority_ = std::max( priority, suspend_priority_ ); { //don't accidentally invalidate flags if already suspended if ( !is_suspended_ ) { suspended_logflags_ = logflags_; logflags_ = 1; } is_suspended_ = true; } } void Resume( PriorityType priority = default_suspend_priority ) { if ( priority >= suspend_priority_ ) { if ( is_suspended_ ) logflags_ = suspended_logflags_; is_suspended_ = false; suspend_priority_ = default_suspend_priority; } } //! alias for ostream compat void flush() { Flush(); } void Flush() { if ( logflags_ & loglevel_ ) { //flush buffer into stream if ( ( logflags_ & LOG_CONSOLE ) != 0 ) { std::cout << buffer_.str();// << std::endl; std::cout .flush(); } if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_ << "\n" << TimeString() << buffer_.str() << std::endl; logfileWoTime_ << buffer_.str();// << std::endl; logfile_.flush(); logfileWoTime_.flush(); } buffer_.flush(); buffer_.str("");// clear the buffer } } void SetColor() { // if ( logflags_ & LOG_INFO ) { // buffer_ << "\033[21;31m"; // } } void UnsetColor() { // buffer_ << "\033[0m"; } //template < class Class > LogStream& operator << ( LogStream& ( *pf )(LogStream&) ) { if ( logflags_ & loglevel_ ) buffer_ << pf; return *this; } LogStream& operator << ( std::ostream& ( *pf )(std::ostream &) ) { SetColor(); if ( logflags_ & loglevel_ ) { if ( pf == (std::ostream& ( * )(std::ostream&))std::endl ) { //flush buffer into stream buffer_ << "\n"; Flush(); } else buffer_ << pf; } UnsetColor(); return *this; } template < class Class,typename Pointer > void Log( Pointer pf, Class& c ) { if ( logflags_ & loglevel_ ) { (c.*pf)( buffer_ ); } } }; protected: Logging( ) { streamIDs_.push_back( LOG_ERR ); streamIDs_.push_back( LOG_DEBUG ); streamIDs_.push_back( LOG_INFO ); } ~Logging() { IdVecCIter it = streamIDs_.end(); for ( ; it != streamIDs_.begin(); --it ) { delete streammap_[*it]; streammap_[*it] = 0; } if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_ << '\n' << TimeString() << ": LOG END" << std::endl; logfileWoTime_ << std::endl; logfile_.close(); logfileWoTime_.close(); } // delete the MatlabLogStream matlabLogStreamPtr->Flush(); matlabLogFile_.close(); delete matlabLogStreamPtr; matlabLogStreamPtr = 0; } public: /** \brief setup loglevel, logfilename \param logflags any OR'd combination of flags \param logfile filename for log, can contain paths, but creation will fail if dir is non-existant **/ void Create (unsigned int logflags = LOG_FILE | LOG_CONSOLE | LOG_ERR, std::string logfile = "dune_stokes", std::string logdir = std::string() ) { logflags_ = logflags; //if we get a logdir from parameters append path seperator, otherwise leave empty //enables us to use logdir unconditionally further down if ( !logdir.empty() ) logdir += "/"; filename_ = logdir + logfile + "_time.log"; Stuff::testCreateDirectory( filename_ ); //could assert this if i figure out why errno is != EEXIST filenameWoTime_ = logdir + logfile + ".log"; if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_.open ( filename_.c_str() ); assert( logfile_.is_open() ); logfileWoTime_.open ( filenameWoTime_.c_str() ); assert( logfileWoTime_.is_open() ); } IdVecCIter it = streamIDs_.begin(); for ( ; it != streamIDs_.end(); ++it ) { flagmap_[*it] = logflags; streammap_[*it] = new LogStream( *it, flagmap_[*it], logfile_, logfileWoTime_ ); } // create the MatlabLogStream std::string matlabLogFileName = logdir + logfile + "_matlab.m"; Stuff::testCreateDirectory( matlabLogFileName ); //could assert this if i figure out why errno is != EEXIST matlabLogFile_.open( matlabLogFileName.c_str() ); assert( matlabLogFile_.is_open() ); matlabLogStreamPtr = new MatlabLogStream( LOG_FILE, logflags_, matlabLogFile_ ); } void SetPrefix( std::string prefix ) { /// begin dtor IdVecCIter it = streamIDs_.end(); for ( ; it != streamIDs_.begin(); --it ) { delete streammap_[*it]; streammap_[*it]=0; } if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_ << '\n' << TimeString() << ": LOG END" << std::endl; logfileWoTime_ << std::endl; logfile_.close(); logfileWoTime_.close(); } // delete the MatlabLogStream matlabLogStreamPtr->Flush(); matlabLogFile_.close(); delete matlabLogStreamPtr; matlabLogStreamPtr = 0; /// end dtor Create ( logflags_, prefix ); } void SetStreamFlags( LogFlags stream, int flags ) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); //this might result in logging to diff targtes, so we flush the current targets flagmap_[stream] = flags; } int GetStreamFlags( LogFlags stream ) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); return flagmap_[stream]; } /** \name Log funcs for member-function pointers * \{ */ template < typename Pointer, class Class > void LogDebug( Pointer pf, Class& c ) { if ( ( logflags_ & LOG_DEBUG ) ) Log( pf, c, LOG_DEBUG ); } template < class Class,typename Pointer > void LogInfo( Pointer pf , Class& c ) { if ( ( logflags_ & LOG_INFO ) ) Log( pf, c, LOG_INFO ); } template < typename Pointer, class Class > void LogErr( Pointer pf, Class& c ) { if ( ( logflags_ & LOG_ERR ) ) Log( pf, c, LOG_ERR ); } template < typename Pointer, class Class > void Log( void ( Class::*pf )(std::ostream&) const, Class& c, LogFlags stream) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); if ( ( flagmap_[stream] & LOG_CONSOLE ) != 0 ) (c.*pf)( std::cout ); if ( ( flagmap_[stream] & LOG_FILE ) != 0 ) (c.*pf)( logfile_ ); } template < class Class,typename Pointer > void Log( Pointer pf, Class& c, LogFlags stream) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); if ( ( flagmap_[stream] & LOG_CONSOLE ) != 0 ) (c.*pf)( std::cout ); if ( ( flagmap_[stream] & LOG_FILE ) != 0 ) { (c.*pf)( logfile_ ); (c.*pf)( logfileWoTime_ ); } } /** \} */ /** \name Log funcs for basic types/classes * \{ */ template < class Class > void LogDebug( Class c ) { if ( ( logflags_ & LOG_DEBUG ) ) Log( c, LOG_DEBUG ); } template < class Class > void LogInfo( Class c ) { if ( ( logflags_ & LOG_INFO ) ) Log( c, LOG_INFO ); } template < class Class > void LogErr( Class c ) { if ( ( logflags_ & LOG_ERR ) ) Log( c, LOG_ERR ); } template < class Class > void Log( Class c, LogFlags stream ) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); if ( ( flagmap_[stream] & LOG_CONSOLE ) != 0 ) std::cout << c; if ( ( flagmap_[stream] & LOG_FILE ) != 0 ) { logfile_ << c; logfileWoTime_ << c; } } /** \} */ LogStream& GetStream(int stream) { assert( streammap_[(LogFlags)stream] ); return *streammap_[(LogFlags)stream]; } LogStream& Err() { return GetStream( LOG_ERR ); } LogStream& Info() { return GetStream( LOG_INFO ); } LogStream& Dbg() { return GetStream( LOG_DEBUG ); } MatlabLogStream& Matlab() { return *matlabLogStreamPtr; } static std::string TimeString() { const time_t cur_time = time( NULL ); return ctime ( &cur_time ); } void Flush() { for ( StreamMap::iterator it = streammap_.begin(); it != streammap_.end(); ++it ) { it->second->Flush(); } } int AddStream( int flags ) { // assert( streamIDs_.find( streamID ) == streamIDs_.end() ); static int streamID_int = 16; streamID_int <<= 2; LogFlags streamID = (LogFlags) streamID_int; streamIDs_.push_back( streamID ); flagmap_[streamID] = flags | streamID; streammap_[streamID] = new LogStream( streamID, flagmap_[streamID], logfile_, logfileWoTime_ ); return streamID_int; } void Resume( LogStream::PriorityType prio = LogStream::default_suspend_priority ) { for ( StreamMap::iterator it = streammap_.begin(); it != streammap_.end(); ++it ) { it->second->Resume( prio ); } } void Suspend( LogStream::PriorityType prio = LogStream::default_suspend_priority ) { for ( StreamMap::iterator it = streammap_.begin(); it != streammap_.end(); ++it ) { it->second->Suspend( prio ); } } struct SuspendLocal { LogStream::PriorityType prio_; SuspendLocal( LogStream::PriorityType prio = LogStream::default_suspend_priority ) :prio_(prio) { Logger().Suspend( prio_ ); } ~SuspendLocal() { Logger().Resume( prio_ ); } }; struct ResumeLocal { LogStream::PriorityType prio_; ResumeLocal( LogStream::PriorityType prio = LogStream::default_suspend_priority ) :prio_(prio) { Logger().Resume( prio_ ); } ~ResumeLocal() { Logger().Suspend( prio_ ); } }; private: std::string filename_; std::string filenameWoTime_; std::ofstream logfile_; std::ofstream logfileWoTime_; std::ofstream matlabLogFile_; typedef std::map<LogFlags,int> FlagMap; FlagMap flagmap_; typedef std::map<LogFlags,LogStream*> StreamMap; StreamMap streammap_; typedef std::vector<LogFlags> IdVec; typedef std::vector<LogFlags>::const_iterator IdVecCIter; IdVec streamIDs_; int logflags_; MatlabLogStream* matlabLogStreamPtr; friend Logging& Logger (); }; ///global Logging instance Logging& Logger () { static Logging log; return log; } #endif <commit_msg>moved logs into datadir<commit_after>/** * \file logging.hh * \brief logging **/ #ifndef LOGGING_HH_INCLUDED #define LOGGING_HH_INCLUDED #include <fstream> #include <ostream> #include <sstream> #include <ctime> #include <iomanip> #include <map> #include <assert.h> #include "misc.hh" #include "filesystem.hh" class Logging; Logging& Logger (); /** \brief handles all logging **/ class Logging { public: enum LogFlags{ LOG_NONE = 1, LOG_ERR = 2, LOG_INFO = 4, LOG_DEBUG = 8, LOG_CONSOLE = 16, LOG_FILE = 32 }; //! only for logging to a single file which should then be executable by matlab class MatlabLogStream { public: MatlabLogStream( LogFlags loglevel, int& logflags, std::ofstream& logFile ) : matlabLogFile_( logFile ), loglevel_(loglevel), logflags_(logflags), suspended_logflags_(logflags) {} ~MatlabLogStream(){} template < typename T > MatlabLogStream& operator << ( T in ) { if ( logflags_ & loglevel_ ) buffer_ << in; return *this; } MatlabLogStream& operator << ( MatlabLogStream& ( *pf )(MatlabLogStream&) ) { if ( logflags_ & loglevel_ ) buffer_ << pf; return *this; } MatlabLogStream& operator << ( std::ostream& ( *pf )(std::ostream &) ) { if ( logflags_ & loglevel_ ) { if ( pf == (std::ostream& ( * )(std::ostream&))std::endl ) { //flush buffer into stream buffer_ << "\n"; Flush(); } else { buffer_ << pf; } } return *this; } void Flush() { matlabLogFile_ << buffer_.str(); matlabLogFile_.flush(); buffer_.flush(); buffer_.str("");// clear the buffer } void Suspend() { //don't accidentally invalidate flags if already suspended if ( !is_suspended_ ) { suspended_logflags_ = logflags_; logflags_ = 1; } is_suspended_ = true; } void Resume() { if ( is_suspended_ ) logflags_ = suspended_logflags_; is_suspended_ = false; } private: std::stringstream buffer_; std::ofstream& matlabLogFile_; LogFlags loglevel_; int& logflags_; int suspended_logflags_; bool is_suspended_; }; //! ostream compatible class wrapping file and console output class LogStream //: virtual public std::ostream { public: typedef int PriorityType; static const PriorityType default_suspend_priority = 0; protected: LogFlags loglevel_; int& logflags_; int suspended_logflags_; std::stringstream buffer_; std::ofstream& logfile_; std::ofstream& logfileWoTime_; bool is_suspended_; PriorityType suspend_priority_; public: LogStream( LogFlags loglevel, int& logflags, std::ofstream& file, std::ofstream& fileWoTime ) : loglevel_(loglevel), logflags_(logflags), suspended_logflags_(logflags), logfile_(file), logfileWoTime_( fileWoTime ), is_suspended_(false), suspend_priority_( default_suspend_priority ) {} ~LogStream() { Flush(); } template < typename T > LogStream& operator << ( T in ) { SetColor(); if ( logflags_ & loglevel_ ) buffer_ << in; UnsetColor(); return *this; } void Suspend( PriorityType priority = default_suspend_priority ) { //the suspend_priority_ mechanism provides a way to silence streams from 'higher' modules suspend_priority_ = std::max( priority, suspend_priority_ ); { //don't accidentally invalidate flags if already suspended if ( !is_suspended_ ) { suspended_logflags_ = logflags_; logflags_ = 1; } is_suspended_ = true; } } void Resume( PriorityType priority = default_suspend_priority ) { if ( priority >= suspend_priority_ ) { if ( is_suspended_ ) logflags_ = suspended_logflags_; is_suspended_ = false; suspend_priority_ = default_suspend_priority; } } //! alias for ostream compat void flush() { Flush(); } void Flush() { if ( logflags_ & loglevel_ ) { //flush buffer into stream if ( ( logflags_ & LOG_CONSOLE ) != 0 ) { std::cout << buffer_.str();// << std::endl; std::cout .flush(); } if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_ << "\n" << TimeString() << buffer_.str() << std::endl; logfileWoTime_ << buffer_.str();// << std::endl; logfile_.flush(); logfileWoTime_.flush(); } buffer_.flush(); buffer_.str("");// clear the buffer } } void SetColor() { // if ( logflags_ & LOG_INFO ) { // buffer_ << "\033[21;31m"; // } } void UnsetColor() { // buffer_ << "\033[0m"; } //template < class Class > LogStream& operator << ( LogStream& ( *pf )(LogStream&) ) { if ( logflags_ & loglevel_ ) buffer_ << pf; return *this; } LogStream& operator << ( std::ostream& ( *pf )(std::ostream &) ) { SetColor(); if ( logflags_ & loglevel_ ) { if ( pf == (std::ostream& ( * )(std::ostream&))std::endl ) { //flush buffer into stream buffer_ << "\n"; Flush(); } else buffer_ << pf; } UnsetColor(); return *this; } template < class Class,typename Pointer > void Log( Pointer pf, Class& c ) { if ( logflags_ & loglevel_ ) { (c.*pf)( buffer_ ); } } }; protected: Logging( ) { streamIDs_.push_back( LOG_ERR ); streamIDs_.push_back( LOG_DEBUG ); streamIDs_.push_back( LOG_INFO ); } ~Logging() { IdVecCIter it = streamIDs_.end(); for ( ; it != streamIDs_.begin(); --it ) { delete streammap_[*it]; streammap_[*it] = 0; } if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_ << '\n' << TimeString() << ": LOG END" << std::endl; logfileWoTime_ << std::endl; logfile_.close(); logfileWoTime_.close(); } // delete the MatlabLogStream matlabLogStreamPtr->Flush(); matlabLogFile_.close(); delete matlabLogStreamPtr; matlabLogStreamPtr = 0; } public: /** \brief setup loglevel, logfilename \param logflags any OR'd combination of flags \param logfile filename for log, can contain paths, but creation will fail if dir is non-existant **/ void Create (unsigned int logflags = LOG_FILE | LOG_CONSOLE | LOG_ERR, std::string logfile = "dune_stokes", std::string datadir = "data", std::string logdir = std::string("") ) { logflags_ = logflags; //if we get a logdir from parameters append path seperator, otherwise leave empty //enables us to use logdir unconditionally further down if ( !datadir.empty() ) datadir += "/"; if ( !logdir.empty() ) logdir += "/"; logdir = datadir + logdir; filename_ = logdir + logfile + "_time.log"; Stuff::testCreateDirectory( logdir ); //could assert this if i figure out why errno is != EEXIST filenameWoTime_ = logdir + logfile + ".log"; if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_.open ( filename_.c_str() ); assert( logfile_.is_open() ); logfileWoTime_.open ( filenameWoTime_.c_str() ); assert( logfileWoTime_.is_open() ); } IdVecCIter it = streamIDs_.begin(); for ( ; it != streamIDs_.end(); ++it ) { flagmap_[*it] = logflags; streammap_[*it] = new LogStream( *it, flagmap_[*it], logfile_, logfileWoTime_ ); } // create the MatlabLogStream std::string matlabLogFileName = logdir + logfile + "_matlab.m"; Stuff::testCreateDirectory( matlabLogFileName ); //could assert this if i figure out why errno is != EEXIST matlabLogFile_.open( matlabLogFileName.c_str() ); assert( matlabLogFile_.is_open() ); matlabLogStreamPtr = new MatlabLogStream( LOG_FILE, logflags_, matlabLogFile_ ); } void SetPrefix( std::string prefix ) { /// begin dtor IdVecCIter it = streamIDs_.end(); for ( ; it != streamIDs_.begin(); --it ) { delete streammap_[*it]; streammap_[*it]=0; } if ( ( logflags_ & LOG_FILE ) != 0 ) { logfile_ << '\n' << TimeString() << ": LOG END" << std::endl; logfileWoTime_ << std::endl; logfile_.close(); logfileWoTime_.close(); } // delete the MatlabLogStream matlabLogStreamPtr->Flush(); matlabLogFile_.close(); delete matlabLogStreamPtr; matlabLogStreamPtr = 0; /// end dtor Create ( logflags_, prefix ); } void SetStreamFlags( LogFlags stream, int flags ) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); //this might result in logging to diff targtes, so we flush the current targets flagmap_[stream] = flags; } int GetStreamFlags( LogFlags stream ) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); return flagmap_[stream]; } /** \name Log funcs for member-function pointers * \{ */ template < typename Pointer, class Class > void LogDebug( Pointer pf, Class& c ) { if ( ( logflags_ & LOG_DEBUG ) ) Log( pf, c, LOG_DEBUG ); } template < class Class,typename Pointer > void LogInfo( Pointer pf , Class& c ) { if ( ( logflags_ & LOG_INFO ) ) Log( pf, c, LOG_INFO ); } template < typename Pointer, class Class > void LogErr( Pointer pf, Class& c ) { if ( ( logflags_ & LOG_ERR ) ) Log( pf, c, LOG_ERR ); } template < typename Pointer, class Class > void Log( void ( Class::*pf )(std::ostream&) const, Class& c, LogFlags stream) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); if ( ( flagmap_[stream] & LOG_CONSOLE ) != 0 ) (c.*pf)( std::cout ); if ( ( flagmap_[stream] & LOG_FILE ) != 0 ) (c.*pf)( logfile_ ); } template < class Class,typename Pointer > void Log( Pointer pf, Class& c, LogFlags stream) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); if ( ( flagmap_[stream] & LOG_CONSOLE ) != 0 ) (c.*pf)( std::cout ); if ( ( flagmap_[stream] & LOG_FILE ) != 0 ) { (c.*pf)( logfile_ ); (c.*pf)( logfileWoTime_ ); } } /** \} */ /** \name Log funcs for basic types/classes * \{ */ template < class Class > void LogDebug( Class c ) { if ( ( logflags_ & LOG_DEBUG ) ) Log( c, LOG_DEBUG ); } template < class Class > void LogInfo( Class c ) { if ( ( logflags_ & LOG_INFO ) ) Log( c, LOG_INFO ); } template < class Class > void LogErr( Class c ) { if ( ( logflags_ & LOG_ERR ) ) Log( c, LOG_ERR ); } template < class Class > void Log( Class c, LogFlags stream ) { assert( stream & ( LOG_ERR | LOG_INFO | LOG_DEBUG ) ); if ( ( flagmap_[stream] & LOG_CONSOLE ) != 0 ) std::cout << c; if ( ( flagmap_[stream] & LOG_FILE ) != 0 ) { logfile_ << c; logfileWoTime_ << c; } } /** \} */ LogStream& GetStream(int stream) { assert( streammap_[(LogFlags)stream] ); return *streammap_[(LogFlags)stream]; } LogStream& Err() { return GetStream( LOG_ERR ); } LogStream& Info() { return GetStream( LOG_INFO ); } LogStream& Dbg() { return GetStream( LOG_DEBUG ); } MatlabLogStream& Matlab() { return *matlabLogStreamPtr; } static std::string TimeString() { const time_t cur_time = time( NULL ); return ctime ( &cur_time ); } void Flush() { for ( StreamMap::iterator it = streammap_.begin(); it != streammap_.end(); ++it ) { it->second->Flush(); } } int AddStream( int flags ) { // assert( streamIDs_.find( streamID ) == streamIDs_.end() ); static int streamID_int = 16; streamID_int <<= 2; LogFlags streamID = (LogFlags) streamID_int; streamIDs_.push_back( streamID ); flagmap_[streamID] = flags | streamID; streammap_[streamID] = new LogStream( streamID, flagmap_[streamID], logfile_, logfileWoTime_ ); return streamID_int; } void Resume( LogStream::PriorityType prio = LogStream::default_suspend_priority ) { for ( StreamMap::iterator it = streammap_.begin(); it != streammap_.end(); ++it ) { it->second->Resume( prio ); } } void Suspend( LogStream::PriorityType prio = LogStream::default_suspend_priority ) { for ( StreamMap::iterator it = streammap_.begin(); it != streammap_.end(); ++it ) { it->second->Suspend( prio ); } } struct SuspendLocal { LogStream::PriorityType prio_; SuspendLocal( LogStream::PriorityType prio = LogStream::default_suspend_priority ) :prio_(prio) { Logger().Suspend( prio_ ); } ~SuspendLocal() { Logger().Resume( prio_ ); } }; struct ResumeLocal { LogStream::PriorityType prio_; ResumeLocal( LogStream::PriorityType prio = LogStream::default_suspend_priority ) :prio_(prio) { Logger().Resume( prio_ ); } ~ResumeLocal() { Logger().Suspend( prio_ ); } }; private: std::string filename_; std::string filenameWoTime_; std::ofstream logfile_; std::ofstream logfileWoTime_; std::ofstream matlabLogFile_; typedef std::map<LogFlags,int> FlagMap; FlagMap flagmap_; typedef std::map<LogFlags,LogStream*> StreamMap; StreamMap streammap_; typedef std::vector<LogFlags> IdVec; typedef std::vector<LogFlags>::const_iterator IdVecCIter; IdVec streamIDs_; int logflags_; MatlabLogStream* matlabLogStreamPtr; friend Logging& Logger (); }; ///global Logging instance Logging& Logger () { static Logging log; return log; } #endif <|endoftext|>
<commit_before>#include <PCU.h> #include "phBubble.h" #include "phInput.h" #include <apfMesh.h> #include <apf.h> #include <stdio.h> namespace ph { struct Bubble { int id; apf::Vector3 center; double radius; }; typedef std::vector<Bubble> Bubbles; void readBubbles(Bubbles& bubbles) { unsigned long bubblecount = 0; char bubblefname[256]; FILE *filebubble; Bubble readbubble; sprintf(bubblefname,"bubbles.inp"); if (!PCU_Comm_Self()) printf("reading bubbles info from %s\n",bubblefname); filebubble = fopen(bubblefname, "r"); assert(filebubble != NULL); while(1) { // File format (each line represents a bubble): x_center y_center z_center radius fscanf(filebubble, "%lf %lf %lf %lf", &readbubble.center[0], &readbubble.center[1], &readbubble.center[2], &readbubble.radius); if(feof(filebubble)) break; bubblecount++; readbubble.id = bubblecount; bubbles.push_back(readbubble); } fclose(filebubble); if (!PCU_Comm_Self()) printf("%lu bubbles found in %s\n", bubbles.size(), bubblefname); // Debug /* for(unsigned long i=0; i<bubbles.size(); i++) { printf("%d %lf %lf %lf %lf\n", bubbles[i].id, bubbles[i].center[0], bubbles[i].center[1], bubbles[i].center[2], bubbles[i].radius); } */ } void setBubbleScalars(apf::Mesh* m, apf::MeshEntity* v, Bubbles& bubbles, double* sol) { apf::Vector3 v_center; m->getPoint(v, 0, v_center); int bubbleid = 0; double distx; double disty; double distz; double tmpdist; double distance = 1e99; /* search through bubbles, find the distance to the nearet bubble membrane (sphere) */ for(unsigned long i=0; i<bubbles.size(); i++) { distx = (v_center[0]-bubbles[i].center[0]); disty = (v_center[1]-bubbles[i].center[1]); distz = (v_center[2]-bubbles[i].center[2]); tmpdist = sqrt(distx*distx + disty*disty + distz*distz) - bubbles[i].radius; if(tmpdist < distance) { distance = tmpdist; if (distance < 0) { bubbleid = bubbles[i].id; break; //if v is inside a bubble, stop searching since bubbles should not intersect each other } } } // debug // printf("coord: %lf %lf %lf - Dist: %lf - Bubble id: %d\n", coord[0], coord[1], coord[2], distance, bubbleid); sol[5] = distance; sol[6] = static_cast<double>(bubbleid); } void initBubbles(apf::Mesh* m, Input& in) { Bubbles bubbles; readBubbles(bubbles); assert(in.ensa_dof >= 7); apf::NewArray<double> s(in.ensa_dof); apf::Field* f = m->findField("solution"); apf::MeshIterator* it = m->begin(0); apf::MeshEntity* v; while ((v = m->iterate(it))) { apf::getComponents(f, v, 0, &s[0]); setBubbleScalars(m, v, bubbles, &s[0]); apf::setComponents(f, v, 0, &s[0]); } m->end(it); } } <commit_msg>Change in the logic of the bubble id for pts outside the bubbles.<commit_after>#include <PCU.h> #include "phBubble.h" #include "phInput.h" #include <apfMesh.h> #include <apf.h> #include <stdio.h> namespace ph { struct Bubble { int id; apf::Vector3 center; double radius; }; typedef std::vector<Bubble> Bubbles; void readBubbles(Bubbles& bubbles) { unsigned long bubblecount = 0; char bubblefname[256]; FILE *filebubble; Bubble readbubble; sprintf(bubblefname,"bubbles.inp"); if (!PCU_Comm_Self()) printf("reading bubbles info from %s\n",bubblefname); filebubble = fopen(bubblefname, "r"); assert(filebubble != NULL); while(1) { // File format (each line represents a bubble): x_center y_center z_center radius fscanf(filebubble, "%lf %lf %lf %lf", &readbubble.center[0], &readbubble.center[1], &readbubble.center[2], &readbubble.radius); if(feof(filebubble)) break; bubblecount++; readbubble.id = bubblecount; bubbles.push_back(readbubble); } fclose(filebubble); if (!PCU_Comm_Self()) printf("%lu bubbles found in %s\n", bubbles.size(), bubblefname); // Debug /* for(unsigned long i=0; i<bubbles.size(); i++) { printf("%d %lf %lf %lf %lf\n", bubbles[i].id, bubbles[i].center[0], bubbles[i].center[1], bubbles[i].center[2], bubbles[i].radius); } */ } void setBubbleScalars(apf::Mesh* m, apf::MeshEntity* v, Bubbles& bubbles, double* sol) { apf::Vector3 v_center; m->getPoint(v, 0, v_center); int bubbleid = 0; double distx; double disty; double distz; double tmpdist; double distance = 1e99; /* search through bubbles, find the distance to the nearet bubble membrane (sphere) */ for(unsigned long i=0; i<bubbles.size(); i++) { distx = (v_center[0]-bubbles[i].center[0]); disty = (v_center[1]-bubbles[i].center[1]); distz = (v_center[2]-bubbles[i].center[2]); tmpdist = sqrt(distx*distx + disty*disty + distz*distz) - bubbles[i].radius; if(tmpdist < distance) { distance = tmpdist; if (distance < 0) { bubbleid = bubbles[i].id; break; //if v is inside a bubble, stop searching since bubbles should not intersect each other } else bubbleid = -bubbles[i].id; // a negative value still give the id of the nearest bubble } } // debug // printf("coord: %lf %lf %lf - Dist: %lf - Bubble id: %d\n", coord[0], coord[1], coord[2], distance, bubbleid); sol[5] = distance; sol[6] = static_cast<double>(bubbleid); } void initBubbles(apf::Mesh* m, Input& in) { Bubbles bubbles; readBubbles(bubbles); assert(in.ensa_dof >= 7); apf::NewArray<double> s(in.ensa_dof); apf::Field* f = m->findField("solution"); apf::MeshIterator* it = m->begin(0); apf::MeshEntity* v; while ((v = m->iterate(it))) { apf::getComponents(f, v, 0, &s[0]); setBubbleScalars(m, v, bubbles, &s[0]); apf::setComponents(f, v, 0, &s[0]); } m->end(it); } } <|endoftext|>
<commit_before>//============================================================================ // Name : poa_1.cpp // Author : Adriano Bacac // Version : // Copyright : Your copyright notice // Description : Consensus generator from partial order sequence aligment //============================================================================ #include <iostream> #include "PoMsa.h" #include "HeaviestBundle.h" #include "SequenceBundler.h" #include "PercentageMatchSeqRule.h" using namespace std; int main() { PoMsa *poMsa; try { poMsa = new PoMsa("m_po_mine.aln"); }catch (std::string message){ std::cerr << message << std::endl; exit(-1); } SequenceBundler *bundler = new SequenceBundler(); bundler->addInclusionRule(new PercentageMatchSeqRule(1.0, 1.0)); HeaviestBundle *hb = new HeaviestBundle(poMsa, 1); while (true){ // pronadi najbolji put std::vector<Node *> bestPath; bestPath = hb->findTopScoringPath(); // gotovo nalazenje najboljeg puta // stvori novu sekvencu Seq *new_consensus = new Seq("name", "> title", bestPath.size(), 0); poMsa->cons.insert(new_consensus); poMsa->createSeqOnPath(new_consensus, bestPath); for (Node *node : bestPath) { std::cout << node->nucl << " -> "; } std::cout << std::endl; // gotovo stvaranje nove sekvence // pronadi slicne sekvence std::vector<Seq *> *bundle = new std::vector < Seq * > ; if (bundler->addSequencesToBundle(&poMsa->seqs, new_consensus, bundle) > 0){ std::cout << "pronasao slicne sekvence" << std::endl; for (Seq *seq : *bundle){ seq->rescaleWeight(0); std::cout << seq->name << std::endl; } std::cout << "-----------------" << std::endl; } else{ std::cout << "nisam pronasao slicne sekvence" << std::endl; break; } std::getchar(); } poMsa->dotFormat(); std::getchar(); return 0; } <commit_msg>arguments passed over command line (not for rules, yet)<commit_after>//============================================================================ // Name : poa_1.cpp // Author : Adriano Bacac // Version : // Copyright : Your copyright notice // Description : Consensus generator from partial order sequence aligment //============================================================================ #include <iostream> #include <getopt.h> #include <string.h> #include "PoMsa.h" #include "HeaviestBundle.h" #include "SequenceBundler.h" #include "PercentageMatchSeqRule.h" using namespace std; int parse_input(int argc, char * const argv[], string *input, string *conf, int *thread_count) { // default values *input = "in.po"; *conf = "config.txt"; *thread_count = 1; int next_option; /* String of short options */ const char *short_options = "t:i:c:"; /* The array of long options */ const struct option long_options[] = { { "input", 1, NULL, 'i' }, { "config", 1, NULL, 'c' }, { "threads", 1, NULL, 't'} }; do { next_option = getopt_long(argc, argv, short_options, long_options, NULL); switch (next_option) { case 'i': /* User requested help */ *input = optarg; break; case 'c': *conf = optarg; break; case 't': *thread_count = atoi(optarg); break; case '?': /* The user specified an invalid option */ fprintf(stdout, "Requested arg does not exist!\n"); exit(EXIT_FAILURE); case -1: /* Done with options */ break; default: /* Unexpected things */ fprintf(stdout, "I can't handle this arg!\n"); exit(EXIT_FAILURE); } } while(next_option != -1); return (EXIT_SUCCESS); } int main(int argc, char * const argv[]) { string input; string config; int thread_cnt; if(parse_input(argc, argv, &input, &config, &thread_cnt)){ cout << "Could not parse file" << endl; exit(EXIT_FAILURE); } fprintf(stdout, "INPUT: %s\n", input.c_str()); fprintf(stdout, "CONFIG: %s\n", config.c_str()); fprintf(stdout, "THREADS: %d\n", thread_cnt); PoMsa *poMsa; try { poMsa = new PoMsa(input); }catch (std::string message){ std::cerr << message << std::endl; exit(-1); } SequenceBundler *bundler = new SequenceBundler(); bundler->addInclusionRule(new PercentageMatchSeqRule(1.0, 1.0)); HeaviestBundle *hb = new HeaviestBundle(poMsa, thread_cnt); while (true){ // pronadi najbolji put std::vector<Node *> bestPath; bestPath = hb->findTopScoringPath(); // gotovo nalazenje najboljeg puta // stvori novu sekvencu Seq *new_consensus = new Seq("name", "> title", bestPath.size(), 0); poMsa->cons.insert(new_consensus); poMsa->createSeqOnPath(new_consensus, bestPath); for (Node *node : bestPath) { std::cout << node->nucl << " -> "; } std::cout << std::endl; // gotovo stvaranje nove sekvence // pronadi slicne sekvence std::vector<Seq *> *bundle = new std::vector < Seq * > ; if (bundler->addSequencesToBundle(&poMsa->seqs, new_consensus, bundle) > 0){ std::cout << "pronasao slicne sekvence" << std::endl; for (Seq *seq : *bundle){ seq->rescaleWeight(0); std::cout << seq->name << std::endl; } std::cout << "-----------------" << std::endl; } else{ std::cout << "nisam pronasao slicne sekvence" << std::endl; break; } std::getchar(); } poMsa->dotFormat(); std::getchar(); return 0; } <|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 "OgreStableHeaders.h" namespace Ogre { const ColourValue ColourValue::ZERO = ColourValue(0.0,0.0,0.0,0.0); const ColourValue ColourValue::Black = ColourValue(0.0,0.0,0.0); const ColourValue ColourValue::White = ColourValue(1.0,1.0,1.0); const ColourValue ColourValue::Red = ColourValue(1.0,0.0,0.0); const ColourValue ColourValue::Green = ColourValue(0.0,1.0,0.0); const ColourValue ColourValue::Blue = ColourValue(0.0,0.0,1.0); //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG ABGR ColourValue::getAsABGR(void) const #else RGBA ColourValue::getAsRGBA(void) const #endif { uint8 val8; uint32 val32 = 0; // Convert to 32bit pattern // (RGBA = 8888) // Red val8 = static_cast<uint8>(r * 255); val32 = val8 << 24; // Green val8 = static_cast<uint8>(g * 255); val32 += val8 << 16; // Blue val8 = static_cast<uint8>(b * 255); val32 += val8 << 8; // Alpha val8 = static_cast<uint8>(a * 255); val32 += val8; return val32; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG BGRA ColourValue::getAsBGRA(void) const #else ARGB ColourValue::getAsARGB(void) const #endif { uint8 val8; uint32 val32 = 0; // Convert to 32bit pattern // (ARGB = 8888) // Alpha val8 = static_cast<uint8>(a * 255); val32 = val8 << 24; // Red val8 = static_cast<uint8>(r * 255); val32 += val8 << 16; // Green val8 = static_cast<uint8>(g * 255); val32 += val8 << 8; // Blue val8 = static_cast<uint8>(b * 255); val32 += val8; return val32; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG ARGB ColourValue::getAsARGB(void) const #else BGRA ColourValue::getAsBGRA(void) const #endif { uint8 val8; uint32 val32 = 0; // Convert to 32bit pattern // (ARGB = 8888) // Blue val8 = static_cast<uint8>(b * 255); val32 = val8 << 24; // Green val8 = static_cast<uint8>(g * 255); val32 += val8 << 16; // Red val8 = static_cast<uint8>(r * 255); val32 += val8 << 8; // Alpha val8 = static_cast<uint8>(a * 255); val32 += val8; return val32; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG RGBA ColourValue::getAsRGBA(void) const #else ABGR ColourValue::getAsABGR(void) const #endif { uint8 val8; uint32 val32 = 0; // Convert to 32bit pattern // (ABRG = 8888) // Alpha val8 = static_cast<uint8>(a * 255); val32 = val8 << 24; // Blue val8 = static_cast<uint8>(b * 255); val32 += val8 << 16; // Green val8 = static_cast<uint8>(g * 255); val32 += val8 << 8; // Red val8 = static_cast<uint8>(r * 255); val32 += val8; return val32; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG void ColourValue::setAsABGR(ABGR val32) #else void ColourValue::setAsRGBA(RGBA val32) #endif { // Convert from 32bit pattern // (RGBA = 8888) // Red r = ((val32 >> 24) & 0xFF) / 255.0f; // Green g = ((val32 >> 16) & 0xFF) / 255.0f; // Blue b = ((val32 >> 8) & 0xFF) / 255.0f; // Alpha a = (val32 & 0xFF) / 255.0f; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG void ColourValue::setAsBGRA(BGRA val32) #else void ColourValue::setAsARGB(ARGB val32) #endif { // Convert from 32bit pattern // (ARGB = 8888) // Alpha a = ((val32 >> 24) & 0xFF) / 255.0f; // Red r = ((val32 >> 16) & 0xFF) / 255.0f; // Green g = ((val32 >> 8) & 0xFF) / 255.0f; // Blue b = (val32 & 0xFF) / 255.0f; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG void ColourValue::setAsARGB(ARGB val32) #else void ColourValue::setAsBGRA(BGRA val32) #endif { // Convert from 32bit pattern // (ARGB = 8888) // Blue b = ((val32 >> 24) & 0xFF) / 255.0f; // Green g = ((val32 >> 16) & 0xFF) / 255.0f; // Red r = ((val32 >> 8) & 0xFF) / 255.0f; // Alpha a = (val32 & 0xFF) / 255.0f; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG void ColourValue::setAsRGBA(RGBA val32) #else void ColourValue::setAsABGR(ABGR val32) #endif { // Convert from 32bit pattern // (ABGR = 8888) // Alpha a = ((val32 >> 24) & 0xFF) / 255.0f; // Blue b = ((val32 >> 16) & 0xFF) / 255.0f; // Green g = ((val32 >> 8) & 0xFF) / 255.0f; // Red r = (val32 & 0xFF) / 255.0f; } //--------------------------------------------------------------------- bool ColourValue::operator==(const ColourValue& rhs) const { return (r == rhs.r && g == rhs.g && b == rhs.b && a == rhs.a); } //--------------------------------------------------------------------- bool ColourValue::operator!=(const ColourValue& rhs) const { return !(*this == rhs); } //--------------------------------------------------------------------- void ColourValue::setHSB(float hue, float saturation, float brightness) { // wrap hue if (hue > 1.0f) { hue -= (int)hue; } else if (hue < 0.0f) { hue += (int)hue + 1; } // clamp saturation / brightness saturation = std::min(saturation, 1.0f); saturation = std::max(saturation, 0.0f); brightness = std::min(brightness, 1.0f); brightness = std::max(brightness, 0.0f); if (brightness == 0.0f) { // early exit, this has to be black r = g = b = 0.0f; return; } if (saturation == 0.0f) { // early exit, this has to be grey r = g = b = brightness; return; } float hueDomain = hue * 6.0f; if (hueDomain >= 6.0f) { // wrap around, and allow mathematical errors hueDomain = 0.0f; } unsigned short domain = (unsigned short)hueDomain; float f1 = brightness * (1 - saturation); float f2 = brightness * (1 - saturation * (hueDomain - domain)); float f3 = brightness * (1 - saturation * (1 - (hueDomain - domain))); switch (domain) { case 0: // red domain; green ascends r = brightness; g = f3; b = f1; break; case 1: // yellow domain; red descends r = f2; g = brightness; b = f1; break; case 2: // green domain; blue ascends r = f1; g = brightness; b = f3; break; case 3: // cyan domain; green descends r = f1; g = f2; b = brightness; break; case 4: // blue domain; red ascends r = f3; g = f1; b = brightness; break; case 5: // magenta domain; blue descends r = brightness; g = f1; b = f2; break; } } //--------------------------------------------------------------------- void ColourValue::getHSB(float& hue, float& saturation, float& brightness) const { float vMin = std::min(r, std::min(g, b)); float vMax = std::max(r, std::max(g, b)); float delta = vMax - vMin; brightness = vMax; if (Math::RealEqual(delta, 0.0f, 1e-6)) { // grey hue = 0; saturation = 0; } else { // a colour saturation = delta / vMax; float deltaR = (((vMax - r) / 6.0f) + (delta / 2.0f)) / delta; float deltaG = (((vMax - g) / 6.0f) + (delta / 2.0f)) / delta; float deltaB = (((vMax - b) / 6.0f) + (delta / 2.0f)) / delta; if (Math::RealEqual(r, vMax)) hue = deltaB - deltaG; else if (Math::RealEqual(g, vMax)) hue = 0.3333333f + deltaR - deltaB; else if (Math::RealEqual(b, vMax)) hue = 0.6666667f + deltaG - deltaR; if (hue < 0.0f) hue += 1.0f; if (hue > 1.0f) hue -= 1.0f; } } } <commit_msg>Main: ColourValue - fix Wconversion warnings<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 "OgreStableHeaders.h" namespace Ogre { const ColourValue ColourValue::ZERO = ColourValue(0.0,0.0,0.0,0.0); const ColourValue ColourValue::Black = ColourValue(0.0,0.0,0.0); const ColourValue ColourValue::White = ColourValue(1.0,1.0,1.0); const ColourValue ColourValue::Red = ColourValue(1.0,0.0,0.0); const ColourValue ColourValue::Green = ColourValue(0.0,1.0,0.0); const ColourValue ColourValue::Blue = ColourValue(0.0,0.0,1.0); //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG ABGR ColourValue::getAsABGR(void) const #else RGBA ColourValue::getAsRGBA(void) const #endif { uint8 val8; uint32 val32 = 0; // Convert to 32bit pattern // (RGBA = 8888) // Red val8 = static_cast<uint8>(r * 255); val32 = val8 << 24; // Green val8 = static_cast<uint8>(g * 255); val32 += val8 << 16; // Blue val8 = static_cast<uint8>(b * 255); val32 += val8 << 8; // Alpha val8 = static_cast<uint8>(a * 255); val32 += val8; return val32; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG BGRA ColourValue::getAsBGRA(void) const #else ARGB ColourValue::getAsARGB(void) const #endif { uint8 val8; uint32 val32 = 0; // Convert to 32bit pattern // (ARGB = 8888) // Alpha val8 = static_cast<uint8>(a * 255); val32 = val8 << 24; // Red val8 = static_cast<uint8>(r * 255); val32 += val8 << 16; // Green val8 = static_cast<uint8>(g * 255); val32 += val8 << 8; // Blue val8 = static_cast<uint8>(b * 255); val32 += val8; return val32; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG ARGB ColourValue::getAsARGB(void) const #else BGRA ColourValue::getAsBGRA(void) const #endif { uint8 val8; uint32 val32 = 0; // Convert to 32bit pattern // (ARGB = 8888) // Blue val8 = static_cast<uint8>(b * 255); val32 = val8 << 24; // Green val8 = static_cast<uint8>(g * 255); val32 += val8 << 16; // Red val8 = static_cast<uint8>(r * 255); val32 += val8 << 8; // Alpha val8 = static_cast<uint8>(a * 255); val32 += val8; return val32; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG RGBA ColourValue::getAsRGBA(void) const #else ABGR ColourValue::getAsABGR(void) const #endif { uint8 val8; uint32 val32 = 0; // Convert to 32bit pattern // (ABRG = 8888) // Alpha val8 = static_cast<uint8>(a * 255); val32 = val8 << 24; // Blue val8 = static_cast<uint8>(b * 255); val32 += val8 << 16; // Green val8 = static_cast<uint8>(g * 255); val32 += val8 << 8; // Red val8 = static_cast<uint8>(r * 255); val32 += val8; return val32; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG void ColourValue::setAsABGR(ABGR val32) #else void ColourValue::setAsRGBA(RGBA val32) #endif { // Convert from 32bit pattern // (RGBA = 8888) // Red r = float((val32 >> 24) & 0xFF) / 255.0f; // Green g = float((val32 >> 16) & 0xFF) / 255.0f; // Blue b = float((val32 >> 8) & 0xFF) / 255.0f; // Alpha a = float(val32 & 0xFF) / 255.0f; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG void ColourValue::setAsBGRA(BGRA val32) #else void ColourValue::setAsARGB(ARGB val32) #endif { // Convert from 32bit pattern // (ARGB = 8888) // Alpha a = float((val32 >> 24) & 0xFF) / 255.0f; // Red r = float((val32 >> 16) & 0xFF) / 255.0f; // Green g = float((val32 >> 8) & 0xFF) / 255.0f; // Blue b = float(val32 & 0xFF) / 255.0f; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG void ColourValue::setAsARGB(ARGB val32) #else void ColourValue::setAsBGRA(BGRA val32) #endif { // Convert from 32bit pattern // (ARGB = 8888) // Blue b = float((val32 >> 24) & 0xFF) / 255.0f; // Green g = float((val32 >> 16) & 0xFF) / 255.0f; // Red r = float((val32 >> 8) & 0xFF) / 255.0f; // Alpha a = float(val32 & 0xFF) / 255.0f; } //--------------------------------------------------------------------- #if OGRE_ENDIAN == OGRE_ENDIAN_BIG void ColourValue::setAsRGBA(RGBA val32) #else void ColourValue::setAsABGR(ABGR val32) #endif { // Convert from 32bit pattern // (ABGR = 8888) // Alpha a = float((val32 >> 24) & 0xFF) / 255.0f; // Blue b = float((val32 >> 16) & 0xFF) / 255.0f; // Green g = float((val32 >> 8) & 0xFF) / 255.0f; // Red r = float(val32 & 0xFF) / 255.0f; } //--------------------------------------------------------------------- bool ColourValue::operator==(const ColourValue& rhs) const { return (r == rhs.r && g == rhs.g && b == rhs.b && a == rhs.a); } //--------------------------------------------------------------------- bool ColourValue::operator!=(const ColourValue& rhs) const { return !(*this == rhs); } //--------------------------------------------------------------------- void ColourValue::setHSB(float hue, float saturation, float brightness) { // wrap hue hue = std::fmod(hue, 1.0f); // clamp saturation / brightness saturation = Math::saturate(saturation); brightness = Math::saturate(brightness); if (brightness == 0.0f) { // early exit, this has to be black r = g = b = 0.0f; return; } if (saturation == 0.0f) { // early exit, this has to be grey r = g = b = brightness; return; } float hueDomain = hue * 6.0f; if (hueDomain >= 6.0f) { // wrap around, and allow mathematical errors hueDomain = 0.0f; } unsigned short domain = (unsigned short)hueDomain; float f1 = brightness * (1 - saturation); float f2 = brightness * (1 - saturation * (hueDomain - domain)); float f3 = brightness * (1 - saturation * (1 - (hueDomain - domain))); switch (domain) { case 0: // red domain; green ascends r = brightness; g = f3; b = f1; break; case 1: // yellow domain; red descends r = f2; g = brightness; b = f1; break; case 2: // green domain; blue ascends r = f1; g = brightness; b = f3; break; case 3: // cyan domain; green descends r = f1; g = f2; b = brightness; break; case 4: // blue domain; red ascends r = f3; g = f1; b = brightness; break; case 5: // magenta domain; blue descends r = brightness; g = f1; b = f2; break; } } //--------------------------------------------------------------------- void ColourValue::getHSB(float& hue, float& saturation, float& brightness) const { float vMin = std::min(r, std::min(g, b)); float vMax = std::max(r, std::max(g, b)); float delta = vMax - vMin; brightness = vMax; if (Math::RealEqual(delta, 0.0f, 1e-6f)) { // grey hue = 0; saturation = 0; } else { // a colour saturation = delta / vMax; float deltaR = (((vMax - r) / 6.0f) + (delta / 2.0f)) / delta; float deltaG = (((vMax - g) / 6.0f) + (delta / 2.0f)) / delta; float deltaB = (((vMax - b) / 6.0f) + (delta / 2.0f)) / delta; if (Math::RealEqual(r, vMax)) hue = deltaB - deltaG; else if (Math::RealEqual(g, vMax)) hue = 0.3333333f + deltaR - deltaB; else if (Math::RealEqual(b, vMax)) hue = 0.6666667f + deltaG - deltaR; if (hue < 0.0f) hue += 1.0f; if (hue > 1.0f) hue -= 1.0f; } } } <|endoftext|>
<commit_before>#include "share.h" #include "object.h" #include "directory.h" #include "file.h" #include "objectiterator.h" #include "objectcache.h" #include "ipfs/ipfs.h" #include <QDateTime> #include <QDebug> #include <QStringBuilder> /* * PlanUML * @startuml * * [*] -> CREATING * CREATING -> CREATING : add file/dir * CREATING -> DOWNLOAD_METADATA : download * DOWNLOAD_METADATA -> READY : dl metadata done * READY -> DOWNLOAD : start * PAUSED -> DOWNLOAD : start * DOWNLOAD -> SHARING : ended * DOWNLOAD -> PAUSED : pause * * [*] -> SHARING : share * * @enduml */ Share::Share(QObject *parent): QObject(parent), id_(-1), creation_date_(QDateTime::currentDateTime()), starred_(false), state_(CREATING) { } int Share::id() const { return id_; } const QString& Share::title() const { return title_; } const QString Share::description() const { if(!description_.isEmpty() || objects_.count() == 0) return description_; // If no description is available, we build a list of the first files QString desc; for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { for(ObjectIterator it = ObjectIterator(*i); it != ObjectIterator(); it++) { if(!(*it).name().isEmpty()) { desc += (*it).name(); desc += ", "; } if(desc.count() > 100) { desc += "..."; return desc; } } } return desc; } const QDir &Share::path() const { return path_; } const QDateTime &Share::date_creation() const { return creation_date_; } bool Share::starred() const { return starred_; } void Share::set_starred(const bool &starred) { starred_ = starred; emit shareChanged(); } QString Share::textual_arborescence() const { if(this->objects_.count() == 0) return ""; QString result; for(ObjectIterator it = ObjectIterator(this->objects_[0]); it != ObjectIterator(); it++) { result += QString("--").repeated(it.depth()); result += (*it).name(); result += "\n"; } return result; } Share::ShareState Share::state() const { return state_; } float Share::progress() const { if(state_ == CREATING) return 0.0; uint total = block_total(); if(total == 0) return 0.0; return (float)block_local() / (float)total; } uint Share::size_total() const { uint size_total = 0; for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { size_total += (*i)->size_total(); } return size_total; } uint Share::size_local() const { uint size_local = 0; for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { size_local += (*i)->size_local(); } return size_local; } uint Share::block_total() const { uint block_total = 0; for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { block_total += (*i)->block_total(); } return block_total; } uint Share::block_local() const { uint block_local = 0; for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { block_local += (*i)->block_local(); } return block_local; } uint Share::file_total() const { uint file_total = 0; for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { file_total += (*i)->file_total(); } return file_total; } uint Share::file_local() const { uint file_local = 0; for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { file_local += (*i)->file_local(); } return file_local; } bool Share::metadata_local() const { for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { if(!(*i)->metadata_local()) { return false; } } return true; } void Share::add_hash(const IpfsHash &hash) { Object *obj = ObjectCache::instance()->get(hash); if(obj != NULL) { connect(obj, SIGNAL(localityChanged()), this, SLOT(objectChanged())); this->objects_ << obj; return; } LsReply *reply = Ipfs::instance()->ls.ls(hash); connect(reply, &LsReply::finished, [reply, hash, this]() { Object *obj; if(reply->entries.count() == 0) { // no child objet, we have a file obj = new File(hash); } else { // we have a directory obj = new Directory(reply); } connect(obj, SIGNAL(localityChanged()), this, SLOT(objectChanged())); this->objects_ << obj; }); } void Share::add_hash(const IpfsHash &hash, Object::ObjectType type) { Object *obj = ObjectCache::instance()->get(hash); if(obj != NULL) { connect(obj, SIGNAL(localityChanged()), this, SLOT(objectChanged())); this->objects_ << obj; return; } switch (type) { case Object::ObjectType::DIRECTORY: obj = new Directory(hash); break; case Object::ObjectType::FILE: obj = new File(hash); default: qDebug() << "Unknow object type retrieved from database."; Q_ASSERT(false); break; } objects_ << obj; connect(obj, SIGNAL(localityChanged()), this, SLOT(objectChanged())); } void Share::download() { // Todo } void Share::pause() { // Todo } void Share::set_title(const QString &title) { title_ = title; emit shareChanged(); } void Share::objectChanged() { emit dataChanged(); emit shareChanged(); } <commit_msg>fix a missing break, courtesy of Clang's scan-build<commit_after>#include "share.h" #include "object.h" #include "directory.h" #include "file.h" #include "objectiterator.h" #include "objectcache.h" #include "ipfs/ipfs.h" #include <QDateTime> #include <QDebug> #include <QStringBuilder> /* * PlanUML * @startuml * * [*] -> CREATING * CREATING -> CREATING : add file/dir * CREATING -> DOWNLOAD_METADATA : download * DOWNLOAD_METADATA -> READY : dl metadata done * READY -> DOWNLOAD : start * PAUSED -> DOWNLOAD : start * DOWNLOAD -> SHARING : ended * DOWNLOAD -> PAUSED : pause * * [*] -> SHARING : share * * @enduml */ Share::Share(QObject *parent): QObject(parent), id_(-1), creation_date_(QDateTime::currentDateTime()), starred_(false), state_(CREATING) { } int Share::id() const { return id_; } const QString& Share::title() const { return title_; } const QString Share::description() const { if(!description_.isEmpty() || objects_.count() == 0) return description_; // If no description is available, we build a list of the first files QString desc; for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { for(ObjectIterator it = ObjectIterator(*i); it != ObjectIterator(); it++) { if(!(*it).name().isEmpty()) { desc += (*it).name(); desc += ", "; } if(desc.count() > 100) { desc += "..."; return desc; } } } return desc; } const QDir &Share::path() const { return path_; } const QDateTime &Share::date_creation() const { return creation_date_; } bool Share::starred() const { return starred_; } void Share::set_starred(const bool &starred) { starred_ = starred; emit shareChanged(); } QString Share::textual_arborescence() const { if(this->objects_.count() == 0) return ""; QString result; for(ObjectIterator it = ObjectIterator(this->objects_[0]); it != ObjectIterator(); it++) { result += QString("--").repeated(it.depth()); result += (*it).name(); result += "\n"; } return result; } Share::ShareState Share::state() const { return state_; } float Share::progress() const { if(state_ == CREATING) return 0.0; uint total = block_total(); if(total == 0) return 0.0; return (float)block_local() / (float)total; } uint Share::size_total() const { uint size_total = 0; for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { size_total += (*i)->size_total(); } return size_total; } uint Share::size_local() const { uint size_local = 0; for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { size_local += (*i)->size_local(); } return size_local; } uint Share::block_total() const { uint block_total = 0; for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { block_total += (*i)->block_total(); } return block_total; } uint Share::block_local() const { uint block_local = 0; for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { block_local += (*i)->block_local(); } return block_local; } uint Share::file_total() const { uint file_total = 0; for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { file_total += (*i)->file_total(); } return file_total; } uint Share::file_local() const { uint file_local = 0; for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { file_local += (*i)->file_local(); } return file_local; } bool Share::metadata_local() const { for(QList<Object*>::const_iterator i = objects_.constBegin(); i != objects_.constEnd(); i++) { if(!(*i)->metadata_local()) { return false; } } return true; } void Share::add_hash(const IpfsHash &hash) { Object *obj = ObjectCache::instance()->get(hash); if(obj != NULL) { connect(obj, SIGNAL(localityChanged()), this, SLOT(objectChanged())); this->objects_ << obj; return; } LsReply *reply = Ipfs::instance()->ls.ls(hash); connect(reply, &LsReply::finished, [reply, hash, this]() { Object *obj; if(reply->entries.count() == 0) { // no child objet, we have a file obj = new File(hash); } else { // we have a directory obj = new Directory(reply); } connect(obj, SIGNAL(localityChanged()), this, SLOT(objectChanged())); this->objects_ << obj; }); } void Share::add_hash(const IpfsHash &hash, Object::ObjectType type) { Object *obj = ObjectCache::instance()->get(hash); if(obj != NULL) { connect(obj, SIGNAL(localityChanged()), this, SLOT(objectChanged())); this->objects_ << obj; return; } switch (type) { case Object::ObjectType::DIRECTORY: obj = new Directory(hash); break; case Object::ObjectType::FILE: obj = new File(hash); break; default: qDebug() << "Unknow object type retrieved from database."; Q_ASSERT(false); break; } objects_ << obj; connect(obj, SIGNAL(localityChanged()), this, SLOT(objectChanged())); } void Share::download() { // Todo } void Share::pause() { // Todo } void Share::set_title(const QString &title) { title_ = title; emit shareChanged(); } void Share::objectChanged() { emit dataChanged(); emit shareChanged(); } <|endoftext|>
<commit_before>#include "cprocessing.hpp" using namespace cprocessing; Style::Style() { std::cout << styles.size() << std::endl; if(styles.size() > 0) { /*strokeColor.rgba[0] = styles[styles.size()-1].strokeColor.rgba[0]; ///< Line drawing color strokeColor.rgba[1] = styles[styles.size()-1].strokeColor.rgba[1]; strokeColor.rgba[2] = styles[styles.size()-1].strokeColor.rgba[2]; strokeColor.rgba[3] = styles[styles.size()-1].strokeColor.rgba[3]; fillColor.rgba[0] = styles[styles.size()-1].fillColor.rgba[0]; ///< Area drawing color fillColor.rgba[1] = styles[styles.size()-1].fillColor.rgba[1]; fillColor.rgba[2] = styles[styles.size()-1].fillColor.rgba[2]; fillColor.rgba[3] = styles[styles.size()-1].fillColor.rgba[3];*/ strokeColor = styles[styles.size()-1].strokeColor; fillColor = styles[styles.size()-1].fillColor; rectMode = styles[styles.size()-1].rectMode; ///< Rectangle drawing mode ellipseMode = styles[styles.size()-1].ellipseMode; ///< Ellipse drawing mode globColorMode = styles[styles.size()-1].globColorMode; imageMode = styles[styles.size()-1].imageMode; strokeWeight = styles[styles.size()-1].strokeWeight; sphereDetail = styles[styles.size()-1].sphereDetail; ellipseDetail = styles[styles.size()-1].ellipseDetail; bezierDetail = styles[styles.size()-1].bezierDetail; specular = new float[4]; specular[0] = styles[styles.size()-1].specular[0]; specular[1] = styles[styles.size()-1].specular[1]; specular[2] = styles[styles.size()-1].specular[2]; specular[3] = styles[styles.size()-1].specular[3]; ellipseVtx = styles[styles.size()-1].ellipseVtx; ures = styles[styles.size()-1].ures; vres = styles[styles.size()-1].vres; sphereVtx = styles[styles.size()-1].sphereVtx; sphereIdx = styles[styles.size()-1].sphereIdx; bezierBlend = styles[styles.size()-1].bezierBlend; ///< bezierDetail samples of Bézier blending functions } else { rectMode = CORNER; ///< Rectangle drawing mode ellipseMode = CENTER; ///< Ellipse drawing mode globColorMode = RGB; max1 = 255; // First component max2 = 255; // Second component max3 = 255; // Third component maxA = 255; // Alpha component imageMode = CORNER; strokeWeight = 1; sphereDetail = 10; ellipseDetail = 30; bezierDetail = 50; specular = new float[4]; specular[0] = 0; specular[1] = 0; specular[2] = 0; specular[3] = 1; } } /* //TODO Style::~Style() { delete [] specular; } */<commit_msg>remove useless cout of style size<commit_after>#include "cprocessing.hpp" using namespace cprocessing; Style::Style() { if(styles.size() > 0) { /*strokeColor.rgba[0] = styles[styles.size()-1].strokeColor.rgba[0]; ///< Line drawing color strokeColor.rgba[1] = styles[styles.size()-1].strokeColor.rgba[1]; strokeColor.rgba[2] = styles[styles.size()-1].strokeColor.rgba[2]; strokeColor.rgba[3] = styles[styles.size()-1].strokeColor.rgba[3]; fillColor.rgba[0] = styles[styles.size()-1].fillColor.rgba[0]; ///< Area drawing color fillColor.rgba[1] = styles[styles.size()-1].fillColor.rgba[1]; fillColor.rgba[2] = styles[styles.size()-1].fillColor.rgba[2]; fillColor.rgba[3] = styles[styles.size()-1].fillColor.rgba[3];*/ strokeColor = styles[styles.size()-1].strokeColor; fillColor = styles[styles.size()-1].fillColor; rectMode = styles[styles.size()-1].rectMode; ///< Rectangle drawing mode ellipseMode = styles[styles.size()-1].ellipseMode; ///< Ellipse drawing mode globColorMode = styles[styles.size()-1].globColorMode; imageMode = styles[styles.size()-1].imageMode; strokeWeight = styles[styles.size()-1].strokeWeight; sphereDetail = styles[styles.size()-1].sphereDetail; ellipseDetail = styles[styles.size()-1].ellipseDetail; bezierDetail = styles[styles.size()-1].bezierDetail; specular = new float[4]; specular[0] = styles[styles.size()-1].specular[0]; specular[1] = styles[styles.size()-1].specular[1]; specular[2] = styles[styles.size()-1].specular[2]; specular[3] = styles[styles.size()-1].specular[3]; ellipseVtx = styles[styles.size()-1].ellipseVtx; ures = styles[styles.size()-1].ures; vres = styles[styles.size()-1].vres; sphereVtx = styles[styles.size()-1].sphereVtx; sphereIdx = styles[styles.size()-1].sphereIdx; bezierBlend = styles[styles.size()-1].bezierBlend; ///< bezierDetail samples of Bézier blending functions } else { rectMode = CORNER; ///< Rectangle drawing mode ellipseMode = CENTER; ///< Ellipse drawing mode globColorMode = RGB; max1 = 255; // First component max2 = 255; // Second component max3 = 255; // Third component maxA = 255; // Alpha component imageMode = CORNER; strokeWeight = 1; sphereDetail = 10; ellipseDetail = 30; bezierDetail = 50; specular = new float[4]; specular[0] = 0; specular[1] = 0; specular[2] = 0; specular[3] = 1; } } /* //TODO Style::~Style() { delete [] specular; } */ <|endoftext|>
<commit_before>// // Created by Artur Troian on 4/21/16. // #include <tools/tools.hpp> std::string serialize_json(const Json::Value &json) { Json::StreamWriterBuilder wbuilder; std::string s = Json::writeString(wbuilder, json); return s; } <commit_msg>Wrap serialise_json into namespace tools<commit_after>// // Created by Artur Troian on 4/21/16. // #include <tools/tools.hpp> namespace tools { std::string serialize_json(const Json::Value &json) { Json::StreamWriterBuilder wbuilder; std::string s = Json::writeString(wbuilder, json); return s; } } // namespace tools <|endoftext|>
<commit_before>/*! \file uqueue.cc ******************************************************************************* File: uqueue.cc\n Implementation of the UQueue class. This file is part of %URBI Kernel, version __kernelversion__\n (c) Jean-Christophe Baillie, 2004-2005. Permission to use, copy, modify, and redistribute this software for non-commercial use is hereby granted. This software is provided "as is" without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of fitness for a particular purpose. For more information, comments, bug reports: http://www.urbiforge.net **************************************************************************** */ #include <cstdlib> #include "libport/cstring" #include "kernel/userver.hh" #include "uqueue.hh" //! UQueue constructor. /*! UQueue implements a dynamic circular FIFO buffer. You can specify the following parameters: \param minBufferSize is the initial size of the buffer. If the buffer is shrinked (adaptive buffer), its size will be at least minBufferSize. The default value if not specified is 4096 octets. \param maxBufferSize is the maximal size of the buffer. The buffer size is increased when one tries to push data that is too big for the current buffer size. However, this dynamic behavior is limited to maxBufferSize in any case. If the buffer can still not hold the pushed data, the push() function returns UFAIL. If set to zero, the limit is infinite. The default value is equal to minBufferSize. \param adaptive the default behavior of the UQueue is to increase the size of the internal buffer if one tries to hold more data that what the current size allows (up to maxBufferSize, as we said). However, if the buffer is adaptive, it will also be able to shrink the buffer. This is very useful to allow the UQueue to grow momentarily to hold a large amount of data and then recover memory after the boost, if this data size is not the usual functioning load. If adaptive is non null, the behavior is the following: the UQueue counts the number of calls to the pop() function. Each time this number goes above 'adaptive', the UQueue will resize to the maximum data size it has held in the past 'adaptive' calls to pop(), and minBufferSize at least. So, 'adaptive' is a time windows that is periodicaly checked to shink the buffer if necessary. Note that the buffer will shrink only if there is a minimum of 20% size difference, to avoid time consuming reallocs for nothing. We recommand a default value of 100 for the adaptive value. */ UQueue::UQueue (size_t minBufferSize, size_t maxBufferSize, size_t adaptive) : minBufferSize_ (minBufferSize ? minBufferSize : static_cast<size_t>(INITIAL_BUFFER_SIZE)), maxBufferSize_ (maxBufferSize == static_cast<size_t>(-1) ? minBufferSize_ : maxBufferSize), adaptive_(adaptive), buffer_(minBufferSize_), outputBuffer_(UQueue::INITIAL_BUFFER_SIZE), start_(0), end_(0), dataSize_(0), nbPopCall_(0), topDataSize_(0), topOutputSize_(0), mark_(0), locked_(false) { } //! UQueue destructor. UQueue::~UQueue() { } //! Clear the queue void UQueue::clear() { start_ = 0; end_ = 0; dataSize_ = 0; } //! Set a mark to be able to revert to this position void UQueue::mark() { mark_ = end_; locked_ = false; } //! Revert the buffer to the marked position. void UQueue::revert() { end_ = mark_; locked_ = true; } //! Pushes a buffer into the queue.. /*! This function tries to store the buffer in the queue, and tries to extend to buffer size when the buffer does not fit and if it is possible. \param buffer the buffer to push \param length the length of the buffer \return - USUCCESS: successful - UFAIL : could not push the buffer. The queue is not changed. */ UErrorValue UQueue::push (const ubyte *buffer, size_t length) { size_t bfs = bufferFreeSpace(); if (bfs < length) // Is the internal buffer big enough? { // No. Check if the internal buffer can be extended. size_t newSize = buffer_.size() + (length - bfs); if (newSize > maxBufferSize_ && maxBufferSize_ != 0) return UFAIL; else { // Calculate the required size + 10%, if it fits. newSize = (size_t)(1.10 * newSize); if (newSize % 2 != 0) ++newSize; // hack for short alignment... if (newSize > maxBufferSize_ && maxBufferSize_ != 0) newSize = maxBufferSize_; // Realloc the internal buffer size_t old_size = buffer_.size(); buffer_.resize(newSize); if (end_ < start_ || bfs == 0 ) { // Translate the rightside of the old internal buffer. memmove(&buffer_[0] + start_ + newSize - old_size, &buffer_[0] + start_, old_size - start_); start_ += newSize - old_size; } } } if (buffer_.size() - end_ >= length) { // Do we have to split 'buffer'? // No need to split. memcpy(&buffer_[0] + end_, buffer, length); end_ += length; if (end_ == buffer_.size()) end_ = 0; // loop the circular geometry. } else { // Split 'buffer' to fit in the internal circular buffer. memcpy(&buffer_[0] + end_, buffer, buffer_.size() - end_); memcpy(&buffer_[0], buffer + (buffer_.size() - end_), length - (buffer_.size() - end_)); end_ = length - (buffer_.size() - end_); } dataSize_ += length; return USUCCESS; } //! Pops 'length' bytes out of the Queue /*! Pops 'length' bytes. The ubyte* pointer returned is not permanent. You have to make a copy of the data pointed if you want to keep it. Any call to a member function of UQueue might alter it later. \param length the length requested. \return a pointer to the the data popped or 0 in case of error. */ ubyte* UQueue::pop (size_t length) { // Actual size of the data to pop. size_t toPop = length; if (toPop > dataSize_) return 0; // Not enough data to pop 'length' if (toPop == 0) // Pops nothing but gets a pointer to the beginning of the buffer. return &buffer_[0] + start_; // Adaptive shrinking behavior if (adaptive_) { ++nbPopCall_; if (dataSize_ > topDataSize_) topDataSize_ = dataSize_; if (toPop > topOutputSize_) topOutputSize_ = toPop; if (nbPopCall_ > adaptive_ ) { // time out nbPopCall_ = 0; // reset if (topOutputSize_ < (size_t)(outputBuffer_.size() * 0.8)) { // We shrink the output buffer to the new size: topOutputSize_ + 10% topOutputSize_ = (size_t)(topOutputSize_ * 1.1); outputBuffer_.resize(topOutputSize_); } if (topDataSize_ < (size_t) (buffer_.size() * 0.8)) { // We shrink the buffer to the new size: topDataSize_ + 10% (if it fits) topDataSize_ = (size_t) (topDataSize_ * 1.1); if (topDataSize_ > maxBufferSize_ && maxBufferSize_ !=0) topDataSize_ = maxBufferSize_; if (end_ < start_) { // The data is splitted memmove(&buffer_[0] + start_ - (buffer_.size() - topDataSize_), &buffer_[0] + start_, buffer_.size() - start_); start_ = start_ - (buffer_.size() - topDataSize_); } else { // The data is contiguous memmove(&buffer_[0], &buffer_[0] + start_, dataSize_); start_ = 0; end_ = dataSize_; // the case end_ == buffer_.size() is handled below. } buffer_.resize(topDataSize_); if (end_ == buffer_.size() ) end_ =0; // loop the circular geometry. // else... well it should never come to this else anyway. } topDataSize_ = 0; topOutputSize_ = 0; } } if (buffer_.size() - start_ >= toPop) { // Is the packet continuous across the the internal buffer? yes, // the packet is continuous in the internal buffer size_t tmp_index = start_; start_ += toPop; if (start_ == buffer_.size()) start_ = 0; // loop the circular geometry. dataSize_ -= toPop; return &buffer_[0] + tmp_index; } else { // no, the packet spans then end and the beginning of the buffer // and it must be reconstructed. // Is the temporary internal outputBuffer large enough? if (outputBuffer_.size() < toPop) { // Realloc the internal outputBuffer size_t theNewSize = (size_t)(toPop * 1.10); if (theNewSize % 2 != 0) ++theNewSize; outputBuffer_.resize(theNewSize); } memcpy(&outputBuffer_[0], &buffer_[0] + start_, buffer_.size() - start_); memcpy(&outputBuffer_[0] + (buffer_.size() - start_ ), &buffer_[0], toPop - (buffer_.size() - start_)); start_ = toPop - (buffer_.size() - start_); dataSize_ -= toPop; return &outputBuffer_[0]; } } //! Pops at most 'length' bytes out of the Queue /*! Pops at most 'length' bytes. The actual size is returned in 'length'. The ubyte* pointer returned is not permanent. You have to make a copy of the data pointed if you want to keep it. Any call to a member function of UQueue might alter it later. This method is called "fast" because is will not use the temporary outputBuffer if the requested data is half at the end and half at the beginning of the buffer. It will return only the part at the end of the buffer and return the actual size of data popped. You have to check if this value is equal to the requested length. If it is not, a second call to fastPop will give you the rest of the buffer, with a different pointer. This function is useful if you plan to pop huge amount of data which will probably span over the end of the buffer and which would, with a simple call to 'pop', result in a huge memory replication. In other cases, prefer 'pop', which is most of the time as efficient as fastPop and much more convenient to use. \param length the length requested. Contains the actual length popped. \return a pointer to the the data popped or 0 in case of error. */ ubyte* UQueue::fastPop (size_t &length) { return pop((length > buffer_.size() - start_) ? (length = buffer_.size() - start_) : length); } //! Simulates the pop of 'length' bytes out of the Queue /*! Behave like pop but simulate the effect. This is useful if one wants to try something with the popped buffer and check the validity before actually popping the data. It is also typically used when trying to send bytes in a connection and it is not known in advance how many bytes will be effectively sent. \param length the length requested. \return a pointer to the the data popped or 0 in case of error. */ ubyte* UQueue::virtualPop (size_t length) { // Actual size of the data to pop. size_t toPop = length; if (toPop > dataSize_) return 0; // Not enough data to pop 'length' if (toPop == 0) // Pops nothing but gets a pointer to the beginning of the buffer. return &buffer_[0] + start_; // Is the packet continuous across the internal buffer? if (buffer_.size() - start_ >= toPop) // yes, the packet is continuous in the internal buffer return &buffer_[0] + start_; else { // no, the packet spans then end and the beginning of the buffer // and it must be reconstructed. // Is the temporary internal outputBuffer large enough? if (outputBuffer_.size() < toPop) { // Realloc the internal outputBuffer size_t theNewSize = (size_t)(toPop * 1.10); if (theNewSize % 2 != 0) ++theNewSize; outputBuffer_.resize(theNewSize); } memcpy(&outputBuffer_[0], &buffer_[0] + start_, buffer_.size() - start_); memcpy(&outputBuffer_[0] + (buffer_.size() - start_), &buffer_[0], toPop - (buffer_.size() - start_)); //start_ = toPop - (buffer_.size() - start_); //dataSize_ -= toPop; return &outputBuffer_[0]; } } <commit_msg>Simplify.<commit_after>/*! \file uqueue.cc ******************************************************************************* File: uqueue.cc\n Implementation of the UQueue class. This file is part of %URBI Kernel, version __kernelversion__\n (c) Jean-Christophe Baillie, 2004-2005. Permission to use, copy, modify, and redistribute this software for non-commercial use is hereby granted. This software is provided "as is" without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of fitness for a particular purpose. For more information, comments, bug reports: http://www.urbiforge.net **************************************************************************** */ #include <cstdlib> #include "libport/cstring" #include "kernel/userver.hh" #include "uqueue.hh" //! UQueue constructor. /*! UQueue implements a dynamic circular FIFO buffer. You can specify the following parameters: \param minBufferSize is the initial size of the buffer. If the buffer is shrinked (adaptive buffer), its size will be at least minBufferSize. The default value if not specified is 4096 octets. \param maxBufferSize is the maximal size of the buffer. The buffer size is increased when one tries to push data that is too big for the current buffer size. However, this dynamic behavior is limited to maxBufferSize in any case. If the buffer can still not hold the pushed data, the push() function returns UFAIL. If set to zero, the limit is infinite. The default value is equal to minBufferSize. \param adaptive the default behavior of the UQueue is to increase the size of the internal buffer if one tries to hold more data that what the current size allows (up to maxBufferSize, as we said). However, if the buffer is adaptive, it will also be able to shrink the buffer. This is very useful to allow the UQueue to grow momentarily to hold a large amount of data and then recover memory after the boost, if this data size is not the usual functioning load. If adaptive is non null, the behavior is the following: the UQueue counts the number of calls to the pop() function. Each time this number goes above 'adaptive', the UQueue will resize to the maximum data size it has held in the past 'adaptive' calls to pop(), and minBufferSize at least. So, 'adaptive' is a time windows that is periodicaly checked to shink the buffer if necessary. Note that the buffer will shrink only if there is a minimum of 20% size difference, to avoid time consuming reallocs for nothing. We recommand a default value of 100 for the adaptive value. */ UQueue::UQueue (size_t minBufferSize, size_t maxBufferSize, size_t adaptive) : minBufferSize_ (minBufferSize ? minBufferSize : static_cast<size_t>(INITIAL_BUFFER_SIZE)), maxBufferSize_ (maxBufferSize == static_cast<size_t>(-1) ? minBufferSize_ : maxBufferSize), adaptive_(adaptive), buffer_(minBufferSize_), outputBuffer_(UQueue::INITIAL_BUFFER_SIZE), start_(0), end_(0), dataSize_(0), nbPopCall_(0), topDataSize_(0), topOutputSize_(0), mark_(0), locked_(false) { } //! UQueue destructor. UQueue::~UQueue() { } //! Clear the queue void UQueue::clear() { start_ = 0; end_ = 0; dataSize_ = 0; } //! Set a mark to be able to revert to this position void UQueue::mark() { mark_ = end_; locked_ = false; } //! Revert the buffer to the marked position. void UQueue::revert() { end_ = mark_; locked_ = true; } //! Pushes a buffer into the queue.. /*! This function tries to store the buffer in the queue, and tries to extend to buffer size when the buffer does not fit and if it is possible. \param buffer the buffer to push \param length the length of the buffer \return - USUCCESS: successful - UFAIL : could not push the buffer. The queue is not changed. */ UErrorValue UQueue::push (const ubyte *buffer, size_t length) { size_t bfs = bufferFreeSpace(); if (bfs < length) // Is the internal buffer big enough? { // No. Check if the internal buffer can be extended. size_t newSize = buffer_.size() + (length - bfs); if (newSize > maxBufferSize_ && maxBufferSize_ != 0) return UFAIL; else { // Calculate the required size + 10%, if it fits. newSize = (size_t)(1.10 * newSize); if (newSize % 2 != 0) ++newSize; // hack for short alignment... if (newSize > maxBufferSize_ && maxBufferSize_ != 0) newSize = maxBufferSize_; // Realloc the internal buffer size_t old_size = buffer_.size(); buffer_.resize(newSize); if (end_ < start_ || bfs == 0 ) { // Translate the rightside of the old internal buffer. memmove(&buffer_[0] + start_ + newSize - old_size, &buffer_[0] + start_, old_size - start_); start_ += newSize - old_size; } } } if (buffer_.size() - end_ >= length) { // Do we have to split 'buffer'? // No need to split. memcpy(&buffer_[0] + end_, buffer, length); end_ += length; if (end_ == buffer_.size()) end_ = 0; // loop the circular geometry. } else { // Split 'buffer' to fit in the internal circular buffer. memcpy(&buffer_[0] + end_, buffer, buffer_.size() - end_); memcpy(&buffer_[0], buffer + (buffer_.size() - end_), length - (buffer_.size() - end_)); end_ = length - (buffer_.size() - end_); } dataSize_ += length; return USUCCESS; } //! Pops 'length' bytes out of the Queue /*! Pops 'length' bytes. The ubyte* pointer returned is not permanent. You have to make a copy of the data pointed if you want to keep it. Any call to a member function of UQueue might alter it later. \param length the length requested. \return a pointer to the the data popped or 0 in case of error. */ ubyte* UQueue::pop (size_t length) { // Actual size of the data to pop. size_t toPop = length; if (toPop > dataSize_) return 0; // Not enough data to pop 'length' if (toPop == 0) // Pops nothing but gets a pointer to the beginning of the buffer. return &buffer_[0] + start_; // Adaptive shrinking behavior if (adaptive_) { ++nbPopCall_; topDataSize_ = std::max (topDataSize_, dataSize_); topOutputSize_ = std::max (topOutputSize_, toPop); if (nbPopCall_ > adaptive_ ) { // time out nbPopCall_ = 0; // reset if (topOutputSize_ < (size_t)(outputBuffer_.size() * 0.8)) outputBuffer_.resize(topOutputSize_ * 1.1); if (topDataSize_ < (size_t) (buffer_.size() * 0.8)) { // We shrink the buffer to the new size: topDataSize_ + 10% (if it fits) topDataSize_ = (size_t) (topDataSize_ * 1.1); if (topDataSize_ > maxBufferSize_ && maxBufferSize_ !=0) topDataSize_ = maxBufferSize_; if (end_ < start_) { // The data is splitted memmove(&buffer_[0] + start_ - (buffer_.size() - topDataSize_), &buffer_[0] + start_, buffer_.size() - start_); start_ = start_ - (buffer_.size() - topDataSize_); } else { // The data is contiguous memmove(&buffer_[0], &buffer_[0] + start_, dataSize_); start_ = 0; end_ = dataSize_; // the case end_ == buffer_.size() is handled below. } buffer_.resize(topDataSize_); if (end_ == buffer_.size() ) end_ =0; // loop the circular geometry. // else... well it should never come to this else anyway. } topDataSize_ = 0; topOutputSize_ = 0; } } if (buffer_.size() - start_ >= toPop) { // Is the packet continuous across the the internal buffer? yes, // the packet is continuous in the internal buffer size_t tmp_index = start_; start_ += toPop; if (start_ == buffer_.size()) start_ = 0; // loop the circular geometry. dataSize_ -= toPop; return &buffer_[0] + tmp_index; } else { // no, the packet spans then end and the beginning of the buffer // and it must be reconstructed. // Is the temporary internal outputBuffer large enough? if (outputBuffer_.size() < toPop) outputBuffer_.resize(toPop * 1.1); memcpy(&outputBuffer_[0], &buffer_[0] + start_, buffer_.size() - start_); memcpy(&outputBuffer_[0] + (buffer_.size() - start_ ), &buffer_[0], toPop - (buffer_.size() - start_)); start_ = toPop - (buffer_.size() - start_); dataSize_ -= toPop; return &outputBuffer_[0]; } } //! Pops at most 'length' bytes out of the Queue /*! Pops at most 'length' bytes. The actual size is returned in 'length'. The ubyte* pointer returned is not permanent. You have to make a copy of the data pointed if you want to keep it. Any call to a member function of UQueue might alter it later. This method is called "fast" because is will not use the temporary outputBuffer if the requested data is half at the end and half at the beginning of the buffer. It will return only the part at the end of the buffer and return the actual size of data popped. You have to check if this value is equal to the requested length. If it is not, a second call to fastPop will give you the rest of the buffer, with a different pointer. This function is useful if you plan to pop huge amount of data which will probably span over the end of the buffer and which would, with a simple call to 'pop', result in a huge memory replication. In other cases, prefer 'pop', which is most of the time as efficient as fastPop and much more convenient to use. \param length the length requested. Contains the actual length popped. \return a pointer to the the data popped or 0 in case of error. */ ubyte* UQueue::fastPop (size_t &length) { return pop((length > buffer_.size() - start_) ? (length = buffer_.size() - start_) : length); } //! Simulates the pop of 'length' bytes out of the Queue /*! Behave like pop but simulate the effect. This is useful if one wants to try something with the popped buffer and check the validity before actually popping the data. It is also typically used when trying to send bytes in a connection and it is not known in advance how many bytes will be effectively sent. \param length the length requested. \return a pointer to the the data popped or 0 in case of error. */ ubyte* UQueue::virtualPop (size_t length) { // Actual size of the data to pop. size_t toPop = length; if (toPop > dataSize_) return 0; // Not enough data to pop 'length' if (toPop == 0) // Pops nothing but gets a pointer to the beginning of the buffer. return &buffer_[0] + start_; // Is the packet continuous across the internal buffer? if (buffer_.size() - start_ >= toPop) // yes, the packet is continuous in the internal buffer return &buffer_[0] + start_; else { // no, the packet spans then end and the beginning of the buffer // and it must be reconstructed. // Is the temporary internal outputBuffer large enough? if (outputBuffer_.size() < toPop) outputBuffer_.resize(toPop * 1.1); memcpy(&outputBuffer_[0], &buffer_[0] + start_, buffer_.size() - start_); memcpy(&outputBuffer_[0] + (buffer_.size() - start_), &buffer_[0], toPop - (buffer_.size() - start_)); //start_ = toPop - (buffer_.size() - start_); //dataSize_ -= toPop; return &outputBuffer_[0]; } } <|endoftext|>
<commit_before>#include <utils.h> #include <logger.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <iconv.h> #include <errno.h> #include <curl/curl.h> namespace newsbeuter { std::vector<std::string> utils::tokenize_quoted(const std::string& str, std::string delimiters) { std::vector<std::string> tokens; std::string::size_type last_pos = str.find_first_not_of(delimiters, 0); std::string::size_type pos = last_pos; while (pos != std::string::npos && last_pos != std::string::npos) { if (str[last_pos] == '#') // stop as soon as we found a comment break; if (str[last_pos] == '"') { ++last_pos; pos = last_pos; while (pos < str.length() && (str[pos] != '"' || str[pos-1] == '\\')) ++pos; if (pos >= str.length()) { pos = std::string::npos; std::string token; while (last_pos < str.length()) { if (str[last_pos] == '\\') { if (str[last_pos-1] == '\\') token.append("\\"); } else { if (str[last_pos-1] == '\\') { switch (str[last_pos]) { case 'n': token.append("\n"); break; case 'r': token.append("\r"); break; case 't': token.append("\t"); break; case '"': token.append("\""); break; case '\\': break; default: token.append(1, str[last_pos]); break; } } else { token.append(1, str[last_pos]); } } ++last_pos; } tokens.push_back(token); } else { std::string token; while (last_pos < pos) { if (str[last_pos] == '\\') { if (str[last_pos-1] == '\\') token.append("\\"); } else { if (str[last_pos-1] == '\\') { switch (str[last_pos]) { case 'n': token.append("\n"); break; case 'r': token.append("\r"); break; case 't': token.append("\t"); break; case '"': token.append("\""); break; case '\\': break; default: token.append(1, str[last_pos]); break; } } else { token.append(1, str[last_pos]); } } ++last_pos; } tokens.push_back(token); ++pos; } } else { pos = str.find_first_of(delimiters, last_pos); tokens.push_back(str.substr(last_pos, pos - last_pos)); } last_pos = str.find_first_not_of(delimiters, pos); } GetLogger().log(LOG_DEBUG, "utils::tokenize_quoted: tokenizing '%s' resulted in %u elements", str.c_str(), tokens.size()); return tokens; } std::vector<std::string> utils::tokenize(const std::string& str, std::string delimiters) { std::vector<std::string> tokens; std::string::size_type last_pos = str.find_first_not_of(delimiters, 0); std::string::size_type pos = str.find_first_of(delimiters, last_pos); while (std::string::npos != pos || std::string::npos != last_pos) { tokens.push_back(str.substr(last_pos, pos - last_pos)); last_pos = str.find_first_not_of(delimiters, pos); pos = str.find_first_of(delimiters, last_pos); } return tokens; } std::vector<std::string> utils::tokenize_spaced(const std::string& str, std::string delimiters) { std::vector<std::string> tokens; std::string::size_type last_pos = str.find_first_not_of(delimiters, 0); std::string::size_type pos = str.find_first_of(delimiters, last_pos); if (last_pos != 0) { tokens.push_back(std::string(" ")); } while (std::string::npos != pos || std::string::npos != last_pos) { tokens.push_back(str.substr(last_pos, pos - last_pos)); last_pos = str.find_first_not_of(delimiters, pos); if (last_pos > pos) tokens.push_back(std::string(" ")); pos = str.find_first_of(delimiters, last_pos); } return tokens; } std::vector<std::string> utils::tokenize_nl(const std::string& str, std::string delimiters) { std::vector<std::string> tokens; std::string::size_type last_pos = str.find_first_not_of(delimiters, 0); std::string::size_type pos = str.find_first_of(delimiters, last_pos); unsigned int i; GetLogger().log(LOG_DEBUG,"utils::tokenize_nl: last_pos = %u",last_pos); for (i=0;i<last_pos;++i) { tokens.push_back(std::string("\n")); } while (std::string::npos != pos || std::string::npos != last_pos) { tokens.push_back(str.substr(last_pos, pos - last_pos)); GetLogger().log(LOG_DEBUG,"utils::tokenize_nl: substr = %s", str.substr(last_pos, pos - last_pos).c_str()); last_pos = str.find_first_not_of(delimiters, pos); GetLogger().log(LOG_DEBUG,"utils::tokenize_nl: pos - last_pos = %u", last_pos - pos); for (i=0;last_pos != std::string::npos && pos != std::string::npos && i<(last_pos - pos);++i) { tokens.push_back(std::string("\n")); } pos = str.find_first_of(delimiters, last_pos); } return tokens; } void utils::remove_fs_lock(const std::string& lock_file) { GetLogger().log(LOG_DEBUG, "removed lockfile %s", lock_file.c_str()); ::unlink(lock_file.c_str()); } bool utils::try_fs_lock(const std::string& lock_file, pid_t & pid) { int fd; // pid == 0 indicates that something went majorly wrong during locking pid = 0; // first, we open (and possibly create) the lock file fd = ::open(lock_file.c_str(), O_RDWR | O_CREAT, 0600); if (fd < 0) return false; // then we lock it (T_LOCK returns immediately if locking is not possible) if (lockf(fd, F_TLOCK, 0) == 0) { char buf[32]; snprintf(buf, sizeof(buf), "%u", getpid()); // locking successful -> truncate file and write own PID into it ftruncate(fd, 0); write(fd, buf, strlen(buf)); close(fd); return true; } // locking was not successful -> read PID of locking process from it fd = ::open(lock_file.c_str(), O_RDONLY); if (fd >= 0) { char buf[32]; int len = read(fd, buf, sizeof(buf)-1); buf[len] = '\0'; sscanf(buf, "%u", &pid); close(fd); } return false; } std::string utils::convert_text(const std::string& text, const std::string& tocode, const std::string& fromcode) { std::string result; if (tocode == fromcode) return text; iconv_t cd = ::iconv_open((tocode + "//TRANSLIT").c_str(), fromcode.c_str()); if (cd == (iconv_t)-1) return result; size_t inbytesleft; size_t outbytesleft; /* * of all the Unix-like systems around there, only Linux/glibc seems to * come with a SuSv3-conforming iconv implementation. */ #ifndef __linux const char * inbufp; #else char * inbufp; #endif char outbuf[16]; char * outbufp = outbuf; outbytesleft = sizeof(outbuf); inbufp = const_cast<char *>(text.c_str()); // evil, but spares us some trouble inbytesleft = strlen(inbufp); do { char * old_outbufp = outbufp; int rc = ::iconv(cd, &inbufp, &inbytesleft, &outbufp, &outbytesleft); if (-1 == rc) { switch (errno) { case E2BIG: result.append(old_outbufp, outbufp - old_outbufp); outbufp = outbuf; outbytesleft = sizeof(outbuf); inbufp += strlen(inbufp) - inbytesleft; inbytesleft = strlen(inbufp); break; case EILSEQ: case EINVAL: result.append(old_outbufp, outbufp - old_outbufp); result.append("?"); GetLogger().log(LOG_DEBUG, "utils::convert_text: hit EILSEQ/EINVAL: result = `%s'", result.c_str()); inbufp += strlen(inbufp) - inbytesleft + 1; GetLogger().log(LOG_DEBUG, "utils::convert_text: new inbufp: `%s'", inbufp); inbytesleft = strlen(inbufp); break; } } else { result.append(old_outbufp, outbufp - old_outbufp); } } while (inbytesleft > 0); GetLogger().log(LOG_DEBUG, "utils::convert_text: before: %s", text.c_str()); GetLogger().log(LOG_DEBUG, "utils::convert_text: after: %s", result.c_str()); iconv_close(cd); return result; } std::string utils::get_command_output(const std::string& cmd) { FILE * f = popen(cmd.c_str(), "r"); std::string buf; char cbuf[1024]; size_t s; if (f) { while ((s = fread(cbuf, 1, sizeof(cbuf), f)) > 0) { buf.append(cbuf, s); } pclose(f); } return buf; } void utils::extract_filter(const std::string& line, std::string& filter, std::string& url) { std::string::size_type pos = line.find_first_of(":", 0); std::string::size_type pos1 = line.find_first_of(":", pos + 1); filter = line.substr(pos+1, pos1 - pos - 1); pos = pos1; url = line.substr(pos+1, line.length() - pos); GetLogger().log(LOG_DEBUG, "utils::extract_filter: %s -> filter: %s url: %s", line.c_str(), filter.c_str(), url.c_str()); } static size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp) { std::string * pbuf = (std::string *)userp; pbuf->append((const char *)buffer, size * nmemb); return size * nmemb; } std::string utils::retrieve_url(const std::string& url, const char * user_agent) { std::string buf; CURL * easyhandle = curl_easy_init(); if (user_agent) { curl_easy_setopt(easyhandle, CURLOPT_USERAGENT, user_agent); } curl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str()); curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data); curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &buf); curl_easy_perform(easyhandle); GetLogger().log(LOG_DEBUG, "utils::retrieve_url(%s): %s", url.c_str(), buf.c_str()); return buf; } std::string utils::run_filter(const std::string& cmd, const std::string& input) { std::string buf; int ipipe[2]; int opipe[2]; pipe(ipipe); pipe(opipe); int rc = fork(); switch (rc) { case -1: break; case 0: { // child: close(ipipe[1]); close(opipe[0]); dup2(ipipe[0], 0); dup2(opipe[1], 1); execl("/bin/sh", "/bin/sh", "-c", cmd.c_str(), NULL); exit(1); } break; default: { close(ipipe[0]); close(opipe[1]); write(ipipe[1], input.c_str(), input.length()); close(ipipe[1]); char cbuf[1024]; int rc; while ((rc = read(opipe[0], cbuf, sizeof(cbuf))) > 0) { buf.append(cbuf, rc); } close(opipe[0]); } break; } return buf; } } <commit_msg>Andreas Krennmair: oops, we must not close the file because otherwise we would lose the locking.<commit_after>#include <utils.h> #include <logger.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <iconv.h> #include <errno.h> #include <curl/curl.h> namespace newsbeuter { std::vector<std::string> utils::tokenize_quoted(const std::string& str, std::string delimiters) { std::vector<std::string> tokens; std::string::size_type last_pos = str.find_first_not_of(delimiters, 0); std::string::size_type pos = last_pos; while (pos != std::string::npos && last_pos != std::string::npos) { if (str[last_pos] == '#') // stop as soon as we found a comment break; if (str[last_pos] == '"') { ++last_pos; pos = last_pos; while (pos < str.length() && (str[pos] != '"' || str[pos-1] == '\\')) ++pos; if (pos >= str.length()) { pos = std::string::npos; std::string token; while (last_pos < str.length()) { if (str[last_pos] == '\\') { if (str[last_pos-1] == '\\') token.append("\\"); } else { if (str[last_pos-1] == '\\') { switch (str[last_pos]) { case 'n': token.append("\n"); break; case 'r': token.append("\r"); break; case 't': token.append("\t"); break; case '"': token.append("\""); break; case '\\': break; default: token.append(1, str[last_pos]); break; } } else { token.append(1, str[last_pos]); } } ++last_pos; } tokens.push_back(token); } else { std::string token; while (last_pos < pos) { if (str[last_pos] == '\\') { if (str[last_pos-1] == '\\') token.append("\\"); } else { if (str[last_pos-1] == '\\') { switch (str[last_pos]) { case 'n': token.append("\n"); break; case 'r': token.append("\r"); break; case 't': token.append("\t"); break; case '"': token.append("\""); break; case '\\': break; default: token.append(1, str[last_pos]); break; } } else { token.append(1, str[last_pos]); } } ++last_pos; } tokens.push_back(token); ++pos; } } else { pos = str.find_first_of(delimiters, last_pos); tokens.push_back(str.substr(last_pos, pos - last_pos)); } last_pos = str.find_first_not_of(delimiters, pos); } GetLogger().log(LOG_DEBUG, "utils::tokenize_quoted: tokenizing '%s' resulted in %u elements", str.c_str(), tokens.size()); return tokens; } std::vector<std::string> utils::tokenize(const std::string& str, std::string delimiters) { std::vector<std::string> tokens; std::string::size_type last_pos = str.find_first_not_of(delimiters, 0); std::string::size_type pos = str.find_first_of(delimiters, last_pos); while (std::string::npos != pos || std::string::npos != last_pos) { tokens.push_back(str.substr(last_pos, pos - last_pos)); last_pos = str.find_first_not_of(delimiters, pos); pos = str.find_first_of(delimiters, last_pos); } return tokens; } std::vector<std::string> utils::tokenize_spaced(const std::string& str, std::string delimiters) { std::vector<std::string> tokens; std::string::size_type last_pos = str.find_first_not_of(delimiters, 0); std::string::size_type pos = str.find_first_of(delimiters, last_pos); if (last_pos != 0) { tokens.push_back(std::string(" ")); } while (std::string::npos != pos || std::string::npos != last_pos) { tokens.push_back(str.substr(last_pos, pos - last_pos)); last_pos = str.find_first_not_of(delimiters, pos); if (last_pos > pos) tokens.push_back(std::string(" ")); pos = str.find_first_of(delimiters, last_pos); } return tokens; } std::vector<std::string> utils::tokenize_nl(const std::string& str, std::string delimiters) { std::vector<std::string> tokens; std::string::size_type last_pos = str.find_first_not_of(delimiters, 0); std::string::size_type pos = str.find_first_of(delimiters, last_pos); unsigned int i; GetLogger().log(LOG_DEBUG,"utils::tokenize_nl: last_pos = %u",last_pos); for (i=0;i<last_pos;++i) { tokens.push_back(std::string("\n")); } while (std::string::npos != pos || std::string::npos != last_pos) { tokens.push_back(str.substr(last_pos, pos - last_pos)); GetLogger().log(LOG_DEBUG,"utils::tokenize_nl: substr = %s", str.substr(last_pos, pos - last_pos).c_str()); last_pos = str.find_first_not_of(delimiters, pos); GetLogger().log(LOG_DEBUG,"utils::tokenize_nl: pos - last_pos = %u", last_pos - pos); for (i=0;last_pos != std::string::npos && pos != std::string::npos && i<(last_pos - pos);++i) { tokens.push_back(std::string("\n")); } pos = str.find_first_of(delimiters, last_pos); } return tokens; } void utils::remove_fs_lock(const std::string& lock_file) { GetLogger().log(LOG_DEBUG, "removed lockfile %s", lock_file.c_str()); ::unlink(lock_file.c_str()); } bool utils::try_fs_lock(const std::string& lock_file, pid_t & pid) { int fd; // pid == 0 indicates that something went majorly wrong during locking pid = 0; // first, we open (and possibly create) the lock file fd = ::open(lock_file.c_str(), O_RDWR | O_CREAT, 0600); if (fd < 0) return false; // then we lock it (T_LOCK returns immediately if locking is not possible) if (lockf(fd, F_TLOCK, 0) == 0) { char buf[32]; snprintf(buf, sizeof(buf), "%u", getpid()); // locking successful -> truncate file and write own PID into it ftruncate(fd, 0); write(fd, buf, strlen(buf)); return true; } // locking was not successful -> read PID of locking process from it fd = ::open(lock_file.c_str(), O_RDONLY); if (fd >= 0) { char buf[32]; int len = read(fd, buf, sizeof(buf)-1); buf[len] = '\0'; sscanf(buf, "%u", &pid); close(fd); } return false; } std::string utils::convert_text(const std::string& text, const std::string& tocode, const std::string& fromcode) { std::string result; if (tocode == fromcode) return text; iconv_t cd = ::iconv_open((tocode + "//TRANSLIT").c_str(), fromcode.c_str()); if (cd == (iconv_t)-1) return result; size_t inbytesleft; size_t outbytesleft; /* * of all the Unix-like systems around there, only Linux/glibc seems to * come with a SuSv3-conforming iconv implementation. */ #ifndef __linux const char * inbufp; #else char * inbufp; #endif char outbuf[16]; char * outbufp = outbuf; outbytesleft = sizeof(outbuf); inbufp = const_cast<char *>(text.c_str()); // evil, but spares us some trouble inbytesleft = strlen(inbufp); do { char * old_outbufp = outbufp; int rc = ::iconv(cd, &inbufp, &inbytesleft, &outbufp, &outbytesleft); if (-1 == rc) { switch (errno) { case E2BIG: result.append(old_outbufp, outbufp - old_outbufp); outbufp = outbuf; outbytesleft = sizeof(outbuf); inbufp += strlen(inbufp) - inbytesleft; inbytesleft = strlen(inbufp); break; case EILSEQ: case EINVAL: result.append(old_outbufp, outbufp - old_outbufp); result.append("?"); GetLogger().log(LOG_DEBUG, "utils::convert_text: hit EILSEQ/EINVAL: result = `%s'", result.c_str()); inbufp += strlen(inbufp) - inbytesleft + 1; GetLogger().log(LOG_DEBUG, "utils::convert_text: new inbufp: `%s'", inbufp); inbytesleft = strlen(inbufp); break; } } else { result.append(old_outbufp, outbufp - old_outbufp); } } while (inbytesleft > 0); GetLogger().log(LOG_DEBUG, "utils::convert_text: before: %s", text.c_str()); GetLogger().log(LOG_DEBUG, "utils::convert_text: after: %s", result.c_str()); iconv_close(cd); return result; } std::string utils::get_command_output(const std::string& cmd) { FILE * f = popen(cmd.c_str(), "r"); std::string buf; char cbuf[1024]; size_t s; if (f) { while ((s = fread(cbuf, 1, sizeof(cbuf), f)) > 0) { buf.append(cbuf, s); } pclose(f); } return buf; } void utils::extract_filter(const std::string& line, std::string& filter, std::string& url) { std::string::size_type pos = line.find_first_of(":", 0); std::string::size_type pos1 = line.find_first_of(":", pos + 1); filter = line.substr(pos+1, pos1 - pos - 1); pos = pos1; url = line.substr(pos+1, line.length() - pos); GetLogger().log(LOG_DEBUG, "utils::extract_filter: %s -> filter: %s url: %s", line.c_str(), filter.c_str(), url.c_str()); } static size_t my_write_data(void *buffer, size_t size, size_t nmemb, void *userp) { std::string * pbuf = (std::string *)userp; pbuf->append((const char *)buffer, size * nmemb); return size * nmemb; } std::string utils::retrieve_url(const std::string& url, const char * user_agent) { std::string buf; CURL * easyhandle = curl_easy_init(); if (user_agent) { curl_easy_setopt(easyhandle, CURLOPT_USERAGENT, user_agent); } curl_easy_setopt(easyhandle, CURLOPT_URL, url.c_str()); curl_easy_setopt(easyhandle, CURLOPT_WRITEFUNCTION, my_write_data); curl_easy_setopt(easyhandle, CURLOPT_WRITEDATA, &buf); curl_easy_perform(easyhandle); GetLogger().log(LOG_DEBUG, "utils::retrieve_url(%s): %s", url.c_str(), buf.c_str()); return buf; } std::string utils::run_filter(const std::string& cmd, const std::string& input) { std::string buf; int ipipe[2]; int opipe[2]; pipe(ipipe); pipe(opipe); int rc = fork(); switch (rc) { case -1: break; case 0: { // child: close(ipipe[1]); close(opipe[0]); dup2(ipipe[0], 0); dup2(opipe[1], 1); execl("/bin/sh", "/bin/sh", "-c", cmd.c_str(), NULL); exit(1); } break; default: { close(ipipe[0]); close(opipe[1]); write(ipipe[1], input.c_str(), input.length()); close(ipipe[1]); char cbuf[1024]; int rc; while ((rc = read(opipe[0], cbuf, sizeof(cbuf))) > 0) { buf.append(cbuf, rc); } close(opipe[0]); } break; } return buf; } } <|endoftext|>
<commit_before>/* vcflib C++ library for parsing and manipulating VCF files Copyright © 2010-2020 Erik Garrison Copyright © 2020 Pjotr Prins This software is published under the MIT License. See the LICENSE file. */ #include "Variant.h" #include "split.h" #include "cdflib.hpp" #include "pdflib.hpp" #include "var.hpp" #include <string> #include <iostream> #include <math.h> #include <cmath> #include <stdlib.h> #include <time.h> #include <stdio.h> #include <getopt.h> using namespace std; using namespace vcf; void printVersion(void){ cerr << "INFO: version 1.1.0 ; date: April 2014 ; author: Zev Kronenberg; email : zev.kronenberg@utah.edu " << endl; exit(1); } void printHelp(void){ cerr << endl << endl; cerr << "INFO: help" << endl; cerr << "INFO: description:" << endl; cerr << " xpEHH estimates haplotype decay between the target and background populations. Haplotypes are integrated " << endl; cerr << " until EHH in the target and background is less than 0.05. The score is the itegrated EHH (target) / integrated EHH (background). " << endl; cerr << " xpEHH does NOT integrate over genetic distance, as genetic maps are not availible for most non-model organisms. " << endl; cerr << "Output : 4 columns : " << endl; cerr << " 1. seqid " << endl; cerr << " 2. position " << endl; cerr << " 3. alllele frequency " << endl; cerr << " 4. EHH-alt " << endl; cerr << " 5. EHH-ref " << endl; cerr << " 6. xpEHH " << endl << endl; cerr << "INFO: xpEHH --target 0,1,2,3,4,5,6,7 --background 11,12,13,16,17,19,22 --file my.vcf " << endl; cerr << endl; cerr << "INFO: required: t,target -- argument: a zero based comma separated list of target individuals corrisponding to VCF columns " << endl; cerr << "INFO: required: b,background -- argument: a zero based comma separated list of background individuals corrisponding to VCF columns " << endl; cerr << "INFO: required: f,file -- argument: a properly formatted phased VCF file " << endl; cerr << "INFO: required: y,type -- argument: type of genotype likelihood: PL, GL or GP " << endl; cerr << "INFO: optional: r,region -- argument: a tabix compliant genomic range: seqid or seqid:start-end " << endl; cerr << endl; printVersion(); exit(1); } void clearHaplotypes(string haplotypes[][2], int ntarget){ for(int i= 0; i < ntarget; i++){ haplotypes[i][0].clear(); haplotypes[i][1].clear(); } } void loadIndices(map<int, int> & index, string set){ vector<string> indviduals = split(set, ","); vector<string>::iterator it = indviduals.begin(); for(; it != indviduals.end(); it++){ index[ atoi( (*it).c_str() ) ] = 1; } } void calc(string haplotypes[][2], int nhaps, vector<long int> pos, vector<double> afs, vector<int> & target, vector<int> & background, string seqid){ for(int snp = 0; snp < haplotypes[0][0].length(); snp++){ double ehhsat = 1; double ehhsab = 1; double ehhAT = 1 ; double ehhAB = 1 ; int start = snp; int end = snp; int core = snp; while( ehhAT > 0.001 && ehhAB > 0.001 ) { start -= 1; end += 1; if(start == -1){ break; } if(end == haplotypes[0][0].length() - 1){ break; } map<string , int> targetH, backgroundH; double sumrT = 0; double sumaT = 0; double sumrB = 0; double sumaB = 0; double nrefT = 0; double naltT = 0; double nrefB = 0; double naltB = 0; // hashing haplotypes into maps for both chr1 and chr2 target[][1 & 2] for(int i = 0; i < target.size(); i++){ targetH[ haplotypes[target[i]][0].substr(start, (end - start)) ]++; targetH[ haplotypes[target[i]][1].substr(start, (end - start)) ]++; } for(int i = 0; i < background.size(); i++){ backgroundH[ haplotypes[background[i]][0].substr(start, (end - start)) ]++; backgroundH[ haplotypes[background[i]][0].substr(start, (end - start)) ]++; } // interating over the target populations haplotypes for( map<string, int>::iterator th = targetH.begin(); th != targetH.end(); th++){ // grabbing the core SNP (*th).first.substr((end-start)/2, 1) == "1" if( (*th).first.substr((end-start)/2, 1) == "1"){ sumaT += r8_choose(th->second, 2); naltT += th->second; } else{ sumrT += r8_choose(th->second, 2); nrefT += th->second; } } // integrating over the background populations haplotypes for( map<string, int>::iterator bh = backgroundH.begin(); bh != backgroundH.end(); bh++){ // grabbing the core SNP (*bh).first.substr((end-start)/2, 1) == "1" if( (*bh).first.substr((end - start)/2 , 1) == "1"){ sumaB += r8_choose(bh->second, 2); naltB += bh->second; } else{ sumrB += r8_choose(bh->second, 2); nrefB += bh->second; } } ehhAT = sumaT / (r8_choose(naltT, 2)); ehhAB = sumaB / (r8_choose(naltB, 2)); ehhsat += ehhAT; ehhsab += ehhAB; } if(std::isnan(ehhsat) || std::isnan(ehhsab)){ continue; } cout << seqid << "\t" << pos[snp] << "\t" << afs[snp] << "\t" << ehhsat << "\t" << ehhsab << "\t" << log(ehhsat/ehhsab) << endl; } } double EHH(string haplotypes[][2], int nhaps){ map<string , int> hapcounts; for(int i = 0; i < nhaps; i++){ hapcounts[ haplotypes[i][0] ]++; hapcounts[ haplotypes[i][1] ]++; } double sum = 0; double nh = 0; for( map<string, int>::iterator it = hapcounts.begin(); it != hapcounts.end(); it++){ nh += it->second; sum += r8_choose(it->second, 2); } double max = (sum / r8_choose(nh, 2)); return max; } void loadPhased(string haplotypes[][2], genotype * pop, int ntarget){ int indIndex = 0; for(vector<string>::iterator ind = pop->gts.begin(); ind != pop->gts.end(); ind++){ string g = (*ind); vector< string > gs = split(g, "|"); haplotypes[indIndex][0].append(gs[0]); haplotypes[indIndex][1].append(gs[1]); indIndex += 1; } } int main(int argc, char** argv) { // set the random seed for MCMC srand((unsigned)time(NULL)); // the filename string filename = "NA"; // set region to scaffold string region = "NA"; // using vcflib; thanks to Erik Garrison VariantCallFile variantFile; // zero based index for the target and background indivudals map<int, int> it, ib; // deltaaf is the difference of allele frequency we bother to look at // ancestral state is set to zero by default int counts = 0; // phased int phased = 0; string type = "NA"; const struct option longopts[] = { {"version" , 0, 0, 'v'}, {"help" , 0, 0, 'h'}, {"file" , 1, 0, 'f'}, {"target" , 1, 0, 't'}, {"background", 1, 0, 'b'}, {"region" , 1, 0, 'r'}, {"type" , 1, 0, 'y'}, {0,0,0,0} }; int findex; int iarg=0; while(iarg != -1) { iarg = getopt_long(argc, argv, "y:r:t:b:f:hv", longopts, &findex); switch (iarg) { case 'h': printHelp(); case 'v': printVersion(); case 'y': type = optarg; break; case 't': loadIndices(it, optarg); cerr << "INFO: there are " << it.size() << " individuals in the target" << endl; cerr << "INFO: target ids: " << optarg << endl; break; case 'b': loadIndices(ib, optarg); cerr << "INFO: there are " << ib.size() << " individuals in the background" << endl; cerr << "INFO: background ids: " << optarg << endl; break; case 'f': cerr << "INFO: file: " << optarg << endl; filename = optarg; break; case 'r': cerr << "INFO: set seqid region to : " << optarg << endl; region = optarg; break; default: break; } } map<string, int> okayGenotypeLikelihoods; okayGenotypeLikelihoods["PL"] = 1; okayGenotypeLikelihoods["GL"] = 1; okayGenotypeLikelihoods["GP"] = 1; okayGenotypeLikelihoods["GT"] = 1; if(type == "NA"){ cerr << "FATAL: failed to specify genotype likelihood format : PL or GL" << endl; printHelp(); return 1; } if(okayGenotypeLikelihoods.find(type) == okayGenotypeLikelihoods.end()){ cerr << "FATAL: genotype likelihood is incorrectly formatted, only use: PL or GL" << endl; printHelp(); return 1; } if(filename == "NA"){ cerr << "FATAL: did not specify a file" << endl; printHelp(); return(1); } variantFile.open(filename); if(region != "NA"){ if(! variantFile.setRegion(region)){ cerr <<"FATAL: unable to set region" << endl; return 1; } } if (!variantFile.is_open()) { return 1; } Variant var(variantFile); vector<string> samples = variantFile.sampleNames; int nsamples = samples.size(); vector<int> target_h, background_h; int index, indexi = 0; for(vector<string>::iterator samp = samples.begin(); samp != samples.end(); samp++){ string sampleName = (*samp); if(it.find(index) != it.end() ){ target_h.push_back(indexi); indexi++; } if(ib.find(index) != ib.end()){ background_h.push_back(indexi); indexi++; } index++; } vector<long int> positions; vector<double> afs; string haplotypes [nsamples][2]; string currentSeqid = "NA"; while (variantFile.getNextVariant(var)) { if(!var.isPhased()){ cerr <<"FATAL: Found an unphased variant. All genotypes must be phased!" << endl; printHelp(); return(1); } if(var.alt.size() > 1){ continue; } if(currentSeqid != var.sequenceName){ if(haplotypes[0][0].length() > 10){ calc(haplotypes, nsamples, positions, afs, target_h, background_h, currentSeqid); } clearHaplotypes(haplotypes, nsamples); positions.clear(); currentSeqid = var.sequenceName; afs.clear(); } vector < map< string, vector<string> > > target, background, total; int sindex = 0; for(int nsamp = 0; nsamp < nsamples; nsamp++){ map<string, vector<string> > sample = var.samples[ samples[nsamp]]; if(it.find(sindex) != it.end() ){ target.push_back(sample); total.push_back(sample); } if(ib.find(sindex) != ib.end()){ background.push_back(sample); total.push_back(sample); } sindex += 1; } unique_ptr<genotype> populationTarget ; unique_ptr<genotype> populationBackground; unique_ptr<genotype> populationTotal ; if(type == "PL"){ populationTarget = makeUnique<pl>(); populationBackground = makeUnique<pl>(); populationTotal = makeUnique<pl>(); } if(type == "GL"){ populationTarget = makeUnique<gl>(); populationBackground = makeUnique<gl>(); populationTotal = makeUnique<gl>(); } if(type == "GP"){ populationTarget = makeUnique<gp>(); populationBackground = makeUnique<gp>(); populationTotal = makeUnique<gp>(); } if(type == "GT"){ populationTarget = makeUnique<gt>(); populationBackground = makeUnique<gt>(); populationTotal = makeUnique<gt>(); } populationTarget->loadPop(target, var.sequenceName, var.position); populationBackground->loadPop(background, var.sequenceName, var.position); populationTotal->loadPop(total, var.sequenceName, var.position); // if(populationTotal->af > 0.99 || populationTotal->af < 0.01){ // // // continue; // } afs.push_back(populationTotal->af); positions.push_back(var.position); loadPhased(haplotypes, populationTotal, nsamples); } calc(haplotypes, nsamples, positions, afs, target_h, background_h, currentSeqid); return 0; } <commit_msg>xpEHH: initialize index when iterating over samples.<commit_after>/* vcflib C++ library for parsing and manipulating VCF files Copyright © 2010-2020 Erik Garrison Copyright © 2020 Pjotr Prins This software is published under the MIT License. See the LICENSE file. */ #include "Variant.h" #include "split.h" #include "cdflib.hpp" #include "pdflib.hpp" #include "var.hpp" #include <string> #include <iostream> #include <math.h> #include <cmath> #include <stdlib.h> #include <time.h> #include <stdio.h> #include <getopt.h> using namespace std; using namespace vcf; void printVersion(void){ cerr << "INFO: version 1.1.0 ; date: April 2014 ; author: Zev Kronenberg; email : zev.kronenberg@utah.edu " << endl; exit(1); } void printHelp(void){ cerr << endl << endl; cerr << "INFO: help" << endl; cerr << "INFO: description:" << endl; cerr << " xpEHH estimates haplotype decay between the target and background populations. Haplotypes are integrated " << endl; cerr << " until EHH in the target and background is less than 0.05. The score is the itegrated EHH (target) / integrated EHH (background). " << endl; cerr << " xpEHH does NOT integrate over genetic distance, as genetic maps are not availible for most non-model organisms. " << endl; cerr << "Output : 4 columns : " << endl; cerr << " 1. seqid " << endl; cerr << " 2. position " << endl; cerr << " 3. alllele frequency " << endl; cerr << " 4. EHH-alt " << endl; cerr << " 5. EHH-ref " << endl; cerr << " 6. xpEHH " << endl << endl; cerr << "INFO: xpEHH --target 0,1,2,3,4,5,6,7 --background 11,12,13,16,17,19,22 --file my.vcf " << endl; cerr << endl; cerr << "INFO: required: t,target -- argument: a zero based comma separated list of target individuals corrisponding to VCF columns " << endl; cerr << "INFO: required: b,background -- argument: a zero based comma separated list of background individuals corrisponding to VCF columns " << endl; cerr << "INFO: required: f,file -- argument: a properly formatted phased VCF file " << endl; cerr << "INFO: required: y,type -- argument: type of genotype likelihood: PL, GL or GP " << endl; cerr << "INFO: optional: r,region -- argument: a tabix compliant genomic range: seqid or seqid:start-end " << endl; cerr << endl; printVersion(); exit(1); } void clearHaplotypes(string haplotypes[][2], int ntarget){ for(int i= 0; i < ntarget; i++){ haplotypes[i][0].clear(); haplotypes[i][1].clear(); } } void loadIndices(map<int, int> & index, string set){ vector<string> indviduals = split(set, ","); vector<string>::iterator it = indviduals.begin(); for(; it != indviduals.end(); it++){ index[ atoi( (*it).c_str() ) ] = 1; } } void calc(string haplotypes[][2], int nhaps, vector<long int> pos, vector<double> afs, vector<int> & target, vector<int> & background, string seqid){ for(int snp = 0; snp < haplotypes[0][0].length(); snp++){ double ehhsat = 1; double ehhsab = 1; double ehhAT = 1 ; double ehhAB = 1 ; int start = snp; int end = snp; int core = snp; while( ehhAT > 0.001 && ehhAB > 0.001 ) { start -= 1; end += 1; if(start == -1){ break; } if(end == haplotypes[0][0].length() - 1){ break; } map<string , int> targetH, backgroundH; double sumrT = 0; double sumaT = 0; double sumrB = 0; double sumaB = 0; double nrefT = 0; double naltT = 0; double nrefB = 0; double naltB = 0; // hashing haplotypes into maps for both chr1 and chr2 target[][1 & 2] for(int i = 0; i < target.size(); i++){ targetH[ haplotypes[target[i]][0].substr(start, (end - start)) ]++; targetH[ haplotypes[target[i]][1].substr(start, (end - start)) ]++; } for(int i = 0; i < background.size(); i++){ backgroundH[ haplotypes[background[i]][0].substr(start, (end - start)) ]++; backgroundH[ haplotypes[background[i]][0].substr(start, (end - start)) ]++; } // interating over the target populations haplotypes for( map<string, int>::iterator th = targetH.begin(); th != targetH.end(); th++){ // grabbing the core SNP (*th).first.substr((end-start)/2, 1) == "1" if( (*th).first.substr((end-start)/2, 1) == "1"){ sumaT += r8_choose(th->second, 2); naltT += th->second; } else{ sumrT += r8_choose(th->second, 2); nrefT += th->second; } } // integrating over the background populations haplotypes for( map<string, int>::iterator bh = backgroundH.begin(); bh != backgroundH.end(); bh++){ // grabbing the core SNP (*bh).first.substr((end-start)/2, 1) == "1" if( (*bh).first.substr((end - start)/2 , 1) == "1"){ sumaB += r8_choose(bh->second, 2); naltB += bh->second; } else{ sumrB += r8_choose(bh->second, 2); nrefB += bh->second; } } ehhAT = sumaT / (r8_choose(naltT, 2)); ehhAB = sumaB / (r8_choose(naltB, 2)); ehhsat += ehhAT; ehhsab += ehhAB; } if(std::isnan(ehhsat) || std::isnan(ehhsab)){ continue; } cout << seqid << "\t" << pos[snp] << "\t" << afs[snp] << "\t" << ehhsat << "\t" << ehhsab << "\t" << log(ehhsat/ehhsab) << endl; } } double EHH(string haplotypes[][2], int nhaps){ map<string , int> hapcounts; for(int i = 0; i < nhaps; i++){ hapcounts[ haplotypes[i][0] ]++; hapcounts[ haplotypes[i][1] ]++; } double sum = 0; double nh = 0; for( map<string, int>::iterator it = hapcounts.begin(); it != hapcounts.end(); it++){ nh += it->second; sum += r8_choose(it->second, 2); } double max = (sum / r8_choose(nh, 2)); return max; } void loadPhased(string haplotypes[][2], genotype * pop, int ntarget){ int indIndex = 0; for(vector<string>::iterator ind = pop->gts.begin(); ind != pop->gts.end(); ind++){ string g = (*ind); vector< string > gs = split(g, "|"); haplotypes[indIndex][0].append(gs[0]); haplotypes[indIndex][1].append(gs[1]); indIndex += 1; } } int main(int argc, char** argv) { // set the random seed for MCMC srand((unsigned)time(NULL)); // the filename string filename = "NA"; // set region to scaffold string region = "NA"; // using vcflib; thanks to Erik Garrison VariantCallFile variantFile; // zero based index for the target and background indivudals map<int, int> it, ib; // deltaaf is the difference of allele frequency we bother to look at // ancestral state is set to zero by default int counts = 0; // phased int phased = 0; string type = "NA"; const struct option longopts[] = { {"version" , 0, 0, 'v'}, {"help" , 0, 0, 'h'}, {"file" , 1, 0, 'f'}, {"target" , 1, 0, 't'}, {"background", 1, 0, 'b'}, {"region" , 1, 0, 'r'}, {"type" , 1, 0, 'y'}, {0,0,0,0} }; int findex; int iarg=0; while(iarg != -1) { iarg = getopt_long(argc, argv, "y:r:t:b:f:hv", longopts, &findex); switch (iarg) { case 'h': printHelp(); case 'v': printVersion(); case 'y': type = optarg; break; case 't': loadIndices(it, optarg); cerr << "INFO: there are " << it.size() << " individuals in the target" << endl; cerr << "INFO: target ids: " << optarg << endl; break; case 'b': loadIndices(ib, optarg); cerr << "INFO: there are " << ib.size() << " individuals in the background" << endl; cerr << "INFO: background ids: " << optarg << endl; break; case 'f': cerr << "INFO: file: " << optarg << endl; filename = optarg; break; case 'r': cerr << "INFO: set seqid region to : " << optarg << endl; region = optarg; break; default: break; } } map<string, int> okayGenotypeLikelihoods; okayGenotypeLikelihoods["PL"] = 1; okayGenotypeLikelihoods["GL"] = 1; okayGenotypeLikelihoods["GP"] = 1; okayGenotypeLikelihoods["GT"] = 1; if(type == "NA"){ cerr << "FATAL: failed to specify genotype likelihood format : PL or GL" << endl; printHelp(); return 1; } if(okayGenotypeLikelihoods.find(type) == okayGenotypeLikelihoods.end()){ cerr << "FATAL: genotype likelihood is incorrectly formatted, only use: PL or GL" << endl; printHelp(); return 1; } if(filename == "NA"){ cerr << "FATAL: did not specify a file" << endl; printHelp(); return(1); } variantFile.open(filename); if(region != "NA"){ if(! variantFile.setRegion(region)){ cerr <<"FATAL: unable to set region" << endl; return 1; } } if (!variantFile.is_open()) { return 1; } Variant var(variantFile); vector<string> samples = variantFile.sampleNames; int nsamples = samples.size(); vector<int> target_h, background_h; int index = 0, indexi = 0; for(vector<string>::iterator samp = samples.begin(); samp != samples.end(); samp++){ string sampleName = (*samp); if(it.find(index) != it.end() ){ target_h.push_back(indexi); indexi++; } if(ib.find(index) != ib.end()){ background_h.push_back(indexi); indexi++; } index++; } vector<long int> positions; vector<double> afs; string haplotypes [nsamples][2]; string currentSeqid = "NA"; while (variantFile.getNextVariant(var)) { if(!var.isPhased()){ cerr <<"FATAL: Found an unphased variant. All genotypes must be phased!" << endl; printHelp(); return(1); } if(var.alt.size() > 1){ continue; } if(currentSeqid != var.sequenceName){ if(haplotypes[0][0].length() > 10){ calc(haplotypes, nsamples, positions, afs, target_h, background_h, currentSeqid); } clearHaplotypes(haplotypes, nsamples); positions.clear(); currentSeqid = var.sequenceName; afs.clear(); } vector < map< string, vector<string> > > target, background, total; int sindex = 0; for(int nsamp = 0; nsamp < nsamples; nsamp++){ map<string, vector<string> > sample = var.samples[ samples[nsamp]]; if(it.find(sindex) != it.end() ){ target.push_back(sample); total.push_back(sample); } if(ib.find(sindex) != ib.end()){ background.push_back(sample); total.push_back(sample); } sindex += 1; } unique_ptr<genotype> populationTarget ; unique_ptr<genotype> populationBackground; unique_ptr<genotype> populationTotal ; if(type == "PL"){ populationTarget = makeUnique<pl>(); populationBackground = makeUnique<pl>(); populationTotal = makeUnique<pl>(); } if(type == "GL"){ populationTarget = makeUnique<gl>(); populationBackground = makeUnique<gl>(); populationTotal = makeUnique<gl>(); } if(type == "GP"){ populationTarget = makeUnique<gp>(); populationBackground = makeUnique<gp>(); populationTotal = makeUnique<gp>(); } if(type == "GT"){ populationTarget = makeUnique<gt>(); populationBackground = makeUnique<gt>(); populationTotal = makeUnique<gt>(); } populationTarget->loadPop(target, var.sequenceName, var.position); populationBackground->loadPop(background, var.sequenceName, var.position); populationTotal->loadPop(total, var.sequenceName, var.position); // if(populationTotal->af > 0.99 || populationTotal->af < 0.01){ // // // continue; // } afs.push_back(populationTotal->af); positions.push_back(var.position); loadPhased(haplotypes, populationTotal, nsamples); } calc(haplotypes, nsamples, positions, afs, target_h, background_h, currentSeqid); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ndgrf.hxx,v $ * * $Revision: 1.17 $ * * last change: $Author: hr $ $Date: 2005-09-28 11:03: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 _NDGRF_HXX #define _NDGRF_HXX #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _LNKBASE_HXX //autogen #include <sfx2/lnkbase.hxx> #endif #ifndef _GRFMGR_HXX //autogen #include <goodies/grfmgr.hxx> #endif #ifndef _NDNOTXT_HXX #include <ndnotxt.hxx> #endif // --> OD, MAV 2005-08-17 #i53025# #ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_ #include <com/sun/star/embed/XStorage.hpp> #endif // <-- class SwGrfFmtColl; class SwDoc; class GraphicAttr; class SvStorage; // -------------------- // SwGrfNode // -------------------- class SwGrfNode: public SwNoTxtNode { friend long GrfNodeChanged( void*, void* ); friend class SwNodes; friend class SwGrfFrm; GraphicObject aGrfObj; ::sfx2::SvBaseLinkRef refLink; // falls Grafik nur als Link, dann Pointer gesetzt Size nGrfSize; // String aStrmName; // SW3: Name des Storage-Streams fuer Embedded String aNewStrmName; // SW3/XML: new stream name (either SW3 stream // name or package url) String aLowResGrf; // HTML: LowRes Grafik (Ersatzdarstellung bis // die normale (HighRes) geladen ist. BOOL bTransparentFlagValid :1; BOOL bInSwapIn :1; BOOL bGrafikArrived :1; BOOL bChgTwipSize :1; BOOL bChgTwipSizeFromPixel :1; BOOL bLoadLowResGrf :1; BOOL bFrameInPaint :1; //Um Start-/EndActions im Paint (ueber //SwapIn zu verhindern. BOOL bScaleImageMap :1; //Image-Map in SetTwipSize skalieren SwGrfNode( const SwNodeIndex& rWhere, const String& rGrfName, const String& rFltName, const Graphic* pGraphic, SwGrfFmtColl* pGrfColl, SwAttrSet* pAutoAttr = 0 ); // Ctor fuer Einlesen (SW/G) ohne Grafik SwGrfNode( const SwNodeIndex& rWhere, const String& rGrfName, const String& rFltName, SwGrfFmtColl* pGrfColl, SwAttrSet* pAutoAttr = 0 ); SwGrfNode( const SwNodeIndex& rWhere, const GraphicObject& rGrfObj, SwGrfFmtColl* pGrfColl, SwAttrSet* pAutoAttr = 0 ); void InsertLink( const String& rGrfName, const String& rFltName ); BOOL ImportGraphic( SvStream& rStrm ); BOOL HasStreamName() const { return aGrfObj.HasUserData(); } // --> OD 2005-05-04 #i48434# - adjust return type and rename method to // indicate that its an private one. // --> OD 2005-08-17 #i53025# // embedded graphic stream couldn't be inside a 3.1 - 5.2 storage any more. // Thus, return value isn't needed any more. void _GetStreamStorageNames( String& rStrmName, String& rStgName ) const; // <-- void DelStreamName(); DECL_LINK( SwapGraphic, GraphicObject* ); /** helper method to determine stream for the embedded graphic. OD 2005-05-04 #i48434# Important note: caller of this method has to handle the thrown exceptions OD, MAV 2005-08-17 #i53025# Storage, which should contain the stream of the embedded graphic, is provided via parameter. Otherwise the returned stream will be closed after the the method returns, because its parent stream is closed and deleted. Proposed name of embedded graphic stream is also provided by parameter. @author OD @param _refPics input parameter - reference to storage, which should contain the embedded graphic stream. @param _aStrmName input parameter - proposed name of the embedded graphic stream. @return SvStream* new created stream of the embedded graphic, which has to be destroyed after its usage. Could be NULL, if the stream isn't found. */ SvStream* _GetStreamForEmbedGrf( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _refPics, String& _aStrmName ) const; /** helper method to get a substorage of the document storage for readonly access. OD, MAV 2005-08-17 #i53025# A substorage with the specified name will be opened readonly. If the provided name is empty the root storage will be returned. @param _aStgName input parameter - name of substorage. Can be empty. @return XStorage reference to substorage or the root storage */ ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > _GetDocSubstorageOrRoot( const String& aStgName ) const; public: virtual ~SwGrfNode(); const Graphic& GetGrf() const { return aGrfObj.GetGraphic(); } const GraphicObject& GetGrfObj() const { return aGrfObj; } GraphicObject& GetGrfObj() { return aGrfObj; } virtual SwCntntNode *SplitNode( const SwPosition & ); virtual Size GetTwipSize() const; #ifndef _FESHVIEW_ONLY_INLINE_NEEDED void SetTwipSize( const Size& rSz ); BOOL IsTransparent() const; inline BOOL IsAnimated() const { return aGrfObj.IsAnimated(); } inline BOOL IsChgTwipSize() const { return bChgTwipSize; } inline BOOL IsChgTwipSizeFromPixel() const { return bChgTwipSizeFromPixel; } inline void SetChgTwipSize( BOOL b, BOOL bFromPx=FALSE ) { bChgTwipSize = b; bChgTwipSizeFromPixel = bFromPx; } inline BOOL IsGrafikArrived() const { return bGrafikArrived; } inline void SetGrafikArrived( BOOL b ) { bGrafikArrived = b; } inline BOOL IsFrameInPaint() const { return bFrameInPaint; } inline void SetFrameInPaint( BOOL b ) { bFrameInPaint = b; } inline BOOL IsScaleImageMap() const { return bScaleImageMap; } inline void SetScaleImageMap( BOOL b ) { bScaleImageMap = b; } // alles fuers Laden der LowRes-Grafiken inline BOOL IsLoadLowResGrf() const { return bLoadLowResGrf; } inline void SetLoadLowResGrf( BOOL b ) { bLoadLowResGrf = b; } const String& GetLowResGrfName() const { return aLowResGrf; } void SetLowResGrfName( const String& r ) { aLowResGrf = r; } #endif // steht in ndcopy.cxx virtual SwCntntNode* MakeCopy( SwDoc*, const SwNodeIndex& ) const; #ifndef _FESHVIEW_ONLY_INLINE_NEEDED // erneutes Einlesen, falls Graphic nicht Ok ist. Die // aktuelle wird durch die neue ersetzt. BOOL ReRead( const String& rGrfName, const String& rFltName, const Graphic* pGraphic = 0, const GraphicObject* pGrfObj = 0, BOOL bModify = TRUE ); // Laden der Grafik unmittelbar vor der Anzeige short SwapIn( BOOL bWaitForData = FALSE ); // Entfernen der Grafik, um Speicher freizugeben short SwapOut(); // Schreiben der Grafik BOOL StoreGraphics( SvStorage* pDocStg = NULL ); // Zugriff auf den Storage-Streamnamen String GetStreamName() const; void SetStreamName( const String& r ) { aGrfObj.SetUserData( r ); } void SetNewStreamName( const String& r ) { aNewStrmName = r; } void SaveCompleted( BOOL bClear ); // is this node selected by any shell? BOOL IsSelected() const; #endif // Der Grafik sagen, dass sich der Node im Undobereich befindet virtual BOOL SavePersistentData(); virtual BOOL RestorePersistentData(); #ifndef _FESHVIEW_ONLY_INLINE_NEEDED // Abfrage der Link-Daten BOOL IsGrfLink() const { return refLink.Is(); } inline BOOL IsLinkedFile() const; inline BOOL IsLinkedDDE() const; ::sfx2::SvBaseLinkRef GetLink() const { return refLink; } BOOL GetFileFilterNms( String* pFileNm, String* pFilterNm ) const; void ReleaseLink(); // Prioritaet beim Laden der Grafik setzen. Geht nur, wenn der Link // ein FileObject gesetzt hat void SetTransferPriority( USHORT nPrio ); // Skalieren einer Image-Map: Die Image-Map wird um den Faktor // zwischen Grafik-Groesse und Rahmen-Groesse vergroessert/verkleinert void ScaleImageMap(); // returns the with our graphic attributes filled Graphic-Attr-Structure GraphicAttr& GetGraphicAttr( GraphicAttr&, const SwFrm* pFrm ) const; #endif }; // ---------------------------------------------------------------------- // Inline Metoden aus Node.hxx - erst hier ist der TxtNode bekannt !! inline SwGrfNode *SwNode::GetGrfNode() { return ND_GRFNODE == nNodeType ? (SwGrfNode*)this : 0; } inline const SwGrfNode *SwNode::GetGrfNode() const { return ND_GRFNODE == nNodeType ? (const SwGrfNode*)this : 0; } #ifndef _FESHVIEW_ONLY_INLINE_NEEDED inline BOOL SwGrfNode::IsLinkedFile() const { return refLink.Is() && OBJECT_CLIENT_GRF == refLink->GetObjType(); } inline BOOL SwGrfNode::IsLinkedDDE() const { return refLink.Is() && OBJECT_CLIENT_DDE == refLink->GetObjType(); } #endif #endif <commit_msg>INTEGRATION: CWS writercorehandoff (1.14.110); FILE MERGED 2005/10/25 08:22:14 tra 1.14.110.4: RESYNC: (1.16-1.17); FILE MERGED 2005/09/13 11:42:14 tra 1.14.110.3: RESYNC: (1.15-1.16); FILE MERGED 2005/07/11 05:31:28 tra 1.14.110.2: #i50348#merge conflicts resolved 2005/06/07 14:10:05 fme 1.14.110.1: #i50348# General cleanup - removed unused header files, functions, members, declarations etc.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ndgrf.hxx,v $ * * $Revision: 1.18 $ * * last change: $Author: hr $ $Date: 2006-08-14 15:26:58 $ * * 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 _NDGRF_HXX #define _NDGRF_HXX #ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_ #include <com/sun/star/io/XInputStream.hpp> #endif #ifndef _LNKBASE_HXX //autogen #include <sfx2/lnkbase.hxx> #endif #ifndef _GRFMGR_HXX //autogen #include <goodies/grfmgr.hxx> #endif #ifndef _NDNOTXT_HXX #include <ndnotxt.hxx> #endif // --> OD, MAV 2005-08-17 #i53025# #ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_ #include <com/sun/star/embed/XStorage.hpp> #endif // <-- class SwGrfFmtColl; class SwDoc; class GraphicAttr; class SvStorage; // -------------------- // SwGrfNode // -------------------- class SwGrfNode: public SwNoTxtNode { friend long GrfNodeChanged( void*, void* ); friend class SwNodes; friend class SwGrfFrm; GraphicObject aGrfObj; ::sfx2::SvBaseLinkRef refLink; // falls Grafik nur als Link, dann Pointer gesetzt Size nGrfSize; // String aStrmName; // SW3: Name des Storage-Streams fuer Embedded String aNewStrmName; // SW3/XML: new stream name (either SW3 stream // name or package url) String aLowResGrf; // HTML: LowRes Grafik (Ersatzdarstellung bis // die normale (HighRes) geladen ist. BOOL bTransparentFlagValid :1; BOOL bInSwapIn :1; BOOL bGrafikArrived :1; BOOL bChgTwipSize :1; BOOL bChgTwipSizeFromPixel :1; BOOL bLoadLowResGrf :1; BOOL bFrameInPaint :1; //Um Start-/EndActions im Paint (ueber //SwapIn zu verhindern. BOOL bScaleImageMap :1; //Image-Map in SetTwipSize skalieren SwGrfNode( const SwNodeIndex& rWhere, const String& rGrfName, const String& rFltName, const Graphic* pGraphic, SwGrfFmtColl* pGrfColl, SwAttrSet* pAutoAttr = 0 ); // Ctor fuer Einlesen (SW/G) ohne Grafik SwGrfNode( const SwNodeIndex& rWhere, const String& rGrfName, const String& rFltName, SwGrfFmtColl* pGrfColl, SwAttrSet* pAutoAttr = 0 ); SwGrfNode( const SwNodeIndex& rWhere, const GraphicObject& rGrfObj, SwGrfFmtColl* pGrfColl, SwAttrSet* pAutoAttr = 0 ); void InsertLink( const String& rGrfName, const String& rFltName ); BOOL ImportGraphic( SvStream& rStrm ); BOOL HasStreamName() const { return aGrfObj.HasUserData(); } // --> OD 2005-05-04 #i48434# - adjust return type and rename method to // indicate that its an private one. // --> OD 2005-08-17 #i53025# // embedded graphic stream couldn't be inside a 3.1 - 5.2 storage any more. // Thus, return value isn't needed any more. void _GetStreamStorageNames( String& rStrmName, String& rStgName ) const; // <-- void DelStreamName(); DECL_LINK( SwapGraphic, GraphicObject* ); /** helper method to determine stream for the embedded graphic. OD 2005-05-04 #i48434# Important note: caller of this method has to handle the thrown exceptions OD, MAV 2005-08-17 #i53025# Storage, which should contain the stream of the embedded graphic, is provided via parameter. Otherwise the returned stream will be closed after the the method returns, because its parent stream is closed and deleted. Proposed name of embedded graphic stream is also provided by parameter. @author OD @param _refPics input parameter - reference to storage, which should contain the embedded graphic stream. @param _aStrmName input parameter - proposed name of the embedded graphic stream. @return SvStream* new created stream of the embedded graphic, which has to be destroyed after its usage. Could be NULL, if the stream isn't found. */ SvStream* _GetStreamForEmbedGrf( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _refPics, String& _aStrmName ) const; /** helper method to get a substorage of the document storage for readonly access. OD, MAV 2005-08-17 #i53025# A substorage with the specified name will be opened readonly. If the provided name is empty the root storage will be returned. @param _aStgName input parameter - name of substorage. Can be empty. @return XStorage reference to substorage or the root storage */ ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > _GetDocSubstorageOrRoot( const String& aStgName ) const; public: virtual ~SwGrfNode(); const Graphic& GetGrf() const { return aGrfObj.GetGraphic(); } const GraphicObject& GetGrfObj() const { return aGrfObj; } GraphicObject& GetGrfObj() { return aGrfObj; } virtual SwCntntNode *SplitNode( const SwPosition & ); virtual Size GetTwipSize() const; #ifndef _FESHVIEW_ONLY_INLINE_NEEDED void SetTwipSize( const Size& rSz ); BOOL IsTransparent() const; inline BOOL IsAnimated() const { return aGrfObj.IsAnimated(); } inline BOOL IsChgTwipSize() const { return bChgTwipSize; } inline BOOL IsChgTwipSizeFromPixel() const { return bChgTwipSizeFromPixel; } inline void SetChgTwipSize( BOOL b, BOOL bFromPx=FALSE ) { bChgTwipSize = b; bChgTwipSizeFromPixel = bFromPx; } inline BOOL IsGrafikArrived() const { return bGrafikArrived; } inline void SetGrafikArrived( BOOL b ) { bGrafikArrived = b; } inline BOOL IsFrameInPaint() const { return bFrameInPaint; } inline void SetFrameInPaint( BOOL b ) { bFrameInPaint = b; } inline BOOL IsScaleImageMap() const { return bScaleImageMap; } inline void SetScaleImageMap( BOOL b ) { bScaleImageMap = b; } #endif // steht in ndcopy.cxx virtual SwCntntNode* MakeCopy( SwDoc*, const SwNodeIndex& ) const; #ifndef _FESHVIEW_ONLY_INLINE_NEEDED // erneutes Einlesen, falls Graphic nicht Ok ist. Die // aktuelle wird durch die neue ersetzt. BOOL ReRead( const String& rGrfName, const String& rFltName, const Graphic* pGraphic = 0, const GraphicObject* pGrfObj = 0, BOOL bModify = TRUE ); // Laden der Grafik unmittelbar vor der Anzeige short SwapIn( BOOL bWaitForData = FALSE ); // Entfernen der Grafik, um Speicher freizugeben short SwapOut(); // Schreiben der Grafik BOOL StoreGraphics( SvStorage* pDocStg = NULL ); // Zugriff auf den Storage-Streamnamen String GetStreamName() const; void SetStreamName( const String& r ) { aGrfObj.SetUserData( r ); } void SetNewStreamName( const String& r ) { aNewStrmName = r; } void SaveCompleted( BOOL bClear ); // is this node selected by any shell? BOOL IsSelected() const; #endif // Der Grafik sagen, dass sich der Node im Undobereich befindet virtual BOOL SavePersistentData(); virtual BOOL RestorePersistentData(); #ifndef _FESHVIEW_ONLY_INLINE_NEEDED // Abfrage der Link-Daten BOOL IsGrfLink() const { return refLink.Is(); } inline BOOL IsLinkedFile() const; inline BOOL IsLinkedDDE() const; ::sfx2::SvBaseLinkRef GetLink() const { return refLink; } BOOL GetFileFilterNms( String* pFileNm, String* pFilterNm ) const; void ReleaseLink(); // Prioritaet beim Laden der Grafik setzen. Geht nur, wenn der Link // ein FileObject gesetzt hat void SetTransferPriority( USHORT nPrio ); // Skalieren einer Image-Map: Die Image-Map wird um den Faktor // zwischen Grafik-Groesse und Rahmen-Groesse vergroessert/verkleinert void ScaleImageMap(); // returns the with our graphic attributes filled Graphic-Attr-Structure GraphicAttr& GetGraphicAttr( GraphicAttr&, const SwFrm* pFrm ) const; #endif }; // ---------------------------------------------------------------------- // Inline Metoden aus Node.hxx - erst hier ist der TxtNode bekannt !! inline SwGrfNode *SwNode::GetGrfNode() { return ND_GRFNODE == nNodeType ? (SwGrfNode*)this : 0; } inline const SwGrfNode *SwNode::GetGrfNode() const { return ND_GRFNODE == nNodeType ? (const SwGrfNode*)this : 0; } #ifndef _FESHVIEW_ONLY_INLINE_NEEDED inline BOOL SwGrfNode::IsLinkedFile() const { return refLink.Is() && OBJECT_CLIENT_GRF == refLink->GetObjType(); } inline BOOL SwGrfNode::IsLinkedDDE() const { return refLink.Is() && OBJECT_CLIENT_DDE == refLink->GetObjType(); } #endif #endif <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <map> #include <node.h> #include "PSATResult.h" #include "calculator/EstimateFLA.h" using namespace v8; using namespace std; Isolate* iso; Local<Object> inp; //todo assert exist double Get(const char *nm) { return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue(); } void Results(const FunctionCallbackInfo<Value>& args) { iso = args.GetIsolate(); inp = args[0]->ToObject(); auto r = Object::New(iso); auto drive = (Pump::Drive)(int)Get("drive"); auto effCls = (Motor::EfficiencyClass)(int)Get("efficiency_class"); Pump pump((Pump::Style)(int)Get("pump_style"),Get("pump_rated_speed"),drive, Get("viscosity"),Get("specific_gravity"),Get("stages"),(Pump::Speed)(int)(!Get("fixed_speed"))); Motor motor((Motor::LineFrequency)(int)(!Get("line")),Get("motor_rated_power"),Get("motor_rated_speed"), effCls,Get("efficiency"),Get("motor_rated_voltage"),Get("motor_rated_flc"),Get("margin")); Financial fin(Get("fraction"),Get("cost")); FieldData fd(Get("flow"),Get("head"),(FieldData::LoadEstimationMethod)(Get("motor_field_power")>0?0:1), Get("motor_field_power"),Get("motor_field_current"),Get("motor_field_voltage")); PSATResult psat(pump,motor,fin,fd); psat.calculate(); auto ex = psat.getExisting(); map<const char *,vector<double>> out = { {"Pump Efficiency",{ex.pumpEfficiency_*100,0}}, {"Motor Rated Power",{ex.motorRatedPower_,0}}, {"Motor Shaft Power",{ex.motorShaftPower_,0}}, {"Pump Shaft Power",{ex.pumpShaftPower_,0}}, {"Motor Efficiency",{ex.motorEfficiency_,0}}, {"Motor Power Factor",{ex.motorPowerFactor_,0}}, {"Motor Current",{ex.motorCurrent_,0}}, {"Motor Power", {ex.motorPower_,0}}, {"Annual Energy", {ex.annualEnergy_,0}}, {"Annual Cost", {ex.annualCost_*1000,0}}, {"Savings Potential", {psat.getAnnualSavingsPotential(),0}}, {"Optimization Rating", {psat.getOptimizationRating(),0}} }; for(auto p: out) { auto a = Array::New(iso); a->Set(0,Number::New(iso,p.second[0])); a->Set(1,Number::New(iso,p.second[1])); r->Set(String::NewFromUtf8(iso,p.first),a); } args.GetReturnValue().Set(r); } void EstFLA(const FunctionCallbackInfo<Value>& args) { iso = args.GetIsolate(); inp = args[0]->ToObject(); EstimateFLA fla(Get("motor_rated_power"),Get("motor_rated_speed"),(Motor::EfficiencyClass)(int)Get("efficiency_class"), Get("efficiency"),Get("motor_rated_voltage")); fla.calculate(); args.GetReturnValue().Set(fla.getEstimatedFLA()); } void Check(double exp, double act, const char* nm="") { cout << "e " << exp << "; a " << act << endl; if (abs(exp-act)>.1*exp) { printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act); assert(!"equal"); } } void Check100(double exp, double act, const char* nm="") { Check(exp,act*100,nm); } void TestSame() { // auto msp = (new MotorShaftPower(200,80,1786,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460)); for (int i=1; i<=10000; i=i+2) { // Check(msp->calculate(),msp->calculate(),"SAME"); } } // void Test(const FunctionCallbackInfo<Value>& args) { // TestSame(); // //assume power load meth, est fla, line=60 // auto msp = new MotorShaftPower(200,80,1786,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460); // Check(101.9,msp->calculate()); // Check100(95,msp->calculateEfficiency()); // Check100(79.1,msp->calculatePowerFactor()); // Check(127,msp->calculateCurrent()); // msp = new MotorShaftPower(200,111.855,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460); // Check(143.4,msp->calculate()); // Check100(95.6,msp->calculateEfficiency()); // Check100(84.3,msp->calculatePowerFactor()); // Check(166.5,msp->calculateCurrent()); // msp = new MotorShaftPower(200,80,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,260); // Check(101.9,msp->calculate()); // Check100(95,msp->calculateEfficiency()); // Check100(138.8,msp->calculatePowerFactor()); // Check(128,msp->calculateCurrent()); // msp = new MotorShaftPower(100,80,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460); // Check(101.8,msp->calculate()); // Check100(94.9,msp->calculateEfficiency()); // Check100(86.7,msp->calculatePowerFactor()); // Check(115.8,msp->calculateCurrent()); // msp = new MotorShaftPower(200,80,1200,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460); // Check(101.4,msp->calculate()); // Check100(94.5,msp->calculateEfficiency()); // Check100(74.3,msp->calculatePowerFactor()); // Check(135.1,msp->calculateCurrent()); // // msp = new MotorShaftPower(200,80,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,200,460); // // Check(101.9,msp->calculate()); // // Check100(95,msp->calculateEfficiency()); // // Check100(35.2,msp->calculatePowerFactor()); // // Check(285,msp->calculateCurrent()); // auto ae = (new AnnualEnergy(80,1))->calculate(); // Check(700.8,ae); // ae = (new AnnualEnergy(150,.25))->calculate(); // Check(328.5,ae); // auto ac = (new AnnualCost(328.5,.05))->calculate(); // Check(16.4,ac); // } void Test2(const FunctionCallbackInfo<Value>& args) { Pump pump((Pump::Style)0,1780,(Pump::Drive)0, 1,1,1,(Pump::Speed)1); Motor motor((Motor::LineFrequency)1,200,1780, (Motor::EfficiencyClass)1,0,460,225,0); Financial fin(1,.05); FieldData fd(2000,277,(FieldData::LoadEstimationMethod)0,150, 0,460); PSATResult psat(pump,motor,fin,fd); psat.calculate(); auto ex = psat.getExisting(); cout << ex.motorCurrent_; } void TestFLA(const FunctionCallbackInfo<Value>& args) { EstimateFLA fla(200,1780,(Motor::EfficiencyClass)(1),0,460); fla.calculate(); Check(225.8,fla.getEstimatedFLA()); } void Test3(const FunctionCallbackInfo<Value>& args) { // Pump pump(Pump::Style::END_SUCTION_ANSI_API,1780,Pump::Drive::DIRECT_DRIVE, // 1,1,1,Pump::Speed::NOT_FIXED_SPEED); // Motor motor(Motor::LineFrequency::FREQ60,200,1780, // Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.4,0); // Financial fin(1,.05); // FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER, // 150,0,460); // PSATResult psat(pump,motor,fin,fd); // psat.calculate(); // auto ex = psat.getExisting(); { Pump pump(Pump::Style::END_SUCTION_ANSI_API,1780,Pump::Drive::DIRECT_DRIVE, 1,1,1,Pump::Speed::NOT_FIXED_SPEED); Motor motor(Motor::LineFrequency::FREQ60,200,1780, Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0); Financial fin(1,.05); FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER, 150,0,460); PSATResult psat(pump,motor,fin,fd); psat.calculate(); auto ex = psat.getExisting(); Check(217.1,ex.motorCurrent_); } { Pump pump(Pump::Style::END_SUCTION_ANSI_API,1780,Pump::Drive::DIRECT_DRIVE, 1,1,1,Pump::Speed::NOT_FIXED_SPEED); Motor motor(Motor::LineFrequency::FREQ60,200,1780, Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0); Financial fin(1,.05); FieldData fd(2000,277,FieldData::LoadEstimationMethod::CURRENT, 0,218,460); PSATResult psat(pump,motor,fin,fd); psat.calculate(); auto ex = psat.getExisting(); Check(150.7,ex.motorPower_); } } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "results", Results); NODE_SET_METHOD(exports, "estFLA", EstFLA); NODE_SET_METHOD(exports, "test", Test3); } NODE_MODULE(bridge, Init) <commit_msg>no message<commit_after>#include <iostream> #include <vector> #include <map> #include <node.h> #include "PSATResult.h" #include "calculator/EstimateFLA.h" using namespace v8; using namespace std; Isolate* iso; Local<Object> inp; //todo assert exist double Get(const char *nm) { return inp->ToObject()->Get(String::NewFromUtf8(iso,nm))->NumberValue(); } void Results(const FunctionCallbackInfo<Value>& args) { iso = args.GetIsolate(); inp = args[0]->ToObject(); auto r = Object::New(iso); auto drive = (Pump::Drive)(int)Get("drive"); auto effCls = (Motor::EfficiencyClass)(int)Get("efficiency_class"); Pump pump((Pump::Style)(int)Get("pump_style"),Get("pump_rated_speed"),drive, Get("viscosity"),Get("specific_gravity"),Get("stages"),(Pump::Speed)(int)(!Get("fixed_speed"))); Motor motor((Motor::LineFrequency)(int)(!Get("line")),Get("motor_rated_power"),Get("motor_rated_speed"), effCls,Get("efficiency"),Get("motor_rated_voltage"),Get("motor_rated_flc"),Get("margin")); Financial fin(Get("fraction"),Get("cost")); FieldData fd(Get("flow"),Get("head"),(FieldData::LoadEstimationMethod)(Get("motor_field_power")>0?0:1), Get("motor_field_power"),Get("motor_field_current"),Get("motor_field_voltage")); PSATResult psat(pump,motor,fin,fd); psat.calculateExisting(); auto ex = psat.getExisting(); map<const char *,vector<double>> out = { {"Pump Efficiency",{ex.pumpEfficiency_*100,0}}, {"Motor Rated Power",{ex.motorRatedPower_,0}}, {"Motor Shaft Power",{ex.motorShaftPower_,0}}, {"Pump Shaft Power",{ex.pumpShaftPower_,0}}, {"Motor Efficiency",{ex.motorEfficiency_,0}}, {"Motor Power Factor",{ex.motorPowerFactor_,0}}, {"Motor Current",{ex.motorCurrent_,0}}, {"Motor Power", {ex.motorPower_,0}}, {"Annual Energy", {ex.annualEnergy_,0}}, {"Annual Cost", {ex.annualCost_*1000,0}}, {"Savings Potential", {psat.getAnnualSavingsPotential(),0}}, {"Optimization Rating", {psat.getOptimizationRating(),0}} }; for(auto p: out) { auto a = Array::New(iso); a->Set(0,Number::New(iso,p.second[0])); a->Set(1,Number::New(iso,p.second[1])); r->Set(String::NewFromUtf8(iso,p.first),a); } args.GetReturnValue().Set(r); } void EstFLA(const FunctionCallbackInfo<Value>& args) { iso = args.GetIsolate(); inp = args[0]->ToObject(); EstimateFLA fla(Get("motor_rated_power"),Get("motor_rated_speed"),(Motor::EfficiencyClass)(int)Get("efficiency_class"), Get("efficiency"),Get("motor_rated_voltage")); fla.calculate(); args.GetReturnValue().Set(fla.getEstimatedFLA()); } void Check(double exp, double act, const char* nm="") { cout << "e " << exp << "; a " << act << endl; if (abs(exp-act)>.1*exp) { printf("\"%s\" TEST FAILED: %f %f\n",nm,exp,act); assert(!"equal"); } } void Check100(double exp, double act, const char* nm="") { Check(exp,act*100,nm); } void TestSame() { // auto msp = (new MotorShaftPower(200,80,1786,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460)); for (int i=1; i<=10000; i=i+2) { // Check(msp->calculate(),msp->calculate(),"SAME"); } } // void Test(const FunctionCallbackInfo<Value>& args) { // TestSame(); // //assume power load meth, est fla, line=60 // auto msp = new MotorShaftPower(200,80,1786,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460); // Check(101.9,msp->calculate()); // Check100(95,msp->calculateEfficiency()); // Check100(79.1,msp->calculatePowerFactor()); // Check(127,msp->calculateCurrent()); // msp = new MotorShaftPower(200,111.855,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460); // Check(143.4,msp->calculate()); // Check100(95.6,msp->calculateEfficiency()); // Check100(84.3,msp->calculatePowerFactor()); // Check(166.5,msp->calculateCurrent()); // msp = new MotorShaftPower(200,80,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,260); // Check(101.9,msp->calculate()); // Check100(95,msp->calculateEfficiency()); // Check100(138.8,msp->calculatePowerFactor()); // Check(128,msp->calculateCurrent()); // msp = new MotorShaftPower(100,80,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460); // Check(101.8,msp->calculate()); // Check100(94.9,msp->calculateEfficiency()); // Check100(86.7,msp->calculatePowerFactor()); // Check(115.8,msp->calculateCurrent()); // msp = new MotorShaftPower(200,80,1200,Motor::EfficiencyClass::ENERGY_EFFICIENT,460,460); // Check(101.4,msp->calculate()); // Check100(94.5,msp->calculateEfficiency()); // Check100(74.3,msp->calculatePowerFactor()); // Check(135.1,msp->calculateCurrent()); // // msp = new MotorShaftPower(200,80,1780,Motor::EfficiencyClass::ENERGY_EFFICIENT,200,460); // // Check(101.9,msp->calculate()); // // Check100(95,msp->calculateEfficiency()); // // Check100(35.2,msp->calculatePowerFactor()); // // Check(285,msp->calculateCurrent()); // auto ae = (new AnnualEnergy(80,1))->calculate(); // Check(700.8,ae); // ae = (new AnnualEnergy(150,.25))->calculate(); // Check(328.5,ae); // auto ac = (new AnnualCost(328.5,.05))->calculate(); // Check(16.4,ac); // } void TestFLA(const FunctionCallbackInfo<Value>& args) { EstimateFLA fla(200,1780,(Motor::EfficiencyClass)(1),0,460); fla.calculate(); Check(225.8,fla.getEstimatedFLA()); } void Test3(const FunctionCallbackInfo<Value>& args) { #define BASE \ Pump pump(Pump::Style::END_SUCTION_ANSI_API,1780,Pump::Drive::DIRECT_DRIVE,\ 1,1,1,Pump::Speed::NOT_FIXED_SPEED);\ Motor motor(Motor::LineFrequency::FREQ60,200,1780,\ Motor::EfficiencyClass::ENERGY_EFFICIENT,0,460,225.8,0);\ Financial fin(1,.05);\ FieldData fd(2000,277,FieldData::LoadEstimationMethod::POWER,\ 150,218,460); #define CALC \ PSATResult psat(pump,motor,fin,fd);\ psat.calculateExisting();\ auto ex = psat.getExisting(); { BASE CALC Check(217.1,ex.motorCurrent_); } { BASE fd.setLoadEstimationMethod(FieldData::LoadEstimationMethod::CURRENT); CALC Check(150.7,psat.getExisting().motorPower_); } } void Init(Local<Object> exports) { NODE_SET_METHOD(exports, "results", Results); NODE_SET_METHOD(exports, "estFLA", EstFLA); NODE_SET_METHOD(exports, "test", Test3); } NODE_MODULE(bridge, Init) <|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // CellML Model Repository widget //============================================================================== #include "cellmlmodelrepositorywindowwidget.h" #include "corecliutils.h" #include "coreguiutils.h" //============================================================================== #include "ui_cellmlmodelrepositorywindowwidget.h" //============================================================================== #include <QClipboard> #include <QDesktopServices> #include <QIODevice> #include <QMenu> #include <QPaintEvent> #include <QRegularExpression> #include <QWebElement> #include <QWebFrame> //============================================================================== namespace OpenCOR { namespace CellMLModelRepositoryWindow { //============================================================================== CellmlModelRepositoryWindowModel::CellmlModelRepositoryWindowModel(const QString &pUrl, const QString &pName) : mUrl(pUrl), mName(pName) { } //============================================================================== QString CellmlModelRepositoryWindowModel::url() const { // Return our URL return mUrl; } //============================================================================== QString CellmlModelRepositoryWindowModel::name() const { // Return our name return mName; } //============================================================================== CellmlModelRepositoryWindowWidget::CellmlModelRepositoryWindowWidget(QWidget *pParent) : Core::WebViewWidget(pParent), Core::CommonWidget(pParent), mGui(new Ui::CellmlModelRepositoryWindowWidget), mModelNames(QStringList()), mModelUrlsIds(QMap<QString, int>()), mErrorMessage(QString()), mNumberOfFilteredModels(0), mUrl(QString()) { // Set up the GUI mGui->setupUi(this); // Add a small margin ourselves, so that no visual trace of the border drawn // by drawBorder() in paintEvent() is left when scrolling (on Windows and // Linux, but it doesn't harm doing it for all our supported platforms) // Note: not sure why, but no matter how many pixels are specified for the // margin, no margin actually exists, but it addresses the issue with // the border drawn by drawBorder()... setStyleSheet("QWebView {" " margin: 1px;" "}"); // Create and populate our context menu mContextMenu = new QMenu(this); mContextMenu->addAction(mGui->actionCopy); // We want out own context menu setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(showCustomContextMenu())); // Prevent objects from being dropped on us setAcceptDrops(false); // Have links opened in the user's browser rather than in our list page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); // Some connections connect(page(), SIGNAL(linkClicked(const QUrl &)), this, SLOT(linkClicked())); // Retrieve the output template Core::readTextFromFile(":/output.html", mOutputTemplate); setHtml(mOutputTemplate.arg(Core::iconDataUri(":/oxygen/places/folder-downloads.png", 16, 16), Core::iconDataUri(":/oxygen/actions/document-open-remote.png", 16, 16))); } //============================================================================== CellmlModelRepositoryWindowWidget::~CellmlModelRepositoryWindowWidget() { // Delete the GUI delete mGui; } //============================================================================== void CellmlModelRepositoryWindowWidget::retranslateUi() { // Retranslate our message QWebElement messageElement = page()->mainFrame()->documentElement().findFirst("p[id=message]"); if (mErrorMessage.isEmpty()) { if (!mNumberOfFilteredModels) { if (mModelNames.isEmpty()) messageElement.removeAllChildren(); else messageElement.setInnerXml(tr("No CellML model matches your criteria.")); } else if (mNumberOfFilteredModels == 1) { messageElement.setInnerXml(tr("<strong>1</strong> CellML model was found:")); } else { messageElement.setInnerXml(tr("<strong>%1</strong> CellML models were found:").arg(mNumberOfFilteredModels)); } } else { messageElement.setInnerXml(tr("<strong>Error:</strong> ")+Core::formatMessage(mErrorMessage, true, true)); } } //============================================================================== QSize CellmlModelRepositoryWindowWidget::sizeHint() const { // Suggest a default size for the CellML Model Repository widget // Note: this is critical if we want a docked widget, with a CellML Model // Repository widget on it, to have a decent size when docked to the // main window... return defaultSize(0.15); } //============================================================================== void CellmlModelRepositoryWindowWidget::paintEvent(QPaintEvent *pEvent) { // Default handling of the event QWebView::paintEvent(pEvent); // Draw a border drawBorder( #if defined(Q_OS_WIN) || defined(Q_OS_LINUX) true, true, true, true, #elif defined(Q_OS_MAC) true, false, false, false, #else #error Unsupported platform #endif true, false, false, false ); } //============================================================================== void CellmlModelRepositoryWindowWidget::initialize(const CellmlModelRepositoryWindowModels &pModels, const QString &pErrorMessage) { // Initialise / keep track of some properties mModelNames = QStringList(); mModelUrlsIds = QMap<QString, int>(); mErrorMessage = pErrorMessage; // Initialise our list of models QString models = QString(); for (int i = 0, iMax = pModels.count(); i < iMax; ++i) { CellmlModelRepositoryWindowModel model = pModels[i]; models = models +"<tr id=\"model_"+QString::number(i)+"\">\n" +" <td>\n" +" <ul>\n" +" <li>\n" +" <a href=\""+model.url()+"\">"+model.name()+"</a>\n" +" </li>\n" +" </ul>\n" +" </td>\n" +" <td class=\"button\">\n" +" <a class=\"noHover\" href=\"clone|"+model.url()+"|"+model.name()+"\"><img class=\"button clone\"/></a>\n" +" </td>\n" +" <td class=\"button\">\n" +" <a class=\"noHover\" href=\"files|"+model.url()+"|"+model.name()+"\"><img id=\"model_"+QString::number(i)+"\" class=\"button open\"/></a>\n" +" </td>\n" +"</tr>\n"; mModelNames << model.name(); mModelUrlsIds.insert(model.url(), i); } QWebElement modelsElement = page()->mainFrame()->documentElement().findFirst("tbody"); modelsElement.removeAllChildren(); modelsElement.appendInside(models); } //============================================================================== void CellmlModelRepositoryWindowWidget::filter(const QString &pFilter) { // Make sure that we have something to filter (i.e. no error message) if (!mErrorMessage.isEmpty()) return; // Filter our list of models, remove duplicates (they will be reintroduced // in the next step) and update our message (by retranslate ourselves) QStringList filteredModelNames = mModelNames.filter(QRegularExpression(pFilter, QRegularExpression::CaseInsensitiveOption)); mNumberOfFilteredModels = filteredModelNames.count(); filteredModelNames.removeDuplicates(); retranslateUi(); // Determine which models should be shown/hidden QIntList modelIndexes = QIntList(); int modelIndex; foreach (const QString &filteredModelName, filteredModelNames) { modelIndex = -1; forever { modelIndex = mModelNames.indexOf(filteredModelName, ++modelIndex); if (modelIndex == -1) break; else modelIndexes << modelIndex; } } // Show/hide the relevant models QWebElement documentElement = page()->mainFrame()->documentElement(); for (int i = 0, iMax = mModelNames.count(); i < iMax; ++i) documentElement.findFirst(QString("tr[id=model_%1]").arg(i)).setStyleProperty("display", modelIndexes.contains(i)?"table-row":"none"); } //============================================================================== void CellmlModelRepositoryWindowWidget::on_actionCopy_triggered() { // Copy the URL of the model to the clipboard QApplication::clipboard()->setText(mUrl); } //============================================================================== void CellmlModelRepositoryWindowWidget::linkClicked() { // Retrieve some information about the link QString link; QString textContent; retrieveLinkInformation(link, textContent); // Check whether we have clicked a model link or a button link, i.e. that we // want to clone the model if (textContent.isEmpty()) { // We have clicked on a button link, so let people know whether we want // to clone a model or show/hide its files QStringList linkList = link.split("|"); if (!linkList[0].compare("clone")) { emit cloneModel(linkList[1], linkList[2]); } else { // Toggle our button link QWebElement buttonElement = page()->mainFrame()->documentElement().findFirst(QString("img[id=model_%1]").arg(mModelUrlsIds.value(linkList[1]))); if (buttonElement.hasClass("button")) { buttonElement.removeClass("button"); buttonElement.addClass("downButton"); } else { buttonElement.addClass("button"); buttonElement.removeClass("downButton"); } // Let people know that we want to show the model's files emit showModelFiles(linkList[1], linkList[2]); } } else { // Open the model link in the user's browser QDesktopServices::openUrl(link); } } //============================================================================== void CellmlModelRepositoryWindowWidget::showCustomContextMenu() { // Retrieve some information about the link, if any QString textContent; retrieveLinkInformation(mUrl, textContent); // Show our context menu to allow the copying of the URL of the model, but // only if we are over a link, i.e. if both mLink and textContent are not // empty if (!mUrl.isEmpty() && !textContent.isEmpty()) mContextMenu->exec(QCursor::pos()); } //============================================================================== } // namespace CellMLModelRepositoryWindow } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>PMR window: some work on allowing a CellML file to be opened directly (#592) [ci skip].<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // CellML Model Repository widget //============================================================================== #include "cellmlmodelrepositorywindowwidget.h" #include "corecliutils.h" #include "coreguiutils.h" //============================================================================== #include "ui_cellmlmodelrepositorywindowwidget.h" //============================================================================== #include <QClipboard> #include <QDesktopServices> #include <QIODevice> #include <QMenu> #include <QPaintEvent> #include <QRegularExpression> #include <QWebElement> #include <QWebFrame> //============================================================================== namespace OpenCOR { namespace CellMLModelRepositoryWindow { //============================================================================== CellmlModelRepositoryWindowModel::CellmlModelRepositoryWindowModel(const QString &pUrl, const QString &pName) : mUrl(pUrl), mName(pName) { } //============================================================================== QString CellmlModelRepositoryWindowModel::url() const { // Return our URL return mUrl; } //============================================================================== QString CellmlModelRepositoryWindowModel::name() const { // Return our name return mName; } //============================================================================== CellmlModelRepositoryWindowWidget::CellmlModelRepositoryWindowWidget(QWidget *pParent) : Core::WebViewWidget(pParent), Core::CommonWidget(pParent), mGui(new Ui::CellmlModelRepositoryWindowWidget), mModelNames(QStringList()), mModelUrlsIds(QMap<QString, int>()), mErrorMessage(QString()), mNumberOfFilteredModels(0), mUrl(QString()) { // Set up the GUI mGui->setupUi(this); // Add a small margin ourselves, so that no visual trace of the border drawn // by drawBorder() in paintEvent() is left when scrolling (on Windows and // Linux, but it doesn't harm doing it for all our supported platforms) // Note: not sure why, but no matter how many pixels are specified for the // margin, no margin actually exists, but it addresses the issue with // the border drawn by drawBorder()... setStyleSheet("QWebView {" " margin: 1px;" "}"); // Create and populate our context menu mContextMenu = new QMenu(this); mContextMenu->addAction(mGui->actionCopy); // We want out own context menu setContextMenuPolicy(Qt::CustomContextMenu); connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(showCustomContextMenu())); // Prevent objects from being dropped on us setAcceptDrops(false); // Have links opened in the user's browser rather than in our list page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); // Some connections connect(page(), SIGNAL(linkClicked(const QUrl &)), this, SLOT(linkClicked())); // Retrieve the output template Core::readTextFromFile(":/output.html", mOutputTemplate); setHtml(mOutputTemplate.arg(Core::iconDataUri(":/oxygen/places/folder-downloads.png", 16, 16), Core::iconDataUri(":/oxygen/actions/document-open-remote.png", 16, 16))); } //============================================================================== CellmlModelRepositoryWindowWidget::~CellmlModelRepositoryWindowWidget() { // Delete the GUI delete mGui; } //============================================================================== void CellmlModelRepositoryWindowWidget::retranslateUi() { // Retranslate our message QWebElement messageElement = page()->mainFrame()->documentElement().findFirst("p[id=message]"); if (mErrorMessage.isEmpty()) { if (!mNumberOfFilteredModels) { if (mModelNames.isEmpty()) messageElement.removeAllChildren(); else messageElement.setInnerXml(tr("No CellML model matches your criteria.")); } else if (mNumberOfFilteredModels == 1) { messageElement.setInnerXml(tr("<strong>1</strong> CellML model was found:")); } else { messageElement.setInnerXml(tr("<strong>%1</strong> CellML models were found:").arg(mNumberOfFilteredModels)); } } else { messageElement.setInnerXml(tr("<strong>Error:</strong> ")+Core::formatMessage(mErrorMessage, true, true)); } } //============================================================================== QSize CellmlModelRepositoryWindowWidget::sizeHint() const { // Suggest a default size for the CellML Model Repository widget // Note: this is critical if we want a docked widget, with a CellML Model // Repository widget on it, to have a decent size when docked to the // main window... return defaultSize(0.15); } //============================================================================== void CellmlModelRepositoryWindowWidget::paintEvent(QPaintEvent *pEvent) { // Default handling of the event QWebView::paintEvent(pEvent); // Draw a border drawBorder( #if defined(Q_OS_WIN) || defined(Q_OS_LINUX) true, true, true, true, #elif defined(Q_OS_MAC) true, false, false, false, #else #error Unsupported platform #endif true, false, false, false ); } //============================================================================== void CellmlModelRepositoryWindowWidget::initialize(const CellmlModelRepositoryWindowModels &pModels, const QString &pErrorMessage) { // Initialise / keep track of some properties mModelNames = QStringList(); mModelUrlsIds = QMap<QString, int>(); mErrorMessage = pErrorMessage; // Initialise our list of models QString models = QString(); for (int i = 0, iMax = pModels.count(); i < iMax; ++i) { CellmlModelRepositoryWindowModel model = pModels[i]; models = models +"<tr id=\"model_"+QString::number(i)+"\">\n" +" <td>\n" +" <ul>\n" +" <li>\n" +" <a href=\""+model.url()+"\">"+model.name()+"</a>\n" +" </li>\n" +" </ul>\n" +" </td>\n" +" <td class=\"button\">\n" +" <a class=\"noHover\" href=\"clone|"+model.url()+"|"+model.name()+"\"><img class=\"button clone\"/></a>\n" +" </td>\n" +" <td class=\"button\">\n" +" <a class=\"noHover\" href=\"files|"+model.url()+"|"+model.name()+"\"><img id=\"model_"+QString::number(i)+"\" class=\"button open\"/></a>\n" +" </td>\n" +"</tr>\n"; mModelNames << model.name(); mModelUrlsIds.insert(model.url(), i); } QWebElement modelsElement = page()->mainFrame()->documentElement().findFirst("tbody"); modelsElement.removeAllChildren(); modelsElement.appendInside(models); } //============================================================================== void CellmlModelRepositoryWindowWidget::filter(const QString &pFilter) { // Make sure that we have something to filter (i.e. no error message) if (!mErrorMessage.isEmpty()) return; // Filter our list of models, remove duplicates (they will be reintroduced // in the next step) and update our message (by retranslate ourselves) QStringList filteredModelNames = mModelNames.filter(QRegularExpression(pFilter, QRegularExpression::CaseInsensitiveOption)); mNumberOfFilteredModels = filteredModelNames.count(); filteredModelNames.removeDuplicates(); retranslateUi(); // Show/hide the relevant models QWebElement documentElement = page()->mainFrame()->documentElement(); for (int i = 0, iMax = mModelNames.count(); i < iMax; ++i) documentElement.findFirst(QString("tr[id=model_%1]").arg(i)).setStyleProperty("display", filteredModelNames.contains(mModelNames[i])?"table-row":"none"); } //============================================================================== void CellmlModelRepositoryWindowWidget::on_actionCopy_triggered() { // Copy the URL of the model to the clipboard QApplication::clipboard()->setText(mUrl); } //============================================================================== void CellmlModelRepositoryWindowWidget::linkClicked() { // Retrieve some information about the link QString link; QString textContent; retrieveLinkInformation(link, textContent); // Check whether we have clicked a model link or a button link, i.e. that we // want to clone the model if (textContent.isEmpty()) { // We have clicked on a button link, so let people know whether we want // to clone a model or show/hide its files QStringList linkList = link.split("|"); if (!linkList[0].compare("clone")) { emit cloneModel(linkList[1], linkList[2]); } else { // Toggle our button link QWebElement buttonElement = page()->mainFrame()->documentElement().findFirst(QString("img[id=model_%1]").arg(mModelUrlsIds.value(linkList[1]))); if (buttonElement.hasClass("button")) { buttonElement.removeClass("button"); buttonElement.addClass("downButton"); } else { buttonElement.addClass("button"); buttonElement.removeClass("downButton"); } // Let people know that we want to show the model's files emit showModelFiles(linkList[1], linkList[2]); } } else { // Open the model link in the user's browser QDesktopServices::openUrl(link); } } //============================================================================== void CellmlModelRepositoryWindowWidget::showCustomContextMenu() { // Retrieve some information about the link, if any QString textContent; retrieveLinkInformation(mUrl, textContent); // Show our context menu to allow the copying of the URL of the model, but // only if we are over a link, i.e. if both mLink and textContent are not // empty if (!mUrl.isEmpty() && !textContent.isEmpty()) mContextMenu->exec(QCursor::pos()); } //============================================================================== } // namespace CellMLModelRepositoryWindow } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Alexandru-Eugen Ichim * Willow Garage, Inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ */ #ifndef PCL_FEATURES_IMPL_STATISTICAL_MULTISCALE_INTEREST_REGION_EXTRACTION_H_ #define PCL_FEATURES_IMPL_STATISTICAL_MULTISCALE_INTEREST_REGION_EXTRACTION_H_ #include "pcl/features/statistical_multiscale_interest_region_extraction.h" #include <pcl/kdtree/kdtree_flann.h> #include <boost/graph/adjacency_list.hpp> #include <boost/property_map/property_map.hpp> #include <boost/graph/johnson_all_pairs_shortest.hpp> ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::StatisticalMultiscaleInterestRegionExtraction<PointT>::generateCloudGraph () { // generate a K-NNG (K-nearest neighbors graph) pcl::KdTreeFLANN<PointT> kdtree; kdtree.setInputCloud (input_); using namespace boost; typedef property<edge_weight_t, float> Weight; typedef adjacency_list<vecS, vecS, undirectedS, no_property, Weight> Graph; Graph cloud_graph; for (size_t point_i = 0; point_i < input_->points.size (); ++point_i) { std::vector<int> k_indices (16); std::vector<float> k_distances (16); kdtree.nearestKSearch (point_i, 16, k_indices, k_distances); for (size_t k_i = 0; k_i < k_indices.size (); ++k_i) add_edge (point_i, k_indices[k_i], Weight (sqrt (k_distances[k_i])), cloud_graph); } const size_t E = num_edges (cloud_graph), V = num_vertices (cloud_graph); PCL_INFO ("The graph has %lu vertices and %lu edges.\n", V, E); geodesic_distances_.clear (); for (size_t i = 0; i < V; ++i) { std::vector<float> aux (V); geodesic_distances_.push_back (aux); } johnson_all_pairs_shortest_paths (cloud_graph, geodesic_distances_); PCL_INFO ("Done generating the graph\n"); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> bool pcl::StatisticalMultiscaleInterestRegionExtraction<PointT>::initCompute () { if (!PCLBase<PointT>::initCompute ()) { PCL_ERROR ("[pcl::StatisticalMultiscaleInterestRegionExtraction::initCompute] PCLBase::initCompute () failed - no input cloud was given.\n"); return false; } if (scale_values_.empty ()) { PCL_ERROR ("[pcl::StatisticalMultiscaleInterestRegionExtraction::initCompute] No scale values were given\n"); return false; } return true; } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::StatisticalMultiscaleInterestRegionExtraction<PointT>::geodesicFixedRadiusSearch (size_t &query_index, float &radius, std::vector<int> &result_indices) { for (size_t i = 0; i < geodesic_distances_[query_index].size (); ++i) if (i != query_index && geodesic_distances_[query_index][i] < radius) result_indices.push_back (i); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::StatisticalMultiscaleInterestRegionExtraction<PointT>::computeRegionsOfInterest (std::list<pcl::StatisticalMultiscaleInterestRegionExtraction<PointT>::IndicesPtr> &rois) { if (!initCompute ()) { PCL_ERROR ("StatisticalMultiscaleInterestRegionExtraction: not completely initialized\n"); return; } generateCloudGraph (); computeF (); extractExtrema (rois); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::StatisticalMultiscaleInterestRegionExtraction<PointT>::computeF () { PCL_INFO ("Calculating statistical information\n"); // declare and initialize data structure F_scales_.resize (scale_values_.size ()); std::vector<float> point_density (input_->points.size ()), F (input_->points.size ()); std::vector<std::vector<float> > phi (input_->points.size ()); std::vector<float> phi_row (input_->points.size ()); for (size_t scale_i = 0; scale_i < scale_values_.size (); ++scale_i) { float scale_squared = scale_values_[scale_i] * scale_values_[scale_i]; // calculate point density for each point x_i for (size_t point_i = 0; point_i < input_->points.size (); ++point_i) { float point_density_i = 0.0; for (size_t point_j = 0; point_j < input_->points.size (); ++point_j) { float d_g = geodesic_distances_[point_i][point_j]; float phi_i_j = 1.0 / sqrt(2.0 * M_PI * scale_squared) * exp( (-1) * d_g*d_g / (2.0*scale_squared)); point_density_i += phi_i_j; phi_row[point_j] = phi_i_j; } point_density[point_i] = point_density_i; phi[point_i] = phi_row; } // compute weights for each pair (x_i, x_j), evaluate the operator A_hat for (size_t point_i = 0; point_i < input_->points.size (); ++point_i) { float A_hat_normalization = 0.0; PointT A_hat; A_hat.x = A_hat.y = A_hat.z = 0.0; for (size_t point_j = 0; point_j < input_->points.size (); ++point_j) { float phi_hat_i_j = phi[point_i][point_j] / (point_density[point_i] * point_density[point_j]); A_hat_normalization += phi_hat_i_j; PointT aux = input_->points[point_j]; aux.x *= phi_hat_i_j; aux.y *= phi_hat_i_j; aux.z *= phi_hat_i_j; A_hat.x += aux.x; A_hat.y += aux.y; A_hat.z += aux.z; } A_hat.x /= A_hat_normalization; A_hat.y /= A_hat_normalization; A_hat.z /= A_hat_normalization; // compute the invariant F float aux = 2.0 / scale_values_[scale_i] * euclideanDistance<PointT, PointT> (A_hat, input_->points[point_i]); F[point_i] = aux * exp (-aux); } F_scales_[scale_i] = F; } } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::StatisticalMultiscaleInterestRegionExtraction<PointT>::extractExtrema (std::list<pcl::StatisticalMultiscaleInterestRegionExtraction<PointT>::IndicesPtr> &rois) { std::vector<std::vector<bool> > is_min (scale_values_.size ()), is_max (scale_values_.size ()); // for each point, check if it is a local extrema on each scale for (size_t scale_i = 0; scale_i < scale_values_.size (); ++scale_i) { std::vector<bool> is_min_scale (input_->points.size ()), is_max_scale (input_->points.size ()); for (size_t point_i = 0; point_i < input_->points.size (); ++point_i) { std::vector<int> nn_indices; geodesicFixedRadiusSearch (point_i, scale_values_[scale_i], nn_indices); bool is_max_point = true, is_min_point = true; for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it) if (F_scales_[scale_i][point_i] < F_scales_[scale_i][*nn_it]) is_max_point = false; else is_min_point = false; is_min_scale[point_i] = is_min_point; is_max_scale[point_i] = is_max_point; } is_min[scale_i] = is_min_scale; is_max[scale_i] = is_max_scale; } // look for points that are min/max over three consecutive scales for (size_t scale_i = 1; scale_i < scale_values_.size () - 1; ++scale_i) { for (size_t point_i = 0; point_i < input_->points.size (); ++point_i) if ((is_min[scale_i - 1][point_i] && is_min[scale_i][point_i] && is_min[scale_i + 1][point_i]) || (is_max[scale_i - 1][point_i] && is_max[scale_i][point_i] && is_max[scale_i + 1][point_i])) { // add the point to the result vector IndicesPtr region (new std::vector<int> ()); region->push_back (point_i); // and also add its scale-sized geodesic neighborhood std::vector<int> nn_indices; geodesicFixedRadiusSearch (point_i, scale_values_[scale_i], nn_indices); region->insert (region->end (), nn_indices.begin (), nn_indices.end ()); rois.push_back (region); } } } #define PCL_INSTANTIATE_StatisticalMultiscaleInterestRegionExtraction(T) template class PCL_EXPORTS pcl::StatisticalMultiscaleInterestRegionExtraction<T>; #endif /* PCL_FEATURES_IMPL_STATISTICAL_MULTISCALE_INTEREST_REGION_EXTRACTION_H_ */ <commit_msg>fix a msvc (weird) build issue<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Alexandru-Eugen Ichim * Willow Garage, Inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ */ #ifndef PCL_FEATURES_IMPL_STATISTICAL_MULTISCALE_INTEREST_REGION_EXTRACTION_H_ #define PCL_FEATURES_IMPL_STATISTICAL_MULTISCALE_INTEREST_REGION_EXTRACTION_H_ #include "pcl/features/statistical_multiscale_interest_region_extraction.h" #include <pcl/kdtree/kdtree_flann.h> #include <boost/graph/adjacency_list.hpp> #include <boost/property_map/property_map.hpp> #include <boost/graph/johnson_all_pairs_shortest.hpp> ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::StatisticalMultiscaleInterestRegionExtraction<PointT>::generateCloudGraph () { // generate a K-NNG (K-nearest neighbors graph) pcl::KdTreeFLANN<PointT> kdtree; kdtree.setInputCloud (input_); using namespace boost; typedef property<edge_weight_t, float> Weight; typedef adjacency_list<vecS, vecS, undirectedS, no_property, Weight> Graph; Graph cloud_graph; for (size_t point_i = 0; point_i < input_->points.size (); ++point_i) { std::vector<int> k_indices (16); std::vector<float> k_distances (16); kdtree.nearestKSearch (point_i, 16, k_indices, k_distances); for (size_t k_i = 0; k_i < k_indices.size (); ++k_i) add_edge (point_i, k_indices[k_i], Weight (sqrt (k_distances[k_i])), cloud_graph); } const size_t E = num_edges (cloud_graph), V = num_vertices (cloud_graph); PCL_INFO ("The graph has %lu vertices and %lu edges.\n", V, E); geodesic_distances_.clear (); for (size_t i = 0; i < V; ++i) { std::vector<float> aux (V); geodesic_distances_.push_back (aux); } johnson_all_pairs_shortest_paths (cloud_graph, geodesic_distances_); PCL_INFO ("Done generating the graph\n"); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> bool pcl::StatisticalMultiscaleInterestRegionExtraction<PointT>::initCompute () { if (!PCLBase<PointT>::initCompute ()) { PCL_ERROR ("[pcl::StatisticalMultiscaleInterestRegionExtraction::initCompute] PCLBase::initCompute () failed - no input cloud was given.\n"); return false; } if (scale_values_.empty ()) { PCL_ERROR ("[pcl::StatisticalMultiscaleInterestRegionExtraction::initCompute] No scale values were given\n"); return false; } return true; } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::StatisticalMultiscaleInterestRegionExtraction<PointT>::geodesicFixedRadiusSearch (size_t &query_index, float &radius, std::vector<int> &result_indices) { for (size_t i = 0; i < geodesic_distances_[query_index].size (); ++i) if (i != query_index && geodesic_distances_[query_index][i] < radius) result_indices.push_back (i); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::StatisticalMultiscaleInterestRegionExtraction<PointT>::computeRegionsOfInterest (std::list<IndicesPtr> &rois) { if (!initCompute ()) { PCL_ERROR ("StatisticalMultiscaleInterestRegionExtraction: not completely initialized\n"); return; } generateCloudGraph (); computeF (); extractExtrema (rois); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::StatisticalMultiscaleInterestRegionExtraction<PointT>::computeF () { PCL_INFO ("Calculating statistical information\n"); // declare and initialize data structure F_scales_.resize (scale_values_.size ()); std::vector<float> point_density (input_->points.size ()), F (input_->points.size ()); std::vector<std::vector<float> > phi (input_->points.size ()); std::vector<float> phi_row (input_->points.size ()); for (size_t scale_i = 0; scale_i < scale_values_.size (); ++scale_i) { float scale_squared = scale_values_[scale_i] * scale_values_[scale_i]; // calculate point density for each point x_i for (size_t point_i = 0; point_i < input_->points.size (); ++point_i) { float point_density_i = 0.0; for (size_t point_j = 0; point_j < input_->points.size (); ++point_j) { float d_g = geodesic_distances_[point_i][point_j]; float phi_i_j = 1.0 / sqrt(2.0 * M_PI * scale_squared) * exp( (-1) * d_g*d_g / (2.0*scale_squared)); point_density_i += phi_i_j; phi_row[point_j] = phi_i_j; } point_density[point_i] = point_density_i; phi[point_i] = phi_row; } // compute weights for each pair (x_i, x_j), evaluate the operator A_hat for (size_t point_i = 0; point_i < input_->points.size (); ++point_i) { float A_hat_normalization = 0.0; PointT A_hat; A_hat.x = A_hat.y = A_hat.z = 0.0; for (size_t point_j = 0; point_j < input_->points.size (); ++point_j) { float phi_hat_i_j = phi[point_i][point_j] / (point_density[point_i] * point_density[point_j]); A_hat_normalization += phi_hat_i_j; PointT aux = input_->points[point_j]; aux.x *= phi_hat_i_j; aux.y *= phi_hat_i_j; aux.z *= phi_hat_i_j; A_hat.x += aux.x; A_hat.y += aux.y; A_hat.z += aux.z; } A_hat.x /= A_hat_normalization; A_hat.y /= A_hat_normalization; A_hat.z /= A_hat_normalization; // compute the invariant F float aux = 2.0 / scale_values_[scale_i] * euclideanDistance<PointT, PointT> (A_hat, input_->points[point_i]); F[point_i] = aux * exp (-aux); } F_scales_[scale_i] = F; } } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointT> void pcl::StatisticalMultiscaleInterestRegionExtraction<PointT>::extractExtrema (std::list<IndicesPtr> &rois) { std::vector<std::vector<bool> > is_min (scale_values_.size ()), is_max (scale_values_.size ()); // for each point, check if it is a local extrema on each scale for (size_t scale_i = 0; scale_i < scale_values_.size (); ++scale_i) { std::vector<bool> is_min_scale (input_->points.size ()), is_max_scale (input_->points.size ()); for (size_t point_i = 0; point_i < input_->points.size (); ++point_i) { std::vector<int> nn_indices; geodesicFixedRadiusSearch (point_i, scale_values_[scale_i], nn_indices); bool is_max_point = true, is_min_point = true; for (std::vector<int>::iterator nn_it = nn_indices.begin (); nn_it != nn_indices.end (); ++nn_it) if (F_scales_[scale_i][point_i] < F_scales_[scale_i][*nn_it]) is_max_point = false; else is_min_point = false; is_min_scale[point_i] = is_min_point; is_max_scale[point_i] = is_max_point; } is_min[scale_i] = is_min_scale; is_max[scale_i] = is_max_scale; } // look for points that are min/max over three consecutive scales for (size_t scale_i = 1; scale_i < scale_values_.size () - 1; ++scale_i) { for (size_t point_i = 0; point_i < input_->points.size (); ++point_i) if ((is_min[scale_i - 1][point_i] && is_min[scale_i][point_i] && is_min[scale_i + 1][point_i]) || (is_max[scale_i - 1][point_i] && is_max[scale_i][point_i] && is_max[scale_i + 1][point_i])) { // add the point to the result vector IndicesPtr region (new std::vector<int> ()); region->push_back (point_i); // and also add its scale-sized geodesic neighborhood std::vector<int> nn_indices; geodesicFixedRadiusSearch (point_i, scale_values_[scale_i], nn_indices); region->insert (region->end (), nn_indices.begin (), nn_indices.end ()); rois.push_back (region); } } } #define PCL_INSTANTIATE_StatisticalMultiscaleInterestRegionExtraction(T) template class PCL_EXPORTS pcl::StatisticalMultiscaleInterestRegionExtraction<T>; #endif /* PCL_FEATURES_IMPL_STATISTICAL_MULTISCALE_INTEREST_REGION_EXTRACTION_H_ */ <|endoftext|>
<commit_before>da2b7406-2e4c-11e5-9284-b827eb9e62be<commit_msg>da307faa-2e4c-11e5-9284-b827eb9e62be<commit_after>da307faa-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c442426c-2e4e-11e5-9284-b827eb9e62be<commit_msg>c447392a-2e4e-11e5-9284-b827eb9e62be<commit_after>c447392a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>60f7b930-2e4e-11e5-9284-b827eb9e62be<commit_msg>60fcc39e-2e4e-11e5-9284-b827eb9e62be<commit_after>60fcc39e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4c593530-2e4e-11e5-9284-b827eb9e62be<commit_msg>4c5e43d6-2e4e-11e5-9284-b827eb9e62be<commit_after>4c5e43d6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8517b64a-2e4d-11e5-9284-b827eb9e62be<commit_msg>851cad1c-2e4d-11e5-9284-b827eb9e62be<commit_after>851cad1c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>158207ae-2e4d-11e5-9284-b827eb9e62be<commit_msg>15871938-2e4d-11e5-9284-b827eb9e62be<commit_after>15871938-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0f682da8-2e4d-11e5-9284-b827eb9e62be<commit_msg>0f6d4144-2e4d-11e5-9284-b827eb9e62be<commit_after>0f6d4144-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>265e95ec-2e4d-11e5-9284-b827eb9e62be<commit_msg>26638c96-2e4d-11e5-9284-b827eb9e62be<commit_after>26638c96-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>811e445e-2e4e-11e5-9284-b827eb9e62be<commit_msg>81234d28-2e4e-11e5-9284-b827eb9e62be<commit_after>81234d28-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>50a79848-2e4e-11e5-9284-b827eb9e62be<commit_msg>50acc11a-2e4e-11e5-9284-b827eb9e62be<commit_after>50acc11a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8cae50ac-2e4e-11e5-9284-b827eb9e62be<commit_msg>8cb35c14-2e4e-11e5-9284-b827eb9e62be<commit_after>8cb35c14-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>4cd39474-2e4e-11e5-9284-b827eb9e62be<commit_msg>4cd8a59a-2e4e-11e5-9284-b827eb9e62be<commit_after>4cd8a59a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c550180a-2e4e-11e5-9284-b827eb9e62be<commit_msg>c55516fc-2e4e-11e5-9284-b827eb9e62be<commit_after>c55516fc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>928f7a74-2e4d-11e5-9284-b827eb9e62be<commit_msg>929dd934-2e4d-11e5-9284-b827eb9e62be<commit_after>929dd934-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f9f7050c-2e4c-11e5-9284-b827eb9e62be<commit_msg>f9fbfa3a-2e4c-11e5-9284-b827eb9e62be<commit_after>f9fbfa3a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>93f873a6-2e4e-11e5-9284-b827eb9e62be<commit_msg>93fd6b04-2e4e-11e5-9284-b827eb9e62be<commit_after>93fd6b04-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>46c0aec8-2e4e-11e5-9284-b827eb9e62be<commit_msg>46c5bc56-2e4e-11e5-9284-b827eb9e62be<commit_after>46c5bc56-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>a868a16c-2e4e-11e5-9284-b827eb9e62be<commit_msg>a86dae1e-2e4e-11e5-9284-b827eb9e62be<commit_after>a86dae1e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>1c639f38-2e4d-11e5-9284-b827eb9e62be<commit_msg>1c689484-2e4d-11e5-9284-b827eb9e62be<commit_after>1c689484-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3b881ece-2e4e-11e5-9284-b827eb9e62be<commit_msg>3b8d4638-2e4e-11e5-9284-b827eb9e62be<commit_after>3b8d4638-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>bd2181ca-2e4c-11e5-9284-b827eb9e62be<commit_msg>bd267324-2e4c-11e5-9284-b827eb9e62be<commit_after>bd267324-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b7fef838-2e4e-11e5-9284-b827eb9e62be<commit_msg>b80403aa-2e4e-11e5-9284-b827eb9e62be<commit_after>b80403aa-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e14b249c-2e4d-11e5-9284-b827eb9e62be<commit_msg>e15037a2-2e4d-11e5-9284-b827eb9e62be<commit_after>e15037a2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>db958d3a-2e4d-11e5-9284-b827eb9e62be<commit_msg>db9aa090-2e4d-11e5-9284-b827eb9e62be<commit_after>db9aa090-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>7a013736-2e4d-11e5-9284-b827eb9e62be<commit_msg>7a063a38-2e4d-11e5-9284-b827eb9e62be<commit_after>7a063a38-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d13fa112-2e4e-11e5-9284-b827eb9e62be<commit_msg>d1449f14-2e4e-11e5-9284-b827eb9e62be<commit_after>d1449f14-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d9a751c6-2e4c-11e5-9284-b827eb9e62be<commit_msg>d9ac7110-2e4c-11e5-9284-b827eb9e62be<commit_after>d9ac7110-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>edebe0a0-2e4e-11e5-9284-b827eb9e62be<commit_msg>edf0d5ce-2e4e-11e5-9284-b827eb9e62be<commit_after>edf0d5ce-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6b87b59e-2e4e-11e5-9284-b827eb9e62be<commit_msg>6b9243a6-2e4e-11e5-9284-b827eb9e62be<commit_after>6b9243a6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>f193754e-2e4c-11e5-9284-b827eb9e62be<commit_msg>f1988070-2e4c-11e5-9284-b827eb9e62be<commit_after>f1988070-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3a0de2b2-2e4f-11e5-9284-b827eb9e62be<commit_msg>3a12e37a-2e4f-11e5-9284-b827eb9e62be<commit_after>3a12e37a-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>8dd8fafa-2e4d-11e5-9284-b827eb9e62be<commit_msg>8dde0310-2e4d-11e5-9284-b827eb9e62be<commit_after>8dde0310-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>9a25187e-2e4e-11e5-9284-b827eb9e62be<commit_msg>9a2a9f24-2e4e-11e5-9284-b827eb9e62be<commit_after>9a2a9f24-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c68c21d4-2e4c-11e5-9284-b827eb9e62be<commit_msg>c6911522-2e4c-11e5-9284-b827eb9e62be<commit_after>c6911522-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>7839cba6-2e4e-11e5-9284-b827eb9e62be<commit_msg>783ecf52-2e4e-11e5-9284-b827eb9e62be<commit_after>783ecf52-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d7ce21d6-2e4c-11e5-9284-b827eb9e62be<commit_msg>d7d3302c-2e4c-11e5-9284-b827eb9e62be<commit_after>d7d3302c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>57014f14-2e4d-11e5-9284-b827eb9e62be<commit_msg>5706500e-2e4d-11e5-9284-b827eb9e62be<commit_after>5706500e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>bd78025a-2e4e-11e5-9284-b827eb9e62be<commit_msg>bd7d1402-2e4e-11e5-9284-b827eb9e62be<commit_after>bd7d1402-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0f521206-2e4e-11e5-9284-b827eb9e62be<commit_msg>0f570450-2e4e-11e5-9284-b827eb9e62be<commit_after>0f570450-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>14896d36-2e4f-11e5-9284-b827eb9e62be<commit_msg>148e7ede-2e4f-11e5-9284-b827eb9e62be<commit_after>148e7ede-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>72e32a2c-2e4d-11e5-9284-b827eb9e62be<commit_msg>72e82130-2e4d-11e5-9284-b827eb9e62be<commit_after>72e82130-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b7d220b6-2e4d-11e5-9284-b827eb9e62be<commit_msg>b7d7188c-2e4d-11e5-9284-b827eb9e62be<commit_after>b7d7188c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>764016c6-2e4d-11e5-9284-b827eb9e62be<commit_msg>76450ed8-2e4d-11e5-9284-b827eb9e62be<commit_after>76450ed8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>324656ce-2e4d-11e5-9284-b827eb9e62be<commit_msg>324b51f6-2e4d-11e5-9284-b827eb9e62be<commit_after>324b51f6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6f30c0c4-2e4d-11e5-9284-b827eb9e62be<commit_msg>6f35d32a-2e4d-11e5-9284-b827eb9e62be<commit_after>6f35d32a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3cd90758-2e4d-11e5-9284-b827eb9e62be<commit_msg>3cde0938-2e4d-11e5-9284-b827eb9e62be<commit_after>3cde0938-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>eeb97f20-2e4d-11e5-9284-b827eb9e62be<commit_msg>eebe78ae-2e4d-11e5-9284-b827eb9e62be<commit_after>eebe78ae-2e4d-11e5-9284-b827eb9e62be<|endoftext|>