text
stringlengths
54
60.6k
<commit_before>// // Player.cpp // CheckersProject // // Created by Benjamin Emdon on 2016-02-13. // Copyright © 2016 Ben Emdon. // #include "../include/Player.h" #include "../include/CheckersBoard.h" #include "../include/Button.h" #include "../include/GameState.h" Player::Player(bool topSide, CheckersBoard *board, Button buttons[]){ Board = board; boardButtons = buttons; initTeam(topSide); if (topSide) { turn = false; } else{ turn = true; } } Player::~Player(){ team.clear(); delete Board; Board = NULL; delete boardButtons; boardButtons = NULL; } void Player::initTeam(bool topSide) { if (topSide) { //----------------------------BLACK TEAM----------------------------\\ //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 0 team[0].x = 1; team[0].y = 0; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 1 team[1].x = 3; team[1].y = 0; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 2 team[2].x = 5; team[2].y = 0; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 3 team[3].x = 7; team[3].y = 0; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 4 team[4].x = 0; team[4].y = 1; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 5 team[5].x = 2; team[5].y = 1; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 6 team[6].x = 4; team[6].y = 1; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 7 team[7].x = 6; team[7].y = 1; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 8 team[8].x = 1; team[8].y = 2; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 9 team[9].x = 3; team[9].y = 2; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 10 team[10].x = 5; team[10].y = 2; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 11 team[11].x = 7; team[11].y = 2; //Sets teamNumberOnVirtualBoard teamNumberOnVirtualBoard = BLACK_PIECE; } else { //-----------------------------RED TEAM----------------------------\\ //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 0 team[0].x = 0; team[0].y = 7; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 1 team[1].x = 2; team[1].y = 7; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 2 team[2].x = 4; team[2].y = 7; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 3 team[3].x = 6; team[3].y = 7; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 4 team[4].x = 1; team[4].y = 6; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 5 team[5].x = 3; team[5].y = 6; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 6 team[6].x = 5; team[6].y = 6; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 7 team[7].x = 7; team[7].y = 6; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 8 team[8].x = 0; team[8].y = 5; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 9 team[9].x = 2; team[9].y = 5; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 10 team[10].x = 4; team[10].y = 5; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 11 team[11].x = 6; team[11].y = 5; //Sets teamNumberOnVirtualBoard teamNumberOnVirtualBoard = RED_PIECE; } // Update Virtual board after init // for (int teamIndex = 0; teamIndex < teamSize; teamIndex++) { Board->virtualBoard[team[teamIndex].x][team[teamIndex].y] = topSide + 1; } } bool Player::makeMove(SDL_Event *){ return false; } void Player::movePiece(int teamIndex, int newX, int newY){ //cout<<"enter move func"<<endl; // Moves piece if (abs(newX - team[teamIndex].x) == 2 && abs(newY - team[teamIndex].y) == 2) { killPiece(abs(newX + team[teamIndex].x)/2, abs(newY + team[teamIndex].y)/2); } //cout<<team[teamIndex].x<<","<<team[teamIndex].y<<" New place:"<<newX<<","<<newY<<endl; Board->virtualBoard[newX][newY] = Board->virtualBoard[team[teamIndex].x][team[teamIndex].y]; Board->virtualBoard[team[teamIndex].x][team[teamIndex].y] = EMPTY_PIECE; team[teamIndex].x = newX; team[teamIndex].y = newY; // Prints virtualBoard at end of move cout<<*Board<<endl; } void Player::killPiece(int x, int y) { Board->virtualBoard[x][y] = EMPTY_PIECE; } void Player::updateTeam() { for(int index=0;index<teamSize;index++){ if (Board->virtualBoard[team[index].x][team[index].y] != teamNumberOnVirtualBoard) { team.erase (team.begin()+index); teamSize--; cout<<"Team:\t"<<teamNumberOnVirtualBoard<<"\thas a TeamSize:\t" << teamSize <<endl; } } } int Player::pieceTeamIndexByXY(int x, int y) { int index=0; for(;index<teamSize;index++){ if((team[index].x == x) && (team[index].y == y)){ break; } } return index; } <commit_msg>Minor change<commit_after>// // Player.cpp // CheckersProject // // Created by Benjamin Emdon on 2016-02-13. // Copyright © 2016 Ben Emdon. // #include "../include/Player.h" #include "../include/CheckersBoard.h" #include "../include/Button.h" #include "../include/GameState.h" Player::Player(bool topSide, CheckersBoard *board, Button buttons[]){ Board = board; boardButtons = buttons; initTeam(topSide); if (topSide) { turn = false; } else{ turn = true; } } Player::~Player(){ team.clear(); delete Board; Board = NULL; delete boardButtons; boardButtons = NULL; } void Player::initTeam(bool topSide) { if (topSide) { //----------------------------BLACK TEAM----------------------------\\ //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 0 team[0].x = 1; team[0].y = 0; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 1 team[1].x = 3; team[1].y = 0; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 2 team[2].x = 5; team[2].y = 0; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 3 team[3].x = 7; team[3].y = 0; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 4 team[4].x = 0; team[4].y = 1; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 5 team[5].x = 2; team[5].y = 1; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 6 team[6].x = 4; team[6].y = 1; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 7 team[7].x = 6; team[7].y = 1; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 8 team[8].x = 1; team[8].y = 2; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 9 team[9].x = 3; team[9].y = 2; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 10 team[10].x = 5; team[10].y = 2; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 11 team[11].x = 7; team[11].y = 2; //Sets teamNumberOnVirtualBoard teamNumberOnVirtualBoard = BLACK_PIECE; } else { //-----------------------------RED TEAM----------------------------\\ //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 0 team[0].x = 0; team[0].y = 7; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 1 team[1].x = 2; team[1].y = 7; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 2 team[2].x = 4; team[2].y = 7; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 3 team[3].x = 6; team[3].y = 7; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 4 team[4].x = 1; team[4].y = 6; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 5 team[5].x = 3; team[5].y = 6; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 6 team[6].x = 5; team[6].y = 6; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 7 team[7].x = 7; team[7].y = 6; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 8 team[8].x = 0; team[8].y = 5; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 9 team[9].x = 2; team[9].y = 5; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 10 team[10].x = 4; team[10].y = 5; //Push back new chip created with default constructor. team.push_back(Piece()); //Vector now has 1 element @ index 11 team[11].x = 6; team[11].y = 5; //Sets teamNumberOnVirtualBoard teamNumberOnVirtualBoard = RED_PIECE; } // Update Virtual board after init // for (int teamIndex = 0; teamIndex < teamSize; teamIndex++) { Board->virtualBoard[team[teamIndex].x][team[teamIndex].y] = topSide + 1; } } bool Player::makeMove(SDL_Event *){ return false; } void Player::movePiece(int teamIndex, int newX, int newY){ //cout<<"enter move func"<<endl; // Moves piece if (abs(newX - team[teamIndex].x) == 2 && abs(newY - team[teamIndex].y) == 2) { killPiece(abs(newX + team[teamIndex].x)/2, abs(newY + team[teamIndex].y)/2); } //cout<<team[teamIndex].x<<","<<team[teamIndex].y<<" New place:"<<newX<<","<<newY<<endl; Board->virtualBoard[newX][newY] = Board->virtualBoard[team[teamIndex].x][team[teamIndex].y]; Board->virtualBoard[team[teamIndex].x][team[teamIndex].y] = EMPTY_PIECE; team[teamIndex].x = newX; team[teamIndex].y = newY; // Prints virtualBoard at end of move cout<<*Board<<endl; } void Player::killPiece(int x, int y) { Board->virtualBoard[x][y] = EMPTY_PIECE; } void Player::updateTeam() { for(int index=0;index<teamSize;index++){ if (Board->virtualBoard[team[index].x][team[index].y] != teamNumberOnVirtualBoard) { team.erase(team.begin()+index); teamSize--; cout<<"Team:\t"<<teamNumberOnVirtualBoard<<"\thas a TeamSize:\t" << teamSize <<endl; } } } int Player::pieceTeamIndexByXY(int x, int y) { int index=0; for(;index<teamSize;index++){ if((team[index].x == x) && (team[index].y == y)){ break; } } return index; } <|endoftext|>
<commit_before>// Toolbar.hh for Fluxbox // Copyright (c) 2002 Henrik Kinnunen (fluxgen at users.sourceforge.net) // // Toolbar.hh for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // $Id: Toolbar.hh,v 1.27 2003/04/16 13:43:48 rathnor Exp $ #ifndef TOOLBAR_HH #define TOOLBAR_HH #include "Timer.hh" #include "IconBar.hh" #include "ToolbarTheme.hh" #include "EventHandler.hh" #include "FbWindow.hh" #include "ArrowButton.hh" #include "Observer.hh" #include "XLayer.hh" #include "XLayerItem.hh" #include "LayerMenu.hh" #include "fluxbox.hh" #include <memory> class BScreen; namespace FbTk { class ImageControl; }; /// The toolbar. /** Handles iconbar, workspace name view and clock view */ class Toolbar : public FbTk::TimeoutHandler, public FbTk::EventHandler { public: ///Toolbar placement on the screen enum Placement{ // top and bottom placement TOPLEFT = 1, BOTTOMLEFT, TOPCENTER, BOTTOMCENTER, TOPRIGHT, BOTTOMRIGHT, // left and right placement LEFTCENTER, LEFTBOTTOM, LEFTTOP, RIGHTCENTER, RIGHTBOTTOM, RIGHTTOP }; /// create a toolbar on the screen with specific width explicit Toolbar(BScreen &screen, FbTk::XLayer &layer, FbTk::Menu &menu, size_t width = 200); /// destructor virtual ~Toolbar(); /// add icon to iconbar void addIcon(FluxboxWindow *w); /// remove icon from iconbar void delIcon(FluxboxWindow *w); /// remove all icons void delAllIcons(); bool containsIcon(FluxboxWindow &win); void enableIconBar(); void disableIconBar(); inline const FbTk::Menu &menu() const { return m_toolbarmenu; } inline FbTk::Menu &menu() { return m_toolbarmenu; } inline FbTk::Menu &placementMenu() { return m_placementmenu; } inline const FbTk::Menu &placementMenu() const { return m_placementmenu; } inline FbTk::Menu &layermenu() { return m_layermenu; } inline const FbTk::Menu &layermenu() const { return m_layermenu; } void moveToLayer(int layernum); FbTk::XLayerItem &getLayerItem() { return m_layeritem; } /// are we in workspacename editing? inline bool isEditing() const { return editing; } /// are we hidden? inline bool isHidden() const { return hidden; } /// do we auto hide the toolbar? inline bool doAutoHide() const { return do_auto_hide; } /// @return X window of the toolbar inline Window getWindowID() const { return frame.window.window(); } inline BScreen &screen() { return m_screen; } inline const BScreen &screen() const { return m_screen; } inline unsigned int width() const { return frame.width; } inline unsigned int height() const { return frame.height; } inline unsigned int exposedHeight() const { return ((do_auto_hide) ? frame.bevel_w : frame.height); } inline int x() const { return ((hidden) ? frame.x_hidden : frame.x); } inline int y() const { return ((hidden) ? frame.y_hidden : frame.y); } /// @return pointer to iconbar if it got one, else 0 inline const IconBar *iconBar() const { return m_iconbar.get(); } inline const ToolbarTheme &theme() const { return m_theme; } inline ToolbarTheme &theme() { return m_theme; } inline bool isVertical() const; /** @name eventhandlers */ //@{ void buttonPressEvent(XButtonEvent &be); void buttonReleaseEvent(XButtonEvent &be); void enterNotifyEvent(XCrossingEvent &ce); void leaveNotifyEvent(XCrossingEvent &ce); void exposeEvent(XExposeEvent &ee); void keyPressEvent(XKeyEvent &ke); //@} void redrawWindowLabel(bool redraw= false); void redrawWorkspaceLabel(bool redraw= false); /// enter edit mode on workspace label void edit(); void reconfigure(); void setPlacement(Placement where); void checkClock(bool redraw = false, bool date = false); virtual void timeout(); private: bool editing; ///< edit workspace label mode bool hidden; ///< hidden state bool do_auto_hide; ///< do we auto hide Display *display; ///< display connection /// Toolbar frame struct Frame { Frame(FbTk::EventHandler &evh, int screen_num); ~Frame(); Pixmap base, label, wlabel, clk, button, pbutton; FbTk::FbWindow window, workspace_label, window_label, clock; ArrowButton psbutton, nsbutton, pwbutton, nwbutton; int x, y, x_hidden, y_hidden, hour, minute, grab_x, grab_y; unsigned int width, height, window_label_w, workspace_label_w, clock_w, button_w, bevel_w, label_h; } frame; class HideHandler : public FbTk::TimeoutHandler { public: Toolbar *toolbar; virtual void timeout(); } hide_handler; friend class HideHandler; BScreen &m_screen; FbTk::ImageControl &image_ctrl; FbTk::Timer clock_timer; ///< timer to update clock FbTk::Timer hide_timer; ///< timer to for auto hide toolbar FbTk::Menu &m_toolbarmenu; FbTk::Menu m_placementmenu; LayerMenu<Toolbar> m_layermenu; std::auto_ptr<IconBar> m_iconbar; std::string new_workspace_name; ///< temp variable in edit workspace name mode ToolbarTheme m_theme; Placement m_place; //!! TODO this is just temporary class ThemeListener: public FbTk::Observer { public: ThemeListener(Toolbar &tb):m_tb(tb) { } void update(FbTk::Subject *subj) { m_tb.reconfigure(); } private: Toolbar &m_tb; }; ThemeListener m_themelistener; FbTk::XLayerItem m_layeritem; }; #endif // TOOLBAR_HH <commit_msg>minor fix<commit_after>// Toolbar.hh for Fluxbox // Copyright (c) 2002 Henrik Kinnunen (fluxgen at users.sourceforge.net) // // Toolbar.hh for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes (bhughes@tcac.net) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // $Id: Toolbar.hh,v 1.28 2003/04/23 00:13:47 fluxgen Exp $ #ifndef TOOLBAR_HH #define TOOLBAR_HH #include "Timer.hh" #include "IconBar.hh" #include "ToolbarTheme.hh" #include "EventHandler.hh" #include "FbWindow.hh" #include "ArrowButton.hh" #include "Observer.hh" #include "XLayer.hh" #include "XLayerItem.hh" #include "LayerMenu.hh" #include "fluxbox.hh" #include <memory> class BScreen; namespace FbTk { class ImageControl; }; /// The toolbar. /** Handles iconbar, workspace name view and clock view */ class Toolbar : public FbTk::TimeoutHandler, public FbTk::EventHandler { public: ///Toolbar placement on the screen enum Placement{ // top and bottom placement TOPLEFT = 1, BOTTOMLEFT, TOPCENTER, BOTTOMCENTER, TOPRIGHT, BOTTOMRIGHT, // left and right placement LEFTCENTER, LEFTBOTTOM, LEFTTOP, RIGHTCENTER, RIGHTBOTTOM, RIGHTTOP }; /// create a toolbar on the screen with specific width explicit Toolbar(BScreen &screen, FbTk::XLayer &layer, FbTk::Menu &menu, size_t width = 200); /// destructor virtual ~Toolbar(); /// add icon to iconbar void addIcon(FluxboxWindow *w); /// remove icon from iconbar void delIcon(FluxboxWindow *w); /// remove all icons void delAllIcons(); bool containsIcon(FluxboxWindow &win); void enableIconBar(); void disableIconBar(); inline const FbTk::Menu &menu() const { return m_toolbarmenu; } inline FbTk::Menu &menu() { return m_toolbarmenu; } inline FbTk::Menu &placementMenu() { return m_placementmenu; } inline const FbTk::Menu &placementMenu() const { return m_placementmenu; } inline FbTk::Menu &layermenu() { return m_layermenu; } inline const FbTk::Menu &layermenu() const { return m_layermenu; } void moveToLayer(int layernum); FbTk::XLayerItem &getLayerItem() { return m_layeritem; } /// are we in workspacename editing? inline bool isEditing() const { return editing; } /// are we hidden? inline bool isHidden() const { return hidden; } /// do we auto hide the toolbar? inline bool doAutoHide() const { return do_auto_hide; } /// @return X window of the toolbar inline const FbTk::FbWindow &window() const { return frame.window; } inline BScreen &screen() { return m_screen; } inline const BScreen &screen() const { return m_screen; } inline unsigned int width() const { return frame.width; } inline unsigned int height() const { return frame.height; } inline unsigned int exposedHeight() const { return ((do_auto_hide) ? frame.bevel_w : frame.height); } inline int x() const { return ((hidden) ? frame.x_hidden : frame.x); } inline int y() const { return ((hidden) ? frame.y_hidden : frame.y); } /// @return pointer to iconbar if it got one, else 0 inline const IconBar *iconBar() const { return m_iconbar.get(); } inline const ToolbarTheme &theme() const { return m_theme; } inline ToolbarTheme &theme() { return m_theme; } inline bool isVertical() const; /** @name eventhandlers */ //@{ void buttonPressEvent(XButtonEvent &be); void buttonReleaseEvent(XButtonEvent &be); void enterNotifyEvent(XCrossingEvent &ce); void leaveNotifyEvent(XCrossingEvent &ce); void exposeEvent(XExposeEvent &ee); void keyPressEvent(XKeyEvent &ke); //@} void redrawWindowLabel(bool redraw= false); void redrawWorkspaceLabel(bool redraw= false); /// enter edit mode on workspace label void edit(); void reconfigure(); void setPlacement(Placement where); void checkClock(bool redraw = false, bool date = false); virtual void timeout(); private: bool editing; ///< edit workspace label mode bool hidden; ///< hidden state bool do_auto_hide; ///< do we auto hide Display *display; ///< display connection /// Toolbar frame struct Frame { Frame(FbTk::EventHandler &evh, int screen_num); ~Frame(); Pixmap base, label, wlabel, clk, button, pbutton; FbTk::FbWindow window, workspace_label, window_label, clock; ArrowButton psbutton, nsbutton, pwbutton, nwbutton; int x, y, x_hidden, y_hidden, hour, minute, grab_x, grab_y; unsigned int width, height, window_label_w, workspace_label_w, clock_w, button_w, bevel_w, label_h; } frame; class HideHandler : public FbTk::TimeoutHandler { public: Toolbar *toolbar; virtual void timeout(); } hide_handler; friend class HideHandler; BScreen &m_screen; FbTk::ImageControl &image_ctrl; FbTk::Timer clock_timer; ///< timer to update clock FbTk::Timer hide_timer; ///< timer to for auto hide toolbar FbTk::Menu &m_toolbarmenu; FbTk::Menu m_placementmenu; LayerMenu<Toolbar> m_layermenu; std::auto_ptr<IconBar> m_iconbar; std::string new_workspace_name; ///< temp variable in edit workspace name mode ToolbarTheme m_theme; Placement m_place; //!! TODO this is just temporary class ThemeListener: public FbTk::Observer { public: ThemeListener(Toolbar &tb):m_tb(tb) { } void update(FbTk::Subject *subj) { m_tb.reconfigure(); } private: Toolbar &m_tb; }; ThemeListener m_themelistener; FbTk::XLayerItem m_layeritem; }; #endif // TOOLBAR_HH <|endoftext|>
<commit_before>/* * Copyright 2015 - 2016 gtalent2@gmail.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma #define offsetof(st, m) ((size_t)(&((st *)0)->m)) namespace wombat { namespace fs { typedef char int8_t; typedef unsigned char uint8_t; typedef short int16_t; typedef unsigned short uint16_t; typedef int int32_t; typedef unsigned int uint32_t; typedef unsigned uint_t; typedef long long int64_t; typedef unsigned long long uint64_t; typedef uint32_t Error; #if defined(_LP64) || defined(__ppc64__) || defined(_WIN64) typedef uint64_t size_t; #elif defined(_LP32) || defined(__ppc__) || defined(_WIN32) typedef uint32_t size_t; #else #error size_t undefined #endif } } <commit_msg>Missed a once in pragma once.<commit_after>/* * Copyright 2015 - 2016 gtalent2@gmail.com * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #pragma once #define offsetof(st, m) ((size_t)(&((st *)0)->m)) namespace wombat { namespace fs { typedef char int8_t; typedef unsigned char uint8_t; typedef short int16_t; typedef unsigned short uint16_t; typedef int int32_t; typedef unsigned int uint32_t; typedef unsigned uint_t; typedef long long int64_t; typedef unsigned long long uint64_t; typedef uint32_t Error; #if defined(_LP64) || defined(__ppc64__) || defined(_WIN64) typedef uint64_t size_t; #elif defined(_LP32) || defined(__ppc__) || defined(_WIN32) typedef uint32_t size_t; #else #error size_t undefined #endif } } <|endoftext|>
<commit_before>#include "binlog.h" #include "util/log.h" #include "util/strings.h" #include <map> /* Binlog */ Binlog::Binlog(uint64_t seq, char cmd, char type, const leveldb::Slice &key){ buf.append((char *)(&seq), sizeof(uint64_t)); buf.push_back(cmd); buf.push_back(type); buf.append(key.data(), key.size()); } uint64_t Binlog::seq() const{ return *((uint64_t *)(buf.data())); } char Binlog::type() const{ return buf[sizeof(uint64_t)]; } char Binlog::cmd() const{ return buf[sizeof(uint64_t) + 1]; } const Bytes Binlog::key() const{ return Bytes(buf.data() + HEADER_LEN, buf.size() - HEADER_LEN); } int Binlog::load(const leveldb::Slice &s){ if(s.size() < HEADER_LEN){ return -1; } buf.assign(s.data(), s.size()); return 0; } std::string Binlog::dumps() const{ std::string str; if(buf.size() < HEADER_LEN){ return str; } str.append("binlog# "); char buf[20]; snprintf(buf, sizeof(buf), "%llu ", this->seq()); str.append(buf); switch(this->type()){ case BinlogType::NOOP: str.append("noop "); break; case BinlogType::SYNC: str.append("sync "); break; case BinlogType::MIRROR: str.append("mirror "); break; case BinlogType::COPY: str.append("copy "); break; } switch(this->cmd()){ case BinlogCommand::NONE: str.append("none "); break; case BinlogCommand::KSET: str.append("set "); break; case BinlogCommand::KDEL: str.append("del "); break; case BinlogCommand::HSET: str.append("hset "); break; case BinlogCommand::HDEL: str.append("hdel "); break; case BinlogCommand::ZSET: str.append("zset "); break; case BinlogCommand::ZDEL: str.append("zdel "); break; case BinlogCommand::BEGIN: str.append("begin "); break; case BinlogCommand::END: str.append("end "); break; } Bytes b = this->key(); str.append(hexmem(b.data(), b.size())); return str; } /* SyncLogQueue */ static inline std::string encode_seq_key(uint64_t seq){ seq = big_endian(seq); std::string ret; ret.push_back(DataType::SYNCLOG); ret.append((char *)&seq, sizeof(seq)); return ret; } static inline uint64_t decode_seq_key(const leveldb::Slice &key){ uint64_t seq = 0; if(key.size() == (sizeof(uint64_t) + 1) && key.data()[0] == DataType::SYNCLOG){ seq = *((uint64_t *)(key.data() + 1)); seq = big_endian(seq); } return seq; } BinlogQueue::BinlogQueue(leveldb::DB *db){ this->db = db; this->min_seq = 0; this->last_seq = 0; this->tran_seq = 0; this->capacity = LOG_QUEUE_SIZE; Binlog log; if(this->find_last(&log) == 1){ this->last_seq = log.seq(); } if(this->find_next(1, &log) == 1){ this->min_seq = log.seq(); } log_debug("capacity: %d, min: %llu, max: %llu,", capacity, min_seq, last_seq); //this->merge(); /* int noops = 0; int total = 0; uint64_t seq = this->min_seq; while(this->find_next(seq, &log) == 1){ total ++; seq = log.seq() + 1; if(log.type() != BinlogType::NOOP){ std::string s = log.dumps(); //log_trace("%s", s.c_str()); noops ++; } } log_debug("capacity: %d, min: %llu, max: %llu, noops: %d, total: %d", capacity, min_seq, last_seq, noops, total); */ // start cleaning thread thread_quit = false; pthread_t tid; int err = pthread_create(&tid, NULL, &BinlogQueue::log_clean_thread_func, this); if(err != 0){ log_fatal("can't create thread: %s", strerror(err)); exit(0); } } BinlogQueue::~BinlogQueue(){ thread_quit = true; while(1){ if(thread_quit == false){ break; } usleep(100 * 1000); } log_debug("BinlogQueue finalized"); } void BinlogQueue::begin(){ tran_seq = last_seq; batch.Clear(); } void BinlogQueue::rollback(){ tran_seq = 0; } leveldb::Status BinlogQueue::commit(){ leveldb::WriteOptions write_opts; leveldb::Status s = db->Write(write_opts, &batch); if(s.ok()){ last_seq = tran_seq; tran_seq = 0; } return s; } void BinlogQueue::add(char type, char cmd, const leveldb::Slice &key){ tran_seq ++; Binlog log(tran_seq, type, cmd, key); batch.Put(encode_seq_key(tran_seq), log.repr()); } void BinlogQueue::add(char type, char cmd, const std::string &key){ leveldb::Slice s(key); this->add(type, cmd, s); } // leveldb put void BinlogQueue::Put(const leveldb::Slice& key, const leveldb::Slice& value){ batch.Put(key, value); } // leveldb delete void BinlogQueue::Delete(const leveldb::Slice& key){ batch.Delete(key); } int BinlogQueue::find_next(uint64_t next_seq, Binlog *log) const{ if(this->get(next_seq, log) == 1){ return 1; } uint64_t ret = 0; std::string key_str = encode_seq_key(next_seq); leveldb::ReadOptions iterate_options; leveldb::Iterator *it = db->NewIterator(iterate_options); it->Seek(key_str); if(it->Valid()){ leveldb::Slice key = it->key(); if(decode_seq_key(key) != 0){ leveldb::Slice val = it->value(); if(log->load(val) == -1){ ret = -1; }else{ ret = 1; } } } delete it; return ret; } int BinlogQueue::find_last(Binlog *log) const{ uint64_t ret = 0; std::string key_str = encode_seq_key(UINT64_MAX); leveldb::ReadOptions iterate_options; leveldb::Iterator *it = db->NewIterator(iterate_options); it->Seek(key_str); if(!it->Valid()){ // Iterator::prev requires Valid, so we seek to last it->SeekToLast(); } // UINT64_MAX is not used if(it->Valid()){ it->Prev(); } if(it->Valid()){ leveldb::Slice key = it->key(); if(decode_seq_key(key) != 0){ leveldb::Slice val = it->value(); if(log->load(val) == -1){ ret = -1; }else{ ret = 1; } } } delete it; return ret; } int BinlogQueue::get(uint64_t seq, Binlog *log) const{ std::string val; leveldb::Status s = db->Get(leveldb::ReadOptions(), encode_seq_key(seq), &val); if(s.ok()){ if(log->load(val) != -1){ return 1; } } return 0; } int BinlogQueue::update(uint64_t seq, char type, char cmd, const std::string &key){ Binlog log(seq, type, cmd, key); leveldb::Status s = db->Put(leveldb::WriteOptions(), encode_seq_key(seq), log.repr()); if(s.ok()){ return 0; } return -1; } int BinlogQueue::del(uint64_t seq){ leveldb::Status s = db->Delete(leveldb::WriteOptions(), encode_seq_key(seq)); if(!s.ok()){ return -1; } return 0; } int BinlogQueue::del_range(uint64_t start, uint64_t end){ while(start <= end){ leveldb::WriteBatch batch; for(int count = 0; start <= end && count < 1000; start++, count++){ batch.Delete(encode_seq_key(start)); } leveldb::Status s = db->Write(leveldb::WriteOptions(), &batch); if(!s.ok()){ return -1; } } return 0; } void* BinlogQueue::log_clean_thread_func(void *arg){ BinlogQueue *logs = (BinlogQueue *)arg; while(!logs->thread_quit){ usleep(200 * 1000); if(logs->last_seq - logs->min_seq < LOG_QUEUE_SIZE * 1.1){ continue; } uint64_t start = logs->min_seq; uint64_t end = logs->last_seq - LOG_QUEUE_SIZE; logs->del_range(start, end); logs->min_seq = end + 1; log_debug("clean %d logs[%llu ~ %llu], %d left, max: %llu", end-start+1, start, end, logs->last_seq - logs->min_seq + 1, logs->last_seq); } log_debug("clean_thread quit"); logs->thread_quit = false; return (void *)NULL; } // TESTING, slow, so not used void BinlogQueue::merge(){ std::map<std::string, uint64_t> key_map; uint64_t start = min_seq; uint64_t end = last_seq; int reduce_count = 0; int total = end - start + 1; log_trace("merge begin"); for(; start <= end; start++){ Binlog log; if(this->get(start, &log) == 1){ if(log.type() == BinlogType::NOOP){ continue; } std::string key = log.key().String(); std::map<std::string, uint64_t>::iterator it = key_map.find(key); if(it != key_map.end()){ uint64_t seq = it->second; this->update(seq, BinlogType::NOOP, BinlogCommand::NONE, ""); //log_trace("merge update %llu to NOOP", seq); reduce_count ++; } key_map[key] = log.seq(); } } log_trace("merge reduce %d of %d binlogs", reduce_count, total); } <commit_msg>update<commit_after>#include "binlog.h" #include "util/log.h" #include "util/strings.h" #include <map> /* Binlog */ Binlog::Binlog(uint64_t seq, char cmd, char type, const leveldb::Slice &key){ buf.append((char *)(&seq), sizeof(uint64_t)); buf.push_back(cmd); buf.push_back(type); buf.append(key.data(), key.size()); } uint64_t Binlog::seq() const{ return *((uint64_t *)(buf.data())); } char Binlog::type() const{ return buf[sizeof(uint64_t)]; } char Binlog::cmd() const{ return buf[sizeof(uint64_t) + 1]; } const Bytes Binlog::key() const{ return Bytes(buf.data() + HEADER_LEN, buf.size() - HEADER_LEN); } int Binlog::load(const leveldb::Slice &s){ if(s.size() < HEADER_LEN){ return -1; } buf.assign(s.data(), s.size()); return 0; } std::string Binlog::dumps() const{ std::string str; if(buf.size() < HEADER_LEN){ return str; } str.append("binlog# "); char buf[20]; snprintf(buf, sizeof(buf), "%llu ", this->seq()); str.append(buf); switch(this->type()){ case BinlogType::NOOP: str.append("noop "); break; case BinlogType::SYNC: str.append("sync "); break; case BinlogType::MIRROR: str.append("mirror "); break; case BinlogType::COPY: str.append("copy "); break; } switch(this->cmd()){ case BinlogCommand::NONE: str.append("none "); break; case BinlogCommand::KSET: str.append("set "); break; case BinlogCommand::KDEL: str.append("del "); break; case BinlogCommand::HSET: str.append("hset "); break; case BinlogCommand::HDEL: str.append("hdel "); break; case BinlogCommand::ZSET: str.append("zset "); break; case BinlogCommand::ZDEL: str.append("zdel "); break; case BinlogCommand::BEGIN: str.append("begin "); break; case BinlogCommand::END: str.append("end "); break; } Bytes b = this->key(); str.append(hexmem(b.data(), b.size())); return str; } /* SyncLogQueue */ static inline std::string encode_seq_key(uint64_t seq){ seq = big_endian(seq); std::string ret; ret.push_back(DataType::SYNCLOG); ret.append((char *)&seq, sizeof(seq)); return ret; } static inline uint64_t decode_seq_key(const leveldb::Slice &key){ uint64_t seq = 0; if(key.size() == (sizeof(uint64_t) + 1) && key.data()[0] == DataType::SYNCLOG){ seq = *((uint64_t *)(key.data() + 1)); seq = big_endian(seq); } return seq; } BinlogQueue::BinlogQueue(leveldb::DB *db){ this->db = db; this->min_seq = 0; this->last_seq = 0; this->tran_seq = 0; this->capacity = LOG_QUEUE_SIZE; Binlog log; if(this->find_last(&log) == 1){ this->last_seq = log.seq(); } if(this->find_next(1, &log) == 1){ this->min_seq = log.seq(); } log_debug("capacity: %d, min: %llu, max: %llu,", capacity, min_seq, last_seq); //this->merge(); /* int noops = 0; int total = 0; uint64_t seq = this->min_seq; while(this->find_next(seq, &log) == 1){ total ++; seq = log.seq() + 1; if(log.type() != BinlogType::NOOP){ std::string s = log.dumps(); //log_trace("%s", s.c_str()); noops ++; } } log_debug("capacity: %d, min: %llu, max: %llu, noops: %d, total: %d", capacity, min_seq, last_seq, noops, total); */ // start cleaning thread thread_quit = false; pthread_t tid; int err = pthread_create(&tid, NULL, &BinlogQueue::log_clean_thread_func, this); if(err != 0){ log_fatal("can't create thread: %s", strerror(err)); exit(0); } } BinlogQueue::~BinlogQueue(){ thread_quit = true; while(1){ if(thread_quit == false){ break; } usleep(100 * 1000); } log_debug("BinlogQueue finalized"); } void BinlogQueue::begin(){ tran_seq = last_seq; batch.Clear(); } void BinlogQueue::rollback(){ tran_seq = 0; } leveldb::Status BinlogQueue::commit(){ leveldb::WriteOptions write_opts; leveldb::Status s = db->Write(write_opts, &batch); if(s.ok()){ last_seq = tran_seq; tran_seq = 0; } return s; } void BinlogQueue::add(char type, char cmd, const leveldb::Slice &key){ tran_seq ++; Binlog log(tran_seq, type, cmd, key); batch.Put(encode_seq_key(tran_seq), log.repr()); } void BinlogQueue::add(char type, char cmd, const std::string &key){ leveldb::Slice s(key); this->add(type, cmd, s); } // leveldb put void BinlogQueue::Put(const leveldb::Slice& key, const leveldb::Slice& value){ batch.Put(key, value); } // leveldb delete void BinlogQueue::Delete(const leveldb::Slice& key){ batch.Delete(key); } int BinlogQueue::find_next(uint64_t next_seq, Binlog *log) const{ if(this->get(next_seq, log) == 1){ return 1; } uint64_t ret = 0; std::string key_str = encode_seq_key(next_seq); leveldb::ReadOptions iterate_options; leveldb::Iterator *it = db->NewIterator(iterate_options); it->Seek(key_str); if(it->Valid()){ leveldb::Slice key = it->key(); if(decode_seq_key(key) != 0){ leveldb::Slice val = it->value(); if(log->load(val) == -1){ ret = -1; }else{ ret = 1; } } } delete it; return ret; } int BinlogQueue::find_last(Binlog *log) const{ uint64_t ret = 0; std::string key_str = encode_seq_key(UINT64_MAX); leveldb::ReadOptions iterate_options; leveldb::Iterator *it = db->NewIterator(iterate_options); it->Seek(key_str); if(!it->Valid()){ // Iterator::prev requires Valid, so we seek to last it->SeekToLast(); } // UINT64_MAX is not used if(it->Valid()){ it->Prev(); } if(it->Valid()){ leveldb::Slice key = it->key(); if(decode_seq_key(key) != 0){ leveldb::Slice val = it->value(); if(log->load(val) == -1){ ret = -1; }else{ ret = 1; } } } delete it; return ret; } int BinlogQueue::get(uint64_t seq, Binlog *log) const{ std::string val; leveldb::Status s = db->Get(leveldb::ReadOptions(), encode_seq_key(seq), &val); if(s.ok()){ if(log->load(val) != -1){ return 1; } } return 0; } int BinlogQueue::update(uint64_t seq, char type, char cmd, const std::string &key){ Binlog log(seq, type, cmd, key); leveldb::Status s = db->Put(leveldb::WriteOptions(), encode_seq_key(seq), log.repr()); if(s.ok()){ return 0; } return -1; } int BinlogQueue::del(uint64_t seq){ leveldb::Status s = db->Delete(leveldb::WriteOptions(), encode_seq_key(seq)); if(!s.ok()){ return -1; } return 0; } int BinlogQueue::del_range(uint64_t start, uint64_t end){ while(start <= end){ leveldb::WriteBatch batch; for(int count = 0; start <= end && count < 1000; start++, count++){ batch.Delete(encode_seq_key(start)); } leveldb::Status s = db->Write(leveldb::WriteOptions(), &batch); if(!s.ok()){ return -1; } } return 0; } void* BinlogQueue::log_clean_thread_func(void *arg){ BinlogQueue *logs = (BinlogQueue *)arg; while(!logs->thread_quit){ usleep(200 * 1000); if(logs->last_seq - logs->min_seq < LOG_QUEUE_SIZE * 1.1){ continue; } uint64_t start = logs->min_seq; uint64_t end = logs->last_seq - LOG_QUEUE_SIZE; logs->del_range(start, end); logs->min_seq = end + 1; log_debug("clean %d logs[%llu ~ %llu], %d left, max: %llu", end-start+1, start, end, logs->last_seq - logs->min_seq + 1, logs->last_seq); } log_debug("clean_thread quit"); logs->thread_quit = false; return (void *)NULL; } // TESTING, slow, so not used void BinlogQueue::merge(){ std::map<std::string, uint64_t> key_map; uint64_t start = min_seq; uint64_t end = last_seq; int reduce_count = 0; int total = 0; total = end - start + 1; log_trace("merge begin"); for(; start <= end; start++){ Binlog log; if(this->get(start, &log) == 1){ if(log.type() == BinlogType::NOOP){ continue; } std::string key = log.key().String(); std::map<std::string, uint64_t>::iterator it = key_map.find(key); if(it != key_map.end()){ uint64_t seq = it->second; this->update(seq, BinlogType::NOOP, BinlogCommand::NONE, ""); //log_trace("merge update %llu to NOOP", seq); reduce_count ++; } key_map[key] = log.seq(); } } log_trace("merge reduce %d of %d binlogs", reduce_count, total); } <|endoftext|>
<commit_before><commit_msg>New scom addresses const headers for chip 9031<commit_after><|endoftext|>
<commit_before><commit_msg>Solved problem3 for smaller numbers, still not done<commit_after>#include <iostream> using namespace std; int nextPrime(int prev); int main() { long number = 100054040; int max = 0; int prime = 1; cout << prime << endl; // for (int i = 0; i < 20; i++) { // prime = nextPrime(prime); // cout << prime << endl; // } while (prime < number) { prime = nextPrime(prime); if (number % prime == 0) { max = prime; } } cout << max << endl; } int nextPrime(int prev) { if (prev == 1) return 2; else { bool flag = true; prev = prev + 1; for (int i = 2; i < prev; i++) { if (prev % i == 0) { flag = false; } } if (flag) { return prev; } else { return nextPrime(prev); } } } <|endoftext|>
<commit_before>#include <sysexits.h> #include <unistd.h> #include <iostream> #include <sys/types.h> #include <signal.h> #include <libpstack/dwarf.h> #include <libpstack/dump.h> #include <libpstack/elf.h> #include <libpstack/proc.h> #include <libpstack/ps_callback.h> struct ThreadLister { std::list<ThreadStack> threadStacks; Process *process; ThreadLister(Process *process_ ) : process(process_) {} void operator() (const td_thrhandle_t *thr) { CoreRegisters regs; td_err_e the; #ifdef __linux__ the = td_thr_getgregs(thr, (elf_greg_t *) &regs); #else the = td_thr_getgregs(thr, &regs); #endif if (the == TD_OK) { threadStacks.push_back(ThreadStack()); td_thr_get_info(thr, &threadStacks.back().info); threadStacks.back().unwind(*process, regs); } } }; static int usage(void); std::ostream & pstack(Process &proc, std::ostream &os, const PstackOptions &options) { // get its back trace. ThreadLister threadLister(&proc); { StopProcess here(&proc); proc.listThreads(threadLister); if (threadLister.threadStacks.empty()) { // get the register for the process itself, and use those. CoreRegisters regs; proc.getRegs(ps_getpid(&proc), &regs); threadLister.threadStacks.push_back(ThreadStack()); threadLister.threadStacks.back().unwind(proc, regs); } } /* * resume at this point - maybe a bit optimistic if a shared library gets * unloaded while we print stuff out, but worth the risk, normally. */ for (auto s = threadLister.threadStacks.begin(); s != threadLister.threadStacks.end(); ++s) { proc.dumpStackText(os, *s, options); os << "\n"; } return os; } static void doPstack(Process &proc, const PstackOptions &options) { proc.load(); pstack(proc, std::cout, options); } int emain(int argc, char **argv) { int error, i, c; pid_t pid; std::string execFile; std::shared_ptr<ElfObject> exec; PstackOptions options; noDebugLibs = true; while ((c = getopt(argc, argv, "d:D:hsvnag:")) != -1) { switch (c) { case 'g': globalDebugDirectories.add(optarg); break; case 'D': { auto dumpobj = std::make_shared<ElfObject>(std::make_shared<FileReader>(optarg, -1)); DwarfInfo di(ElfObject::getDebug(dumpobj)); std::cout << di; return 0; } case 'd': { /* Undocumented option to dump image contents */ std::cout << ElfObject(std::make_shared<FileReader>(optarg, -1)); return 0; } case 'h': usage(); return (0); case 'a': options += PstackOptions::dwarfish; break; case 's': options += PstackOptions::nosrc; break; case 'v': debug = &std::clog; break; case 'n': noDebugLibs = false; break; default: return usage(); } } if (optind == argc) return usage(); for (error = 0, i = optind; i < argc; i++) { pid = atoi(argv[i]); if (pid == 0 || (kill(pid, 0) == -1 && errno == ESRCH)) { // It's a file: should be ELF, treat core and exe differently auto obj = std::make_shared<ElfObject>(std::make_shared<FileReader>(argv[i])); if (obj->getElfHeader().e_type == ET_CORE) { CoreProcess proc(exec, obj, PathReplacementList()); doPstack(proc, options); } else { exec = obj; } } else { LiveProcess proc(exec, pid, PathReplacementList()); doPstack(proc, options); } } return (error); } int main(int argc, char **argv) { try { emain(argc, argv); } catch (std::exception &ex) { std::clog << "error: " << ex.what() << std::endl; } } static int usage(void) { std::clog << "usage: pstack\n\t" "[-<D|d> <elf object>] dump details of ELF object (D => show DWARF info\n" "[-D <elf object>] dump details of ELF object (including DWARF info)\n\t" "[-E <elf object>] print name of executable that generated a core)\n\t" "or\n\t" "[-h] show this message\n" "or\n\t" "[-v] include verbose information to stderr\n\t" "[-s] don't include source-level details\n\t" "[-g] add global debug directory\n\t" "[<pid>|<core>|<executable>]* list cores and pids to examine. An executable\n\t" " will override use of in-core or in-process information\n\t" " to predict location of the executable\n" ; return (EX_USAGE); } <commit_msg>Invert meaning of 'n' now that it works and is fast.<commit_after>#include <sysexits.h> #include <unistd.h> #include <iostream> #include <sys/types.h> #include <signal.h> #include <libpstack/dwarf.h> #include <libpstack/dump.h> #include <libpstack/elf.h> #include <libpstack/proc.h> #include <libpstack/ps_callback.h> struct ThreadLister { std::list<ThreadStack> threadStacks; Process *process; ThreadLister(Process *process_ ) : process(process_) {} void operator() (const td_thrhandle_t *thr) { CoreRegisters regs; td_err_e the; #ifdef __linux__ the = td_thr_getgregs(thr, (elf_greg_t *) &regs); #else the = td_thr_getgregs(thr, &regs); #endif if (the == TD_OK) { threadStacks.push_back(ThreadStack()); td_thr_get_info(thr, &threadStacks.back().info); threadStacks.back().unwind(*process, regs); } } }; static int usage(void); std::ostream & pstack(Process &proc, std::ostream &os, const PstackOptions &options) { // get its back trace. ThreadLister threadLister(&proc); { StopProcess here(&proc); proc.listThreads(threadLister); if (threadLister.threadStacks.empty()) { // get the register for the process itself, and use those. CoreRegisters regs; proc.getRegs(ps_getpid(&proc), &regs); threadLister.threadStacks.push_back(ThreadStack()); threadLister.threadStacks.back().unwind(proc, regs); } } /* * resume at this point - maybe a bit optimistic if a shared library gets * unloaded while we print stuff out, but worth the risk, normally. */ for (auto s = threadLister.threadStacks.begin(); s != threadLister.threadStacks.end(); ++s) { proc.dumpStackText(os, *s, options); os << "\n"; } return os; } static void doPstack(Process &proc, const PstackOptions &options) { proc.load(); pstack(proc, std::cout, options); } int emain(int argc, char **argv) { int error, i, c; pid_t pid; std::string execFile; std::shared_ptr<ElfObject> exec; PstackOptions options; noDebugLibs = false; while ((c = getopt(argc, argv, "d:D:hsvnag:")) != -1) { switch (c) { case 'g': globalDebugDirectories.add(optarg); break; case 'D': { auto dumpobj = std::make_shared<ElfObject>(std::make_shared<FileReader>(optarg, -1)); DwarfInfo di(ElfObject::getDebug(dumpobj)); std::cout << di; return 0; } case 'd': { /* Undocumented option to dump image contents */ std::cout << ElfObject(std::make_shared<FileReader>(optarg, -1)); return 0; } case 'h': usage(); return (0); case 'a': options += PstackOptions::dwarfish; break; case 's': options += PstackOptions::nosrc; break; case 'v': debug = &std::clog; break; case 'n': noDebugLibs = true; break; default: return usage(); } } if (optind == argc) return usage(); for (error = 0, i = optind; i < argc; i++) { pid = atoi(argv[i]); if (pid == 0 || (kill(pid, 0) == -1 && errno == ESRCH)) { // It's a file: should be ELF, treat core and exe differently auto obj = std::make_shared<ElfObject>(std::make_shared<FileReader>(argv[i])); if (obj->getElfHeader().e_type == ET_CORE) { CoreProcess proc(exec, obj, PathReplacementList()); doPstack(proc, options); } else { exec = obj; } } else { LiveProcess proc(exec, pid, PathReplacementList()); doPstack(proc, options); } } return (error); } int main(int argc, char **argv) { try { emain(argc, argv); } catch (std::exception &ex) { std::clog << "error: " << ex.what() << std::endl; } } static int usage(void) { std::clog << "usage: pstack\n\t" "[-<D|d> <elf object>] dump details of ELF object (D => show DWARF info\n" "[-D <elf object>] dump details of ELF object (including DWARF info)\n\t" "[-E <elf object>] print name of executable that generated a core)\n\t" "or\n\t" "[-h] show this message\n" "or\n\t" "[-v] include verbose information to stderr\n\t" "[-s] don't include source-level details\n\t" "[-g] add global debug directory\n\t" "[<pid>|<core>|<executable>]* list cores and pids to examine. An executable\n\t" " will override use of in-core or in-process information\n\t" " to predict location of the executable\n" ; return (EX_USAGE); } <|endoftext|>
<commit_before>/* net6 - Library providing IPv4/IPv6 network access * Copyright (C) 2005 Armin Burgmeier / 0x539 dev group * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdexcept> #include "config.hpp" #include "common.hpp" #include "gettext_package.hpp" #ifdef ENABLE_NLS namespace { net6::gettext_package* local_package = NULL; } #endif void net6::init_gettext(gettext_package& package) { #ifdef ENABLE_NLS local_package = &package; #endif } const char* net6::_(const char* msgid) { if(local_package == NULL) { throw std::logic_error( "FreeIsle::net6::_:\n" "init_gettext() has not yet been called. Most " "certainly this means that you have\n" "not created a net6::main object." ); } #ifdef ENABLE_NLS return local_package->gettext(msgid); #else return msgid; #endif } <commit_msg>[project @ Fix misplaced NLS conditional]<commit_after>/* net6 - Library providing IPv4/IPv6 network access * Copyright (C) 2005 Armin Burgmeier / 0x539 dev group * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdexcept> #include "config.hpp" #include "common.hpp" #include "gettext_package.hpp" #ifdef ENABLE_NLS namespace { net6::gettext_package* local_package = NULL; } #endif void net6::init_gettext(gettext_package& package) { #ifdef ENABLE_NLS local_package = &package; #endif } const char* net6::_(const char* msgid) { #ifdef ENABLE_NLS if(local_package == NULL) { throw std::logic_error( "net6::_:\n" "init_gettext() has not yet been called. Most " "This certainly means that you have\n" "not created a net6::main object." ); } return local_package->gettext(msgid); #else return msgid; #endif } <|endoftext|>
<commit_before>#pragma once #include <iostream> #include <sstream> #include <distributions/random_fwd.hpp> #include <distributions/vector.hpp> #ifdef __GNUG__ # define LOOM_LIKELY(x) __builtin_expect(bool(x), true) # define LOOM_UNLIKELY(x) __builtin_expect(bool(x), false) #else // __GNUG__ # warning "ignoring LOOM_LIKELY(-), LOOM_UNLIKELY(-)" # define LOOM_LIKELY(x) (x) # define LOOM_UNLIKELY(x) (x) #endif // __GNUG__ #ifndef LOOM_DEBUG_LEVEL # define LOOM_DEBUG_LEVEL 0 #endif // LOOM_DEBUG_LEVEL #define LOOM_ERROR(message) {\ std::cerr << "ERROR " << message << "\n\t"\ << __FILE__ << " : " << __LINE__ << "\n\t"\ << __PRETTY_FUNCTION__ << std::endl; \ abort(); } #define LOOM_DEBUG(message) {\ std::ostringstream private_message; \ private_message << "DEBUG " << message << '\n'; \ std::cout << private_message.str() << std::flush; } #define LOOM_ASSERT(cond, message) \ { if (LOOM_UNLIKELY(not (cond))) LOOM_ERROR(message) } #define LOOM_ASSERT_EQ(x, y) \ LOOM_ASSERT((x) == (y), \ "expected " #x " == " #y "; actual " << (x) << " vs " << (y)) #define LOOM_ASSERT_LE(x, y) \ LOOM_ASSERT((x) <= (y), \ "expected " #x " <= " #y "; actual " << (x) << " vs " << (y)) #define LOOM_ASSERT_LT(x, y) \ LOOM_ASSERT((x) < (y), \ "expected " #x " < " #y "; actual " << (x) << " vs " << (y)) #define LOOM_ASSERT_NE(x, y) \ LOOM_ASSERT((x) != (y), \ "expected " #x " != " #y "; actual " << (x) << " vs " << (y)) #define LOOM_ASSERT_(level, cond, message) \ { if (LOOM_DEBUG_LEVEL >= (level)) LOOM_ASSERT(cond, message) } #define LOOM_ASSERT1(cond, message) LOOM_ASSERT_(1, cond, message) #define LOOM_ASSERT2(cond, message) LOOM_ASSERT_(2, cond, message) #define LOOM_ASSERT3(cond, message) LOOM_ASSERT_(3, cond, message) #define TODO(message) LOOM_ERROR("TODO " << message) namespace loom { using distributions::rng_t; using distributions::VectorFloat; class noncopyable { noncopyable (const noncopyable &) = delete; void operator= (const noncopyable &) = delete; public: noncopyable () {} }; template<class Value, typename... Args> void inplace_destroy_and_construct (Value & value, Args... args) { value->~Value(); new (& value) Value(args...); } template<class T, class Alloc> inline std::ostream & operator<< ( std::ostream & os, const std::vector<T, Alloc> & vect) { if (vect.empty()) { return os << "[]"; } else { os << '[' << vect[0]; for (size_t i = 1; i < vect.size(); ++i) { os << ", " << vect[i]; } return os << ']'; } } } // namespace loom <commit_msg>Make LOOM_ERROR macro print atomically<commit_after>#pragma once #include <iostream> #include <sstream> #include <distributions/random_fwd.hpp> #include <distributions/vector.hpp> #ifdef __GNUG__ # define LOOM_LIKELY(x) __builtin_expect(bool(x), true) # define LOOM_UNLIKELY(x) __builtin_expect(bool(x), false) #else // __GNUG__ # warning "ignoring LOOM_LIKELY(-), LOOM_UNLIKELY(-)" # define LOOM_LIKELY(x) (x) # define LOOM_UNLIKELY(x) (x) #endif // __GNUG__ #define LOOM_ERROR(message) { \ std::ostringstream PRIVATE_message; \ PRIVATE_message \ << "ERROR " << message << "\n\t" \ << __FILE__ << " : " << __LINE__ << "\n\t" \ << __PRETTY_FUNCTION__ << '\n'; \ std::cerr << PRIVATE_message.str() << std::flush; \ abort(); } #define LOOM_DEBUG(message) { \ std::ostringstream PRIVATE_message; \ PRIVATE_message << "DEBUG " << message << '\n'; \ std::cout << PRIVATE_message.str() << std::flush; } #define LOOM_ASSERT(cond, message) \ { if (LOOM_UNLIKELY(not (cond))) LOOM_ERROR(message) } #define LOOM_ASSERT_EQ(x, y) \ LOOM_ASSERT((x) == (y), \ "expected " #x " == " #y "; actual " << (x) << " vs " << (y)) #define LOOM_ASSERT_LE(x, y) \ LOOM_ASSERT((x) <= (y), \ "expected " #x " <= " #y "; actual " << (x) << " vs " << (y)) #define LOOM_ASSERT_LT(x, y) \ LOOM_ASSERT((x) < (y), \ "expected " #x " < " #y "; actual " << (x) << " vs " << (y)) #define LOOM_ASSERT_NE(x, y) \ LOOM_ASSERT((x) != (y), \ "expected " #x " != " #y "; actual " << (x) << " vs " << (y)) #ifndef LOOM_DEBUG_LEVEL # define LOOM_DEBUG_LEVEL 0 #endif // LOOM_DEBUG_LEVEL #define LOOM_ASSERT_(level, cond, message) \ { if (LOOM_DEBUG_LEVEL >= (level)) LOOM_ASSERT(cond, message) } #define LOOM_ASSERT1(cond, message) LOOM_ASSERT_(1, cond, message) #define LOOM_ASSERT2(cond, message) LOOM_ASSERT_(2, cond, message) #define LOOM_ASSERT3(cond, message) LOOM_ASSERT_(3, cond, message) #define TODO(message) LOOM_ERROR("TODO " << message) namespace loom { using distributions::rng_t; using distributions::VectorFloat; class noncopyable { noncopyable (const noncopyable &) = delete; void operator= (const noncopyable &) = delete; public: noncopyable () {} }; template<class Value, typename... Args> void inplace_destroy_and_construct (Value & value, Args... args) { value->~Value(); new (& value) Value(args...); } template<class T, class Alloc> inline std::ostream & operator<< ( std::ostream & os, const std::vector<T, Alloc> & vect) { if (vect.empty()) { return os << "[]"; } else { os << '[' << vect[0]; for (size_t i = 1; i < vect.size(); ++i) { os << ", " << vect[i]; } return os << ']'; } } } // namespace loom <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, 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 <planning_models/transforms.h> #include <ros/console.h> bool planning_models::quatFromMsg(const geometry_msgs::Quaternion &qmsg, Eigen::Quaterniond &q) { q = Eigen::Quaterniond(qmsg.w, qmsg.x, qmsg.y, qmsg.z); double error = fabs(q.squaredNorm() - 1.0); if (error > 0.1) { ROS_ERROR("Quaternion is NOWHERE CLOSE TO NORMALIZED. Can't do much, returning identity."); q = Eigen::Quaterniond(1.0, 0.0, 0.0, 0.0); return false; } else if(error > 1e-3) q.normalize(); return true; } bool planning_models::poseFromMsg(const geometry_msgs::Pose &tmsg, Eigen::Affine3d &t) { Eigen::Quaterniond q; bool r = quatFromMsg(tmsg.orientation, q); t = Eigen::Affine3d(Eigen::Translation3d(tmsg.position.x, tmsg.position.y, tmsg.position.z)*q.toRotationMatrix()); return r; } void planning_models::msgFromPose(const Eigen::Affine3d &t, geometry_msgs::Pose &tmsg) { tmsg.position.x = t.translation().x(); tmsg.position.y = t.translation().y(); tmsg.position.z = t.translation().z(); Eigen::Quaterniond q(t.rotation()); tmsg.orientation.x = q.x(); tmsg.orientation.y = q.y(); tmsg.orientation.z = q.z(); tmsg.orientation.w = q.w(); } void planning_models::msgFromPose(const Eigen::Affine3d &t, geometry_msgs::Transform &tmsg) { tmsg.translation.x = t.translation().x(); tmsg.translation.y = t.translation().y(); tmsg.translation.z = t.translation().z(); Eigen::Quaterniond q(t.rotation()); tmsg.rotation.x = q.x(); tmsg.rotation.y = q.y(); tmsg.rotation.z = q.z(); tmsg.rotation.w = q.w(); } planning_models::Transforms::Transforms(const std::string &target_frame) : target_frame_(target_frame) { Eigen::Affine3d t; t.setIdentity(); transforms_[target_frame_] = t; } planning_models::Transforms::Transforms(const Transforms &other) : target_frame_(other.target_frame_), transforms_(other.transforms_) { } planning_models::Transforms::~Transforms(void) { } const std::string& planning_models::Transforms::getTargetFrame(void) const { return target_frame_; } const planning_models::EigenAffine3dMapType& planning_models::Transforms::getAllTransforms(void) const { return transforms_; } bool planning_models::Transforms::isFixedFrame(const std::string &frame) const { return transforms_.find(frame) != transforms_.end(); } const Eigen::Affine3d& planning_models::Transforms::getTransform(const std::string &from_frame) const { EigenAffine3dMapType::const_iterator it = transforms_.find(from_frame); if (it != transforms_.end()) return it->second; ROS_ERROR_STREAM("Unable to transform from frame '" + from_frame + "' to frame '" + target_frame_ + "'"); // return identity return transforms_.find(target_frame_)->second; } const Eigen::Affine3d& planning_models::Transforms::getTransform(const planning_models::KinematicState &kstate, const std::string &from_frame) const { std::map<std::string, Eigen::Affine3d>::const_iterator it = transforms_.find(from_frame); if (it != transforms_.end()) return it->second; if (kstate.getKinematicModel()->getModelFrame() != target_frame_) ROS_ERROR("Target frame is assumed to be '%s' but the model of the kinematic state places the robot in frame '%s'", target_frame_.c_str(), kstate.getKinematicModel()->getModelFrame().c_str()); const Eigen::Affine3d *t = kstate.getFrameTransform(from_frame); if (t) return *t; else // return identity return transforms_.find(target_frame_)->second; } void planning_models::Transforms::transformVector3(const std::string &from_frame, const Eigen::Vector3d &v_in, Eigen::Vector3d &v_out) const { v_out = getTransform(from_frame) * v_in; } void planning_models::Transforms::transformQuaternion(const std::string &from_frame, const Eigen::Quaterniond &q_in, Eigen::Quaterniond &q_out) const { q_out = getTransform(from_frame).rotation() * q_in; } void planning_models::Transforms::transformRotationMatrix(const std::string &from_frame, const Eigen::Matrix3d &m_in, Eigen::Matrix3d &m_out) const { m_out = getTransform(from_frame).rotation() * m_in; } void planning_models::Transforms::transformPose(const std::string &from_frame, const Eigen::Affine3d &t_in, Eigen::Affine3d &t_out) const { t_out = getTransform(from_frame) * t_in; } // specify the kinematic state void planning_models::Transforms::transformVector3(const planning_models::KinematicState &kstate, const std::string &from_frame, const Eigen::Vector3d &v_in, Eigen::Vector3d &v_out) const { v_out = getTransform(kstate, from_frame).rotation() * v_in; } void planning_models::Transforms::transformQuaternion(const planning_models::KinematicState &kstate, const std::string &from_frame, const Eigen::Quaterniond &q_in, Eigen::Quaterniond &q_out) const { q_out = getTransform(kstate, from_frame).rotation() * q_in; } void planning_models::Transforms::transformRotationMatrix(const planning_models::KinematicState &kstate, const std::string &from_frame, const Eigen::Matrix3d &m_in, Eigen::Matrix3d &m_out) const { m_out = getTransform(kstate, from_frame).rotation() * m_in; } void planning_models::Transforms::transformPose(const planning_models::KinematicState &kstate, const std::string &from_frame, const Eigen::Affine3d &t_in, Eigen::Affine3d &t_out) const { t_out = getTransform(kstate, from_frame) * t_in; } void planning_models::Transforms::setTransform(const Eigen::Affine3d &t, const std::string &from_frame) { transforms_[from_frame] = t; } void planning_models::Transforms::setTransform(const geometry_msgs::TransformStamped &transform) { if (transform.child_frame_id.rfind(target_frame_) == transform.child_frame_id.length() - target_frame_.length()) { Eigen::Translation3d o(transform.transform.translation.x, transform.transform.translation.y, transform.transform.translation.z); Eigen::Quaterniond q; quatFromMsg(transform.transform.rotation, q); setTransform(Eigen::Affine3d(o*q.toRotationMatrix()), transform.header.frame_id); } else { ROS_ERROR("Given transform is to frame '%s', but frame '%s' was expected.", transform.child_frame_id.c_str(), target_frame_.c_str()); } } void planning_models::Transforms::setTransforms(const std::vector<geometry_msgs::TransformStamped> &transforms) { for (std::size_t i = 0 ; i < transforms.size() ; ++i) setTransform(transforms[i]); } void planning_models::Transforms::getTransforms(std::vector<geometry_msgs::TransformStamped> &transforms) const { transforms.resize(transforms_.size()); std::size_t i = 0; for (EigenAffine3dMapType::const_iterator it = transforms_.begin() ; it != transforms_.end() ; ++it, ++i) { transforms[i].child_frame_id = target_frame_; transforms[i].header.frame_id = it->first; transforms[i].transform.translation.x = it->second.translation().x(); transforms[i].transform.translation.y = it->second.translation().y(); transforms[i].transform.translation.z = it->second.translation().z(); Eigen::Quaterniond q(it->second.rotation()); transforms[i].transform.rotation.x = q.x(); transforms[i].transform.rotation.y = q.y(); transforms[i].transform.rotation.z = q.z(); transforms[i].transform.rotation.w = q.w(); } } <commit_msg>Printing bad quaternions<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, 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 <planning_models/transforms.h> #include <ros/console.h> bool planning_models::quatFromMsg(const geometry_msgs::Quaternion &qmsg, Eigen::Quaterniond &q) { q = Eigen::Quaterniond(qmsg.w, qmsg.x, qmsg.y, qmsg.z); double error = fabs(q.squaredNorm() - 1.0); if (error > 0.1) { ROS_ERROR("Quaternion is NOWHERE CLOSE TO NORMALIZED [x,y,z,w], [%.2f, %.2f, %.2f, %.2f]. Can't do much, returning identity.", qmsg.x, qmsg.y, qmsg.z, qmsg.w); q = Eigen::Quaterniond(1.0, 0.0, 0.0, 0.0); return false; } else if(error > 1e-3) q.normalize(); return true; } bool planning_models::poseFromMsg(const geometry_msgs::Pose &tmsg, Eigen::Affine3d &t) { Eigen::Quaterniond q; bool r = quatFromMsg(tmsg.orientation, q); t = Eigen::Affine3d(Eigen::Translation3d(tmsg.position.x, tmsg.position.y, tmsg.position.z)*q.toRotationMatrix()); return r; } void planning_models::msgFromPose(const Eigen::Affine3d &t, geometry_msgs::Pose &tmsg) { tmsg.position.x = t.translation().x(); tmsg.position.y = t.translation().y(); tmsg.position.z = t.translation().z(); Eigen::Quaterniond q(t.rotation()); tmsg.orientation.x = q.x(); tmsg.orientation.y = q.y(); tmsg.orientation.z = q.z(); tmsg.orientation.w = q.w(); } void planning_models::msgFromPose(const Eigen::Affine3d &t, geometry_msgs::Transform &tmsg) { tmsg.translation.x = t.translation().x(); tmsg.translation.y = t.translation().y(); tmsg.translation.z = t.translation().z(); Eigen::Quaterniond q(t.rotation()); tmsg.rotation.x = q.x(); tmsg.rotation.y = q.y(); tmsg.rotation.z = q.z(); tmsg.rotation.w = q.w(); } planning_models::Transforms::Transforms(const std::string &target_frame) : target_frame_(target_frame) { Eigen::Affine3d t; t.setIdentity(); transforms_[target_frame_] = t; } planning_models::Transforms::Transforms(const Transforms &other) : target_frame_(other.target_frame_), transforms_(other.transforms_) { } planning_models::Transforms::~Transforms(void) { } const std::string& planning_models::Transforms::getTargetFrame(void) const { return target_frame_; } const planning_models::EigenAffine3dMapType& planning_models::Transforms::getAllTransforms(void) const { return transforms_; } bool planning_models::Transforms::isFixedFrame(const std::string &frame) const { return transforms_.find(frame) != transforms_.end(); } const Eigen::Affine3d& planning_models::Transforms::getTransform(const std::string &from_frame) const { EigenAffine3dMapType::const_iterator it = transforms_.find(from_frame); if (it != transforms_.end()) return it->second; ROS_ERROR_STREAM("Unable to transform from frame '" + from_frame + "' to frame '" + target_frame_ + "'"); // return identity return transforms_.find(target_frame_)->second; } const Eigen::Affine3d& planning_models::Transforms::getTransform(const planning_models::KinematicState &kstate, const std::string &from_frame) const { std::map<std::string, Eigen::Affine3d>::const_iterator it = transforms_.find(from_frame); if (it != transforms_.end()) return it->second; if (kstate.getKinematicModel()->getModelFrame() != target_frame_) ROS_ERROR("Target frame is assumed to be '%s' but the model of the kinematic state places the robot in frame '%s'", target_frame_.c_str(), kstate.getKinematicModel()->getModelFrame().c_str()); const Eigen::Affine3d *t = kstate.getFrameTransform(from_frame); if (t) return *t; else // return identity return transforms_.find(target_frame_)->second; } void planning_models::Transforms::transformVector3(const std::string &from_frame, const Eigen::Vector3d &v_in, Eigen::Vector3d &v_out) const { v_out = getTransform(from_frame) * v_in; } void planning_models::Transforms::transformQuaternion(const std::string &from_frame, const Eigen::Quaterniond &q_in, Eigen::Quaterniond &q_out) const { q_out = getTransform(from_frame).rotation() * q_in; } void planning_models::Transforms::transformRotationMatrix(const std::string &from_frame, const Eigen::Matrix3d &m_in, Eigen::Matrix3d &m_out) const { m_out = getTransform(from_frame).rotation() * m_in; } void planning_models::Transforms::transformPose(const std::string &from_frame, const Eigen::Affine3d &t_in, Eigen::Affine3d &t_out) const { t_out = getTransform(from_frame) * t_in; } // specify the kinematic state void planning_models::Transforms::transformVector3(const planning_models::KinematicState &kstate, const std::string &from_frame, const Eigen::Vector3d &v_in, Eigen::Vector3d &v_out) const { v_out = getTransform(kstate, from_frame).rotation() * v_in; } void planning_models::Transforms::transformQuaternion(const planning_models::KinematicState &kstate, const std::string &from_frame, const Eigen::Quaterniond &q_in, Eigen::Quaterniond &q_out) const { q_out = getTransform(kstate, from_frame).rotation() * q_in; } void planning_models::Transforms::transformRotationMatrix(const planning_models::KinematicState &kstate, const std::string &from_frame, const Eigen::Matrix3d &m_in, Eigen::Matrix3d &m_out) const { m_out = getTransform(kstate, from_frame).rotation() * m_in; } void planning_models::Transforms::transformPose(const planning_models::KinematicState &kstate, const std::string &from_frame, const Eigen::Affine3d &t_in, Eigen::Affine3d &t_out) const { t_out = getTransform(kstate, from_frame) * t_in; } void planning_models::Transforms::setTransform(const Eigen::Affine3d &t, const std::string &from_frame) { transforms_[from_frame] = t; } void planning_models::Transforms::setTransform(const geometry_msgs::TransformStamped &transform) { if (transform.child_frame_id.rfind(target_frame_) == transform.child_frame_id.length() - target_frame_.length()) { Eigen::Translation3d o(transform.transform.translation.x, transform.transform.translation.y, transform.transform.translation.z); Eigen::Quaterniond q; quatFromMsg(transform.transform.rotation, q); setTransform(Eigen::Affine3d(o*q.toRotationMatrix()), transform.header.frame_id); } else { ROS_ERROR("Given transform is to frame '%s', but frame '%s' was expected.", transform.child_frame_id.c_str(), target_frame_.c_str()); } } void planning_models::Transforms::setTransforms(const std::vector<geometry_msgs::TransformStamped> &transforms) { for (std::size_t i = 0 ; i < transforms.size() ; ++i) setTransform(transforms[i]); } void planning_models::Transforms::getTransforms(std::vector<geometry_msgs::TransformStamped> &transforms) const { transforms.resize(transforms_.size()); std::size_t i = 0; for (EigenAffine3dMapType::const_iterator it = transforms_.begin() ; it != transforms_.end() ; ++it, ++i) { transforms[i].child_frame_id = target_frame_; transforms[i].header.frame_id = it->first; transforms[i].transform.translation.x = it->second.translation().x(); transforms[i].transform.translation.y = it->second.translation().y(); transforms[i].transform.translation.z = it->second.translation().z(); Eigen::Quaterniond q(it->second.rotation()); transforms[i].transform.rotation.x = q.x(); transforms[i].transform.rotation.y = q.y(); transforms[i].transform.rotation.z = q.z(); transforms[i].transform.rotation.w = q.w(); } } <|endoftext|>
<commit_before>/***************************************************************************** * podcast_configuration.cpp: Podcast configuration dialog **************************************************************************** * Copyright (C) 2007 the VideoLAN team * $Id$ * * Authors: Antoine Cellerier <dionoea at videolan dot org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "podcast_configuration.hpp" PodcastConfigurationDialog::PodcastConfigurationDialog( intf_thread_t *_p_intf ) :p_intf( _p_intf ) { ui.setupUi( this ); CONNECT( ui.podcastAdd, clicked(), this, add() ); CONNECT( ui.podcastDelete, clicked(), this, remove() ); char *psz_urls = config_GetPsz( p_intf, "podcast-urls" ); if( psz_urls ) { char *psz_url = psz_urls; while( 1 ) { char *psz_tok = strchr( psz_url, '|' ); if( psz_tok ) *psz_tok = '\0'; ui.podcastList->addItem( psz_url ); if( psz_tok ) psz_url = psz_tok+1; else break; } free( psz_urls ); } } void PodcastConfigurationDialog::accept() { QString urls = ""; for( int i = 0; i < ui.podcastList->count(); i++ ) { urls += ui.podcastList->item(i)->text(); if( i != ui.podcastList->count()-1 ) urls += "|"; } const char *psz_urls = qtu( urls ); config_PutPsz( p_intf, "podcast-urls", psz_urls ); if( playlist_IsServicesDiscoveryLoaded( THEPL, "podcast" ) ) { msg_Info( p_intf, "You will need to reload the podcast module for changes to be used (FIXME)" ); } QDialog::accept(); } void PodcastConfigurationDialog::add() { if( ui.podcastURL->text() != QString( "" ) ) { ui.podcastList->addItem( ui.podcastURL->text() ); ui.podcastURL->clear(); } } void PodcastConfigurationDialog::remove() { delete ui.podcastList->currentItem(); } <commit_msg>If the podcast service discovery is already runing, update its podcast-urls variable.<commit_after>/***************************************************************************** * podcast_configuration.cpp: Podcast configuration dialog **************************************************************************** * Copyright (C) 2007 the VideoLAN team * $Id$ * * Authors: Antoine Cellerier <dionoea at videolan dot org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #include "podcast_configuration.hpp" PodcastConfigurationDialog::PodcastConfigurationDialog( intf_thread_t *_p_intf ) :p_intf( _p_intf ) { ui.setupUi( this ); CONNECT( ui.podcastAdd, clicked(), this, add() ); CONNECT( ui.podcastDelete, clicked(), this, remove() ); char *psz_urls = config_GetPsz( p_intf, "podcast-urls" ); if( psz_urls ) { char *psz_url = psz_urls; while( 1 ) { char *psz_tok = strchr( psz_url, '|' ); if( psz_tok ) *psz_tok = '\0'; ui.podcastList->addItem( psz_url ); if( psz_tok ) psz_url = psz_tok+1; else break; } free( psz_urls ); } } void PodcastConfigurationDialog::accept() { QString urls = ""; for( int i = 0; i < ui.podcastList->count(); i++ ) { urls += ui.podcastList->item(i)->text(); if( i != ui.podcastList->count()-1 ) urls += "|"; } const char *psz_urls = qtu( urls ); config_PutPsz( p_intf, "podcast-urls", psz_urls ); vlc_object_t *p_obj = (vlc_object_t*) vlc_object_find_name( p_intf->p_libvlc, "podcast", FIND_CHILD ); if( p_obj ) { var_SetString( p_obj, "podcast-urls", psz_urls ); vlc_object_release( p_obj ); } if( playlist_IsServicesDiscoveryLoaded( THEPL, "podcast" ) ) { msg_Dbg( p_intf, "You will need to reload the podcast module to take into account deleted podcast urls" ); } QDialog::accept(); } void PodcastConfigurationDialog::add() { if( ui.podcastURL->text() != QString( "" ) ) { ui.podcastList->addItem( ui.podcastURL->text() ); ui.podcastURL->clear(); } } void PodcastConfigurationDialog::remove() { delete ui.podcastList->currentItem(); } <|endoftext|>
<commit_before>#include "StartingScreen.hpp" #include "SDL/SDL_ttf.h" void ShowStartingScreen(SDL_Surface *surf, SDL_Surface *screen, _bools &bools) { bool daflag = true; TTF_Font *ttf_msg(TTF_OpenFont("resources/fonts/Alias.ttf", 32)); SDL_Rect pmessage; SDL_Surface *msg; SDL_Color col; col.r = 0xff; col.g = 0xff; col.b = 0xff; SDL_Event event; pmessage.x = 16; pmessage.y = 550; pmessage.w = 100; pmessage.h = 30; msg = TTF_RenderUTF8_Blended( ttf_msg, "Press any key to Continue", col); while (!bools.start) { if(!SDL_PollEvent(&event)) ; switch(event.type){ case SDL_KEYUP: switch(event.key.keysym.sym) { case SDLK_ESCAPE : bools.exit = true; return; default : bools.start = true; } break; case SDL_QUIT: bools.exit = true; break; } // capping SDL_Delay(500); if(daflag){ SDL_BlitSurface(msg, NULL, screen, &pmessage); SDL_Flip(screen); daflag = false; } else{ SDL_FillRect(screen, &pmessage, 0); SDL_Flip(screen); daflag = true; } } } <commit_msg>fixed starting screen bug<commit_after>#include "StartingScreen.hpp" #include "SDL/SDL_ttf.h" void ShowStartingScreen(SDL_Surface *surf, SDL_Surface *screen, _bools &bools) { bool daflag = true; TTF_Font *ttf_msg(TTF_OpenFont("resources/fonts/Alias.ttf", 32)); SDL_Rect pmessage; SDL_Surface *msg; SDL_Color col; col.r = 0xff; col.g = 0xff; col.b = 0xff; SDL_Event event; pmessage.x = 16; pmessage.y = 550; pmessage.w = 100; pmessage.h = 30; msg = TTF_RenderUTF8_Blended( ttf_msg, "Press any key to Continue", col); while (!bools.start) { if(!SDL_PollEvent(&event)) ; else { switch(event.type) { case SDL_KEYUP: switch(event.key.keysym.sym) { case SDLK_ESCAPE : bools.exit = true; return; default : bools.start = true; } break; case SDL_QUIT: bools.exit = true; break; } } // capping SDL_Delay(500); if(daflag){ SDL_BlitSurface(msg, NULL, screen, &pmessage); SDL_Flip(screen); daflag = false; } else{ SDL_FillRect(screen, &pmessage, 0); SDL_Flip(screen); daflag = true; } } } <|endoftext|>
<commit_before>// Copyright 2016 AUV-IITK #include <ros/ros.h> #include <std_msgs/Float32.h> #include <std_msgs/Float64.h> #include <std_msgs/Int32.h> #include <actionlib/server/simple_action_server.h> #include <motion_commons/UpwardAction.h> #include <dynamic_reconfigure/server.h> #include <motion_upward/pidConfig.h> #include <string> using std::string; typedef actionlib::SimpleActionServer<motion_commons::UpwardAction> Server; // defining the Client type float presentDepth = 0; float previousDepth = 0; float finalDepth, error, output; bool initData = false; std_msgs::Int32 pwm; // pwm to be send to arduino // new inner class, to encapsulate the interaction with actionclient class innerActionClass { private: ros::NodeHandle nh_; Server upwardServer_; std::string action_name_; motion_commons::UpwardFeedback feedback_; motion_commons::UpwardResult result_; ros::Publisher PWM; float p, i, d; public: // Constructor, called when new instance of class declared explicit innerActionClass(std::string name) : // Defining the server, third argument is optional upwardServer_(nh_, name, boost::bind(&innerActionClass::analysisCB, this, _1), false) , action_name_(name) { // Add preempt callback upwardServer_.registerPreemptCallback(boost::bind(&innerActionClass::preemptCB, this)); // Declaring publisher for PWM PWM = nh_.advertise<std_msgs::Int32>("/pwm/upward", 1000); // Starting new Action Server upwardServer_.start(); } // default contructor ~innerActionClass(void) { } // callback for goal cancelled; Stop the bot void preemptCB(void) { pwm.data = 0; PWM.publish(pwm); ROS_INFO("pwm send to arduino %d", pwm.data); // this command cancels the previous goal upwardServer_.setPreempted(); } // called when new goal recieved; Start motion and finish it, if not interrupted void analysisCB(const motion_commons::UpwardGoalConstPtr goal) { ROS_INFO("Inside analysisCB"); int count = 0; int loopRate = 10; ros::Rate loop_rate(loopRate); // waiting till we recieve the first value from Camera/pressure sensor else it's useless do any calculations while (!initData) { ROS_INFO("Waiting to get first input at topic zDistance"); loop_rate.sleep(); } finalDepth = goal->Goal; float derivative = 0, integral = 0, dt = 1.0 / loopRate; bool reached = false; pwm.data = 0; if (!upwardServer_.isActive()) return; while (!upwardServer_.isPreemptRequested() && ros::ok() && count < goal->loop) { error = finalDepth - presentDepth; integral += (error * dt); derivative = (presentDepth - previousDepth) / dt; output = (p * error) + (i * integral) + (d * derivative); upwardOutputPWMMapping(output); if (pwm.data <= 2 && pwm.data >= -2) { reached = true; pwm.data = 0; PWM.publish(pwm); ROS_INFO("thrusters stopped"); count++; } else { reached = false; count = 0; } if (upwardServer_.isPreemptRequested() || !ros::ok()) { ROS_INFO("%s: Preempted", action_name_.c_str()); // set the action state to preempted upwardServer_.setPreempted(); reached = false; break; } feedback_.DepthRemaining = error; upwardServer_.publishFeedback(feedback_); PWM.publish(pwm); ROS_INFO("pwm send to arduino upward %d", pwm.data); ros::spinOnce(); loop_rate.sleep(); } if (reached) { result_.Result = reached; ROS_INFO("%s: Succeeded", action_name_.c_str()); // set the action state to succeeded upwardServer_.setSucceeded(result_); } } void upwardOutputPWMMapping(float output) { const float maxOutput = 1000, minOutput = -maxOutput; const float scale = 255 / maxOutput; if (output > maxOutput) output = maxOutput; if (output < minOutput) output = minOutput; float temp = output * scale; pwm.data = static_cast<int>(temp); } void setPID(float new_p, float new_i, float new_d) { p = new_p; i = new_i; d = new_d; } }; innerActionClass *object; // dynamic reconfig void callback(motion_upward::pidConfig &config, double level) { ROS_INFO("UpwardServer: Reconfigure Request: p= %f i= %f d=%f", config.p, config.i, config.d); object->setPID(config.p, config.i, config.d); } void distanceCb(std_msgs::Float64 msg) { // this is used to set the final depth after getting the value of first intial position if (initData == false) { presentDepth = msg.data; previousDepth = presentDepth; initData = true; } else { previousDepth = presentDepth; presentDepth = msg.data; } } int main(int argc, char **argv) { ros::init(argc, argv, "upward"); ros::NodeHandle n; double p_param, i_param, d_param; n.getParam("upward/p_param", p_param); n.getParam("upward/i_param", i_param); n.getParam("upward/d_param", d_param); ros::Subscriber zDistance = n.subscribe<std_msgs::Float64>("/varun/motion/z_distance", 1000, &distanceCb); ROS_INFO("Waiting for Goal"); object = new innerActionClass(ros::this_node::getName()); // register dynamic reconfig server. dynamic_reconfigure::Server<motion_upward::pidConfig> server; dynamic_reconfigure::Server<motion_upward::pidConfig>::CallbackType f; f = boost::bind(&callback, _1, _2); server.setCallback(f); // set launch file pid motion_upward::pidConfig config; config.p = p_param; config.i = i_param; config.d = d_param; callback(config, 0); ros::spin(); return 0; } <commit_msg>added band parameter in turn cpp<commit_after>// Copyright 2016 AUV-IITK #include <ros/ros.h> #include <std_msgs/Float32.h> #include <std_msgs/Float64.h> #include <std_msgs/Int32.h> #include <actionlib/server/simple_action_server.h> #include <motion_commons/UpwardAction.h> #include <dynamic_reconfigure/server.h> #include <motion_upward/pidConfig.h> #include <string> using std::string; typedef actionlib::SimpleActionServer<motion_commons::UpwardAction> Server; // defining the Client type float presentDepth = 0; float previousDepth = 0; float finalDepth, error, output; bool initData = false; std_msgs::Int32 pwm; // pwm to be send to arduino // new inner class, to encapsulate the interaction with actionclient class innerActionClass { private: ros::NodeHandle nh_; Server upwardServer_; std::string action_name_; motion_commons::UpwardFeedback feedback_; motion_commons::UpwardResult result_; ros::Publisher PWM; float p, i, d, band; public: // Constructor, called when new instance of class declared explicit innerActionClass(std::string name) : // Defining the server, third argument is optional upwardServer_(nh_, name, boost::bind(&innerActionClass::analysisCB, this, _1), false) , action_name_(name) { // Add preempt callback upwardServer_.registerPreemptCallback(boost::bind(&innerActionClass::preemptCB, this)); // Declaring publisher for PWM PWM = nh_.advertise<std_msgs::Int32>("/pwm/upward", 1000); // Starting new Action Server upwardServer_.start(); } // default contructor ~innerActionClass(void) { } // callback for goal cancelled; Stop the bot void preemptCB(void) { pwm.data = 0; PWM.publish(pwm); ROS_INFO("pwm send to arduino %d", pwm.data); // this command cancels the previous goal upwardServer_.setPreempted(); } // called when new goal recieved; Start motion and finish it, if not interrupted void analysisCB(const motion_commons::UpwardGoalConstPtr goal) { ROS_INFO("Inside analysisCB"); int count = 0; int loopRate = 10; ros::Rate loop_rate(loopRate); // waiting till we recieve the first value from Camera/pressure sensor else it's useless do any calculations while (!initData) { ROS_INFO("Waiting to get first input at topic zDistance"); loop_rate.sleep(); } finalDepth = goal->Goal; float derivative = 0, integral = 0, dt = 1.0 / loopRate; bool reached = false; pwm.data = 0; if (!upwardServer_.isActive()) return; while (!upwardServer_.isPreemptRequested() && ros::ok() && count < goal->loop) { error = finalDepth - presentDepth; integral += (error * dt); derivative = (presentDepth - previousDepth) / dt; output = (p * error) + (i * integral) + (d * derivative); upwardOutputPWMMapping(output); if (pwm.data <= band && pwm.data >= -band) { reached = true; pwm.data = 0; PWM.publish(pwm); ROS_INFO("thrusters stopped"); count++; } else { reached = false; count = 0; } if (upwardServer_.isPreemptRequested() || !ros::ok()) { ROS_INFO("%s: Preempted", action_name_.c_str()); // set the action state to preempted upwardServer_.setPreempted(); reached = false; break; } feedback_.DepthRemaining = error; upwardServer_.publishFeedback(feedback_); PWM.publish(pwm); ROS_INFO("pwm send to arduino upward %d", pwm.data); ros::spinOnce(); loop_rate.sleep(); } if (reached) { result_.Result = reached; ROS_INFO("%s: Succeeded", action_name_.c_str()); // set the action state to succeeded upwardServer_.setSucceeded(result_); } } void upwardOutputPWMMapping(float output) { const float maxOutput = 1000, minOutput = -maxOutput; const float scale = 255 / maxOutput; if (output > maxOutput) output = maxOutput; if (output < minOutput) output = minOutput; float temp = output * scale; pwm.data = static_cast<int>(temp); } void setPID(float new_p, float new_i, float new_d, float new_band) { p = new_p; i = new_i; d = new_d; band = new_band; } }; innerActionClass *object; // dynamic reconfig void callback(motion_upward::pidConfig &config, double level) { ROS_INFO("UpwardServer: Reconfigure Request: p= %f i= %f d=%f error band=%f", config.p, config.i, config.d, config.band); object->setPID(config.p, config.i, config.d, config.band); } void distanceCb(std_msgs::Float64 msg) { // this is used to set the final depth after getting the value of first intial position if (initData == false) { presentDepth = msg.data; previousDepth = presentDepth; initData = true; } else { previousDepth = presentDepth; presentDepth = msg.data; } } int main(int argc, char **argv) { ros::init(argc, argv, "upward"); ros::NodeHandle n; double p_param, i_param, d_param, band_param; n.getParam("upward/p_param", p_param); n.getParam("upward/i_param", i_param); n.getParam("upward/d_param", d_param); n.getParam("upward/band_param", band_param); ros::Subscriber zDistance = n.subscribe<std_msgs::Float64>("/varun/motion/z_distance", 1000, &distanceCb); ROS_INFO("Waiting for Goal"); object = new innerActionClass(ros::this_node::getName()); // register dynamic reconfig server. dynamic_reconfigure::Server<motion_upward::pidConfig> server; dynamic_reconfigure::Server<motion_upward::pidConfig>::CallbackType f; f = boost::bind(&callback, _1, _2); server.setCallback(f); // set launch file pid motion_upward::pidConfig config; config.p = p_param; config.i = i_param; config.d = d_param; config.band = band_param; callback(config, 0); ros::spin(); return 0; } <|endoftext|>
<commit_before>#pragma once /* * Copyright (c) 2012, 2013 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #ifndef _QI_OS_HPP_ #define _QI_OS_HPP_ # include <cstdio> # include <string> # include <map> # include <vector> # include <qi/api.hpp> # include <qi/types.hpp> struct stat; namespace qi { namespace os { QI_API FILE* fopen(const char *filename, const char *mode); QI_API int stat(const char *filename, struct stat *pstat); QI_API int checkdbg(); QI_API std::string home(); QI_API std::string mktmpdir(const char *prefix = ""); QI_API std::string tmp(); QI_API std::string gethostname(); QI_API int isatty(int fd = 1); QI_API bool fnmatch(const std::string &pattern, const std::string &string); // lib C QI_API char* strdup(const char *src); QI_API int snprintf(char *str, size_t size, const char *format, ...); // env QI_API std::string getenv(const char *var); QI_API int setenv(const char *var, const char *value); QI_API std::string timezone(); // time QI_API void sleep(unsigned int seconds); QI_API void msleep(unsigned int milliseconds); struct QI_API timeval { qi::int64_t tv_sec; qi::int64_t tv_usec; }; QI_API int gettimeofday(qi::os::timeval *tp); QI_API qi::int64_t ustime(); QI_API qi::os::timeval operator+(const qi::os::timeval &lhs, const qi::os::timeval &rhs); QI_API qi::os::timeval operator+(const qi::os::timeval &lhs, long us); QI_API qi::os::timeval operator-(const qi::os::timeval &lhs, const qi::os::timeval &rhs); QI_API qi::os::timeval operator-(const qi::os::timeval &lhs, long us); // shared library QI_API void *dlopen(const char *filename, int flag = -1); QI_API int dlclose(void *handle); QI_API void *dlsym(void *handle, const char *symbol); QI_API const char *dlerror(void); // process management QI_API int spawnvp(char *const argv[]); QI_API int spawnlp(const char* argv, ...); QI_API int system(const char *command); QI_API int getpid(); QI_API int gettid(); QI_API int waitpid(int pid, int* status); QI_API int kill(int pid, int sig); QI_API unsigned short findAvailablePort(unsigned short port); QI_API std::map<std::string, std::vector<std::string> > hostIPAddrs(bool ipv6Addr = false); QI_API void setCurrentThreadName(const std::string &name); QI_API bool setCurrentThreadCPUAffinity(const std::vector<int> &cpus); QI_API long numberOfCPUs(); QI_API std::string getMachineId(); QI_API std::string generateUuid(); //since 1.12.1 QI_API_DEPRECATED QI_API std::string tmpdir(const char *prefix = ""); } } #endif // _QI_OS_HPP_ <commit_msg>qi::os::fnmatch: document<commit_after>#pragma once /* * Copyright (c) 2012, 2013 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #ifndef _QI_OS_HPP_ #define _QI_OS_HPP_ # include <cstdio> # include <string> # include <map> # include <vector> # include <qi/api.hpp> # include <qi/types.hpp> struct stat; namespace qi { namespace os { QI_API FILE* fopen(const char *filename, const char *mode); QI_API int stat(const char *filename, struct stat *pstat); QI_API int checkdbg(); QI_API std::string home(); QI_API std::string mktmpdir(const char *prefix = ""); QI_API std::string tmp(); QI_API std::string gethostname(); QI_API int isatty(int fd = 1); /** * handles * and ? wilcards */ QI_API bool fnmatch(const std::string &pattern, const std::string &string); // lib C QI_API char* strdup(const char *src); QI_API int snprintf(char *str, size_t size, const char *format, ...); // env QI_API std::string getenv(const char *var); QI_API int setenv(const char *var, const char *value); QI_API std::string timezone(); // time QI_API void sleep(unsigned int seconds); QI_API void msleep(unsigned int milliseconds); struct QI_API timeval { qi::int64_t tv_sec; qi::int64_t tv_usec; }; QI_API int gettimeofday(qi::os::timeval *tp); QI_API qi::int64_t ustime(); QI_API qi::os::timeval operator+(const qi::os::timeval &lhs, const qi::os::timeval &rhs); QI_API qi::os::timeval operator+(const qi::os::timeval &lhs, long us); QI_API qi::os::timeval operator-(const qi::os::timeval &lhs, const qi::os::timeval &rhs); QI_API qi::os::timeval operator-(const qi::os::timeval &lhs, long us); // shared library QI_API void *dlopen(const char *filename, int flag = -1); QI_API int dlclose(void *handle); QI_API void *dlsym(void *handle, const char *symbol); QI_API const char *dlerror(void); // process management QI_API int spawnvp(char *const argv[]); QI_API int spawnlp(const char* argv, ...); QI_API int system(const char *command); QI_API int getpid(); QI_API int gettid(); QI_API int waitpid(int pid, int* status); QI_API int kill(int pid, int sig); QI_API unsigned short findAvailablePort(unsigned short port); QI_API std::map<std::string, std::vector<std::string> > hostIPAddrs(bool ipv6Addr = false); QI_API void setCurrentThreadName(const std::string &name); QI_API bool setCurrentThreadCPUAffinity(const std::vector<int> &cpus); QI_API long numberOfCPUs(); QI_API std::string getMachineId(); QI_API std::string generateUuid(); //since 1.12.1 QI_API_DEPRECATED QI_API std::string tmpdir(const char *prefix = ""); } } #endif // _QI_OS_HPP_ <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Lewis Baker // Licenced under MIT license. See LICENSE.txt for details. /////////////////////////////////////////////////////////////////////////////// #include <cppcoro/detail/lightweight_manual_reset_event.hpp> #include <system_error> #if CPPCORO_OS_WINNT # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # include <Windows.h> # if CPPCORO_OS_WINNT >= 0x0602 cppcoro::detail::lightweight_manual_reset_event::lightweight_manual_reset_event(bool initiallySet) : m_value(initiallySet ? 1 : 0) {} cppcoro::detail::lightweight_manual_reset_event::~lightweight_manual_reset_event() { } void cppcoro::detail::lightweight_manual_reset_event::set() noexcept { m_value.store(1, std::memory_order_release); ::WakeByAddressAll(&m_value); } void cppcoro::detail::lightweight_manual_reset_event::reset() noexcept { m_value.store(0, std::memory_order_relaxed); } void cppcoro::detail::lightweight_manual_reset_event::wait() noexcept { // Wait in a loop as WaitOnAddress() can have spurious wake-ups. int value = m_value.load(std::memory_order_acquire); BOOL ok = TRUE; while (value == 0) { if (!ok) { // Previous call to WaitOnAddress() failed for some reason. // Put thread to sleep to avoid sitting in a busy loop if it keeps failing. ::Sleep(1); } ok = ::WaitOnAddress(&m_value, &value, sizeof(m_value), INFINITE); value = m_value.load(std::memory_order_acquire); } } # else cppcoro::detail::lightweight_manual_reset_event::lightweight_manual_reset_event(bool initiallySet) : m_eventHandle(::CreateEventW(nullptr, TRUE, initiallySet, nullptr)) { if (m_eventHandle == NULL) { const DWORD errorCode = ::GetLastError(); throw std::system_error { static_cast<int>(errorCode), std::system_category() }; } } cppcoro::detail::lightweight_manual_reset_event::~lightweight_manual_reset_event() { // Ignore failure to close the object. // We can't do much here as we want destructor to be noexcept. (void)::CloseHandle(m_eventHandle); } void cppcoro::detail::lightweight_manual_reset_event::set() noexcept { if (!::SetEvent(m_eventHandle)) { std::abort(); } } void cppcoro::detail::lightweight_manual_reset_event::reset() noexcept { if (!::ResetEvent(m_eventHandle)) { std::abort(); } } void cppcoro::detail::lightweight_manual_reset_event::wait() noexcept { constexpr BOOL alertable = FALSE; DWORD waitResult = ::WaitForSingleObjectEx(m_eventHandle, INFINITE, alertable); if (waitResult == WAIT_FAILED) { std::abort(); } } # endif #elif CPPCORO_OS_LINUX #include <unistd.h> #include <sys/syscall.h> #include <sys/time.h> #include <linux/futex.h> #include <cerrno> #include <climits> #include <cassert> namespace { namespace local { // No futex() function provided by libc. // Wrap the syscall ourselves here. int futex( int* UserAddress, int FutexOperation, int Value, const struct timespec* timeout, int* UserAddress2, int Value3) { return syscall( SYS_futex, UserAddress, FutexOperation, Value, timeout, UserAddress2, Value3); } } } cppcoro::detail::lightweight_manual_reset_event::lightweight_manual_reset_event(bool initiallySet) : m_value(initiallySet ? 1 : 0) {} cppcoro::detail::lightweight_manual_reset_event::~lightweight_manual_reset_event() { } void cppcoro::detail::lightweight_manual_reset_event::set() noexcept { m_value.store(1, std::memory_order_release); constexpr int numberOfWaitersToWakeUp = INT_MAX; [[maybe_unused]] int numberOfWaitersWokenUp = local::futex( reinterpret_cast<int*>(&m_value), FUTEX_WAKE_PRIVATE, numberOfWaitersToWakeUp, nullptr, nullptr, 0); // There are no errors expected here unless this class (or the caller) // has done something wrong. assert(numberOfWaitersWokenUp != -1); } void cppcoro::detail::lightweight_manual_reset_event::reset() noexcept { m_value.store(0, std::memory_order_relaxed); } void cppcoro::detail::lightweight_manual_reset_event::wait() noexcept { // Wait in a loop as futex() can have spurious wake-ups. int oldValue = m_value.load(std::memory_order_acquire); while (oldValue == 0) { int result = local::futex( reinterpret_cast<int*>(&m_value), FUTEX_WAIT_PRIVATE, oldValue, nullptr, nullptr, 0); if (result == -1) { if (errno == EAGAIN) { // The state was changed from zero before we could wait. // Must have been changed to 1. return; } // Other errors we'll treat as transient and just read the // value and go around the loop again. } oldValue = m_value.load(std::memory_order_acquire); } } #else cppcoro::detail::lightweight_manual_reset_event::lightweight_manual_reset_event(bool initiallySet) : m_isSet(initiallySet) { } cppcoro::detail::lightweight_manual_reset_event::~lightweight_manual_reset_event() { } void cppcoro::detail::lightweight_manual_reset_event::set() noexcept { { std::lock_guard<std::mutex> lock(m_mutex); m_isSet = true; } m_cv.notify_all(); } void cppcoro::detail::lightweight_manual_reset_event::reset() noexcept { std::lock_guard<std::mutex> lock(m_mutex); m_isSet = false; } void cppcoro::detail::lightweight_manual_reset_event::wait() noexcept { std::unique_lock<std::mutex> lock(m_mutex); m_cv.wait(lock, [this] { return m_isSet; }); } #endif <commit_msg>Fix potential race condition in lightweight_manual_reset_event.<commit_after>/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Lewis Baker // Licenced under MIT license. See LICENSE.txt for details. /////////////////////////////////////////////////////////////////////////////// #include <cppcoro/detail/lightweight_manual_reset_event.hpp> #include <system_error> #if CPPCORO_OS_WINNT # ifndef WIN32_LEAN_AND_MEAN # define WIN32_LEAN_AND_MEAN # endif # include <Windows.h> # if CPPCORO_OS_WINNT >= 0x0602 cppcoro::detail::lightweight_manual_reset_event::lightweight_manual_reset_event(bool initiallySet) : m_value(initiallySet ? 1 : 0) {} cppcoro::detail::lightweight_manual_reset_event::~lightweight_manual_reset_event() { } void cppcoro::detail::lightweight_manual_reset_event::set() noexcept { m_value.store(1, std::memory_order_release); ::WakeByAddressAll(&m_value); } void cppcoro::detail::lightweight_manual_reset_event::reset() noexcept { m_value.store(0, std::memory_order_relaxed); } void cppcoro::detail::lightweight_manual_reset_event::wait() noexcept { // Wait in a loop as WaitOnAddress() can have spurious wake-ups. int value = m_value.load(std::memory_order_acquire); BOOL ok = TRUE; while (value == 0) { if (!ok) { // Previous call to WaitOnAddress() failed for some reason. // Put thread to sleep to avoid sitting in a busy loop if it keeps failing. ::Sleep(1); } ok = ::WaitOnAddress(&m_value, &value, sizeof(m_value), INFINITE); value = m_value.load(std::memory_order_acquire); } } # else cppcoro::detail::lightweight_manual_reset_event::lightweight_manual_reset_event(bool initiallySet) : m_eventHandle(::CreateEventW(nullptr, TRUE, initiallySet, nullptr)) { if (m_eventHandle == NULL) { const DWORD errorCode = ::GetLastError(); throw std::system_error { static_cast<int>(errorCode), std::system_category() }; } } cppcoro::detail::lightweight_manual_reset_event::~lightweight_manual_reset_event() { // Ignore failure to close the object. // We can't do much here as we want destructor to be noexcept. (void)::CloseHandle(m_eventHandle); } void cppcoro::detail::lightweight_manual_reset_event::set() noexcept { if (!::SetEvent(m_eventHandle)) { std::abort(); } } void cppcoro::detail::lightweight_manual_reset_event::reset() noexcept { if (!::ResetEvent(m_eventHandle)) { std::abort(); } } void cppcoro::detail::lightweight_manual_reset_event::wait() noexcept { constexpr BOOL alertable = FALSE; DWORD waitResult = ::WaitForSingleObjectEx(m_eventHandle, INFINITE, alertable); if (waitResult == WAIT_FAILED) { std::abort(); } } # endif #elif CPPCORO_OS_LINUX #include <unistd.h> #include <sys/syscall.h> #include <sys/time.h> #include <linux/futex.h> #include <cerrno> #include <climits> #include <cassert> namespace { namespace local { // No futex() function provided by libc. // Wrap the syscall ourselves here. int futex( int* UserAddress, int FutexOperation, int Value, const struct timespec* timeout, int* UserAddress2, int Value3) { return syscall( SYS_futex, UserAddress, FutexOperation, Value, timeout, UserAddress2, Value3); } } } cppcoro::detail::lightweight_manual_reset_event::lightweight_manual_reset_event(bool initiallySet) : m_value(initiallySet ? 1 : 0) {} cppcoro::detail::lightweight_manual_reset_event::~lightweight_manual_reset_event() { } void cppcoro::detail::lightweight_manual_reset_event::set() noexcept { m_value.store(1, std::memory_order_release); constexpr int numberOfWaitersToWakeUp = INT_MAX; [[maybe_unused]] int numberOfWaitersWokenUp = local::futex( reinterpret_cast<int*>(&m_value), FUTEX_WAKE_PRIVATE, numberOfWaitersToWakeUp, nullptr, nullptr, 0); // There are no errors expected here unless this class (or the caller) // has done something wrong. assert(numberOfWaitersWokenUp != -1); } void cppcoro::detail::lightweight_manual_reset_event::reset() noexcept { m_value.store(0, std::memory_order_relaxed); } void cppcoro::detail::lightweight_manual_reset_event::wait() noexcept { // Wait in a loop as futex() can have spurious wake-ups. int oldValue = m_value.load(std::memory_order_acquire); while (oldValue == 0) { int result = local::futex( reinterpret_cast<int*>(&m_value), FUTEX_WAIT_PRIVATE, oldValue, nullptr, nullptr, 0); if (result == -1) { if (errno == EAGAIN) { // The state was changed from zero before we could wait. // Must have been changed to 1. return; } // Other errors we'll treat as transient and just read the // value and go around the loop again. } oldValue = m_value.load(std::memory_order_acquire); } } #else cppcoro::detail::lightweight_manual_reset_event::lightweight_manual_reset_event(bool initiallySet) : m_isSet(initiallySet) { } cppcoro::detail::lightweight_manual_reset_event::~lightweight_manual_reset_event() { } void cppcoro::detail::lightweight_manual_reset_event::set() noexcept { std::lock_guard<std::mutex> lock(m_mutex); m_isSet = true; m_cv.notify_all(); } void cppcoro::detail::lightweight_manual_reset_event::reset() noexcept { std::lock_guard<std::mutex> lock(m_mutex); m_isSet = false; } void cppcoro::detail::lightweight_manual_reset_event::wait() noexcept { std::unique_lock<std::mutex> lock(m_mutex); m_cv.wait(lock, [this] { return m_isSet; }); } #endif <|endoftext|>
<commit_before>/* The MIT License Copyright (c) 2008 Dennis Mllegaard Pedersen <dennis@moellegaard.dk> 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 <wx/fileconf.h> #include "config.h" Config appConfig; Config::Config() { } Config::~Config() { } // FIXME - i hate to use this // This is a macro that will allocate and deallocate the wxConfig, since // our app crashes if we let it live too long (for some reason). This // is a temporary hack, which should be fixed ASAP. #define CFG_OP(cfg,op) \ wxFileConfig* cfg = new wxFileConfig(_T("bzlauncher")); \ { op } while(0); \ delete cfg; \ cfg = NULL; wxString Config::getBZFlagCommand(const wxString& proto) const { // first try bzflag/proto (eg bzflag/bzfs0026) // then try bzflag/default wxString key = wxString::Format(_T("bzflag/%s"), proto.Lower().c_str()); wxString cmd; CFG_OP(cfg, if(! cfg->Read(key, &cmd)) { if(! cfg->Read(_T("bzflag/default"), &cmd)) { return _T(""); } } ); return cmd; } void Config::versionCheck() { int version = 0; CFG_OP(cfg, cfg->Read(_T("cfgversion"), &version); // Migrate if needed switch(version) { case 0: { long sortmode = 0; cfg->Read(_T("window/sortmode"), &sortmode); cfg->DeleteEntry(_T("window/sortmode")); cfg->Write(_T("cfgversion"), 1); } break; case 1: // Current break; } ); } void Config::setBZFlagCommand(const wxString& cmd, const wxString& proto) { CFG_OP(cfg, cfg->Write(wxString::Format(_T("bzflag/%s"), proto.c_str()), cmd);); } wxRect Config::getWindowDimensions() const { wxRect wanted; CFG_OP(cfg, wanted.x = cfg->Read(_T("window/x"), 10); wanted.y = cfg->Read(_T("window/y"), 10); wanted.width = cfg->Read(_T("window/w"), 600); wanted.height = cfg->Read(_T("window/h"), 600); ); return wanted; } void Config::setWindowDimensions(wxRect r) { CFG_OP(cfg, cfg->Write(_T("window/x"), r.x); cfg->Write(_T("window/y"), r.y); cfg->Write(_T("window/h"), r.height); cfg->Write(_T("window/w"), r.width); ); } wxString Config::getColumnName(ColType t) const { static const wxString names [] = { _T("server"), _T("name"), _T("type"), _T("players"), _T("ping"), _T("favorite") }; return names[t]; } wxString Config::getColumnKey(ColType type) const { wxString key; key += _T("window/col_"); key += this->getColumnName(type); key += _T("_width"); return key; } int Config::getColumnDefaultWidth(ColType t) const { const int widths[] = { 157, 300, 47, 30, 46, 46 }; return widths[t]; } int Config::getColumnWidth(ColType type) const { int w; wxString key = this->getColumnKey(type); CFG_OP(cfg, w = cfg->Read(key, this->getColumnDefaultWidth(type)); ); return w; } void Config::setColumnWidth(ColType type, int w) { wxString key = this->getColumnKey(type); CFG_OP(cfg, cfg->Write(key,w);); } wxArrayString Config::getFavorites() const { wxString str; wxArrayString list; int count = 0; CFG_OP(cfg, while(cfg->Read(wxString::Format(_T("favorites/%d"), count), &str)) { list.Add(str); count++; } ); return list; } void Config::setFavorites(const wxArrayString& list) { CFG_OP(cfg, for(unsigned int i = 0; i < list.GetCount(); i++) cfg->Write(wxString::Format(_T("favorites/%d"), i), list.Item(i)); ); } wxString Config::getListServerURL(int n) const { int count = 0; wxString str; CFG_OP(cfg, while(cfg->Read(wxString::Format(_T("listserver/%d"), count), &str)) { if(count == n) return str; count++; } ); if(count == 0 && n == 1) return _T("http://bzstats.strayer.de/stuff/listserver.php"); else return _T("http://my.bzflag.org/db?action=LIST"); } viewlist_t Config::getViews() const { int count = 0; wxString query; long sortmode; viewlist_t list; CFG_OP(cfg, while( cfg->Read(wxString::Format(_T("views/%d.query"), count), &query) && cfg->Read(wxString::Format(_T("views/%d.sortmode"), count), &sortmode) ) { // Read it into serverlist-thingy ServerListView* view = new ServerListView(Query(query), sortmode); list.push_back(view); count++; } // Make sure we got at least one view if(list.size() == 0) { ServerListView* viewAll = new ServerListView(Query(_T("All")), sortmode); list.push_back(viewAll); ServerListView* viewRecent = new ServerListView(Query(_T("Recent")), sortmode); list.push_back(viewRecent); } ); return list; } void Config::setViews(viewlist_t list) { int count = 0; wxString query; long sortmode; viewlist_t old_list = this->getViews(); CFG_OP(cfg, for(viewlist_t::iterator i = list.begin(); i != list.end(); ++i ) { sortmode = (*i)->currentSortMode; query = (*i)->query.get(); cfg->Write(wxString::Format(_T("views/%d.query"), count), query); cfg->Write(wxString::Format(_T("views/%d.sortmode"), count), sortmode); count++; } for(;count < old_list.size(); count++) { cfg->DeleteEntry(wxString::Format(_T("views/%d.query"), count)); cfg->DeleteEntry(wxString::Format(_T("views/%d.sortmode"), count)); } ); } bool Config::getToolbarVisible() { bool rc = true; CFG_OP(cfg, cfg->Read(_T("window/toolbar"), &rc); ); return rc; } void Config::setToolbarVisible(bool b) { CFG_OP(cfg, cfg->Write(_T("window/toolbar"), b); ); } wxArrayString Config::getRecentServers() const { wxLogDebug(_T("getRecentservers()")); wxString str; wxArrayString list; int count = 0; CFG_OP(cfg, while(cfg->Read(wxString::Format(_T("recent/%d"), count), &str)) { wxLogDebug(str); list.Insert(str,0); count++; } ); return list; } void Config::setRecentServers(const wxArrayString& list) { CFG_OP(cfg, for(unsigned int i = 0; i < list.GetCount(); i++ ) cfg->Write(wxString::Format(_T("recent/%d"), i), list.Item(i)); ); } <commit_msg>Remember to initialize variable<commit_after>/* The MIT License Copyright (c) 2008 Dennis Mllegaard Pedersen <dennis@moellegaard.dk> 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 <wx/fileconf.h> #include "config.h" Config appConfig; Config::Config() { } Config::~Config() { } // FIXME - i hate to use this // This is a macro that will allocate and deallocate the wxConfig, since // our app crashes if we let it live too long (for some reason). This // is a temporary hack, which should be fixed ASAP. #define CFG_OP(cfg,op) \ wxFileConfig* cfg = new wxFileConfig(_T("bzlauncher")); \ { op } while(0); \ delete cfg; \ cfg = NULL; wxString Config::getBZFlagCommand(const wxString& proto) const { // first try bzflag/proto (eg bzflag/bzfs0026) // then try bzflag/default wxString key = wxString::Format(_T("bzflag/%s"), proto.Lower().c_str()); wxString cmd; CFG_OP(cfg, if(! cfg->Read(key, &cmd)) { if(! cfg->Read(_T("bzflag/default"), &cmd)) { return _T(""); } } ); return cmd; } void Config::versionCheck() { int version = 0; CFG_OP(cfg, cfg->Read(_T("cfgversion"), &version); // Migrate if needed switch(version) { case 0: { long sortmode = 0; cfg->Read(_T("window/sortmode"), &sortmode); cfg->DeleteEntry(_T("window/sortmode")); cfg->Write(_T("cfgversion"), 1); } break; case 1: // Current break; } ); } void Config::setBZFlagCommand(const wxString& cmd, const wxString& proto) { CFG_OP(cfg, cfg->Write(wxString::Format(_T("bzflag/%s"), proto.c_str()), cmd);); } wxRect Config::getWindowDimensions() const { wxRect wanted; CFG_OP(cfg, wanted.x = cfg->Read(_T("window/x"), 10); wanted.y = cfg->Read(_T("window/y"), 10); wanted.width = cfg->Read(_T("window/w"), 600); wanted.height = cfg->Read(_T("window/h"), 600); ); return wanted; } void Config::setWindowDimensions(wxRect r) { CFG_OP(cfg, cfg->Write(_T("window/x"), r.x); cfg->Write(_T("window/y"), r.y); cfg->Write(_T("window/h"), r.height); cfg->Write(_T("window/w"), r.width); ); } wxString Config::getColumnName(ColType t) const { static const wxString names [] = { _T("server"), _T("name"), _T("type"), _T("players"), _T("ping"), _T("favorite") }; return names[t]; } wxString Config::getColumnKey(ColType type) const { wxString key; key += _T("window/col_"); key += this->getColumnName(type); key += _T("_width"); return key; } int Config::getColumnDefaultWidth(ColType t) const { const int widths[] = { 157, 300, 47, 30, 46, 46 }; return widths[t]; } int Config::getColumnWidth(ColType type) const { int w; wxString key = this->getColumnKey(type); CFG_OP(cfg, w = cfg->Read(key, this->getColumnDefaultWidth(type)); ); return w; } void Config::setColumnWidth(ColType type, int w) { wxString key = this->getColumnKey(type); CFG_OP(cfg, cfg->Write(key,w);); } wxArrayString Config::getFavorites() const { wxString str; wxArrayString list; int count = 0; CFG_OP(cfg, while(cfg->Read(wxString::Format(_T("favorites/%d"), count), &str)) { list.Add(str); count++; } ); return list; } void Config::setFavorites(const wxArrayString& list) { CFG_OP(cfg, for(unsigned int i = 0; i < list.GetCount(); i++) cfg->Write(wxString::Format(_T("favorites/%d"), i), list.Item(i)); ); } wxString Config::getListServerURL(int n) const { int count = 0; wxString str; CFG_OP(cfg, while(cfg->Read(wxString::Format(_T("listserver/%d"), count), &str)) { if(count == n) return str; count++; } ); if(count == 0 && n == 1) return _T("http://bzstats.strayer.de/stuff/listserver.php"); else return _T("http://my.bzflag.org/db?action=LIST"); } viewlist_t Config::getViews() const { int count = 0; wxString query; long sortmode = 0; viewlist_t list; CFG_OP(cfg, while( cfg->Read(wxString::Format(_T("views/%d.query"), count), &query) && cfg->Read(wxString::Format(_T("views/%d.sortmode"), count), &sortmode) ) { // Read it into serverlist-thingy ServerListView* view = new ServerListView(Query(query), sortmode); list.push_back(view); count++; } // Make sure we got at least one view if(list.size() == 0) { ServerListView* viewAll = new ServerListView(Query(_T("All")), sortmode); list.push_back(viewAll); ServerListView* viewRecent = new ServerListView(Query(_T("Recent")), sortmode); list.push_back(viewRecent); } ); return list; } void Config::setViews(viewlist_t list) { int count = 0; wxString query; long sortmode; viewlist_t old_list = this->getViews(); CFG_OP(cfg, for(viewlist_t::iterator i = list.begin(); i != list.end(); ++i ) { sortmode = (*i)->currentSortMode; query = (*i)->query.get(); cfg->Write(wxString::Format(_T("views/%d.query"), count), query); cfg->Write(wxString::Format(_T("views/%d.sortmode"), count), sortmode); count++; } for(;count < old_list.size(); count++) { cfg->DeleteEntry(wxString::Format(_T("views/%d.query"), count)); cfg->DeleteEntry(wxString::Format(_T("views/%d.sortmode"), count)); } ); } bool Config::getToolbarVisible() { bool rc = true; CFG_OP(cfg, cfg->Read(_T("window/toolbar"), &rc); ); return rc; } void Config::setToolbarVisible(bool b) { CFG_OP(cfg, cfg->Write(_T("window/toolbar"), b); ); } wxArrayString Config::getRecentServers() const { wxLogDebug(_T("getRecentservers()")); wxString str; wxArrayString list; int count = 0; CFG_OP(cfg, while(cfg->Read(wxString::Format(_T("recent/%d"), count), &str)) { wxLogDebug(str); list.Insert(str,0); count++; } ); return list; } void Config::setRecentServers(const wxArrayString& list) { CFG_OP(cfg, for(unsigned int i = 0; i < list.GetCount(); i++ ) cfg->Write(wxString::Format(_T("recent/%d"), i), list.Item(i)); ); } <|endoftext|>
<commit_before>#include <iostream> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/format.hpp> #include <boost/regex.hpp> #include "include/sqlite3.h" #include "include/sqlite_types.hpp" void setup_mbtiles(std::string filename) { char* zErrMsg; namespace fs = boost::filesystem; sqlite3 *db; sqlite3_open(filename.c_str(), &db); sqlite3_exec(db, "create table tiles (zoom_level integer, tile_column " "integer, tile_row integer, tile_data blob); create table metadata " "(name text, value text); create unique index name on metadata (name);" "create unique index tile_index on tiles " "(zoom_level, tile_column, tile_row);", NULL, 0, &zErrMsg); } void disk_to_mbtiles(std::string input_filename, std::string output_filename) { namespace fs = boost::filesystem; double fsize; if (!fs::is_regular_file(output_filename)) { setup_mbtiles(output_filename); } sqlite3 *db; sqlite3_open(output_filename.c_str(), &db); static sqlite3_stmt *insert_statement; std::string s = "INSERT INTO tiles (zoom_level, tile_column, tile_row, tile_data) " " VALUES (?1, ?2, ?3, ?4);"; int rc = sqlite3_prepare_v2(db, s.c_str(), -1, &insert_statement, 0); // TODO: weak regex. static const boost::regex e("(\\w+)\\/(\\d+)\\/(\\d+)\\/(\\d+)\\.png"); for (boost::filesystem::recursive_directory_iterator end, dir(input_filename); dir != end; ++dir ) { if (fs::is_regular_file(*dir)) { boost::smatch what; if (boost::regex_match((*dir).string(), what, e, boost::match_any)) { fsize = fs::file_size(*dir); char* data = (char*) malloc(sizeof(char) * fsize); fs::ifstream f(*dir); while(!f.eof()) { f >> data; } f.close(); int z = atoi(what[1].str().c_str()); int x = atoi(what[3].str().c_str()); int y = atoi(what[4].str().c_str()); sqlite3_bind_int(insert_statement, 1, z); sqlite3_bind_int(insert_statement, 2, x); sqlite3_bind_int(insert_statement, 3, y); sqlite3_bind_blob(insert_statement, 4, data, fsize, SQLITE_TRANSIENT); sqlite3_step(insert_statement); sqlite3_reset(insert_statement); sqlite3_clear_bindings(insert_statement); free(data); } else { std::cout << "no match\n"; std::cout << (*dir).string() << "\n"; } } } sqlite3_finalize(insert_statement); sqlite3_close(db); } void mbtiles_to_disk(std::string input_filename, std::string output_filename) { namespace fs = boost::filesystem; sqlite_connection* dataset_ = new sqlite_connection(input_filename); std::ostringstream s; s << "SELECT zoom_level, tile_column, tile_row FROM tiles;"; sqlite_resultset* rs (dataset_->execute_query (s.str())); while (rs->is_valid() && rs->step_next()) { double z = rs->column_double(0); double x = rs->column_double(1); double y = rs->column_double(2); int size; const char* data = (const char *) rs->column_blob(3, size); fs::create_directories(str(boost::format("%s/%d/%d") % output_filename % z % x)); fs::ofstream file(str(boost::format("%s/%d/%d/%d.png") % output_filename % z % x % y)); file << data; file.close(); } } int main(int ac, char** av) { namespace po = boost::program_options; namespace fs = boost::filesystem; po::options_description desc("Allowed options"); desc.add_options() ("input", po::value<std::string>(), "input file") ("output", po::value<std::string>(), "output file") ("help", "produce help message"); po::variables_map vm; po::store(po::command_line_parser(ac, av). options(desc).run(), vm); po::notify(vm); if (vm.count("input") && vm.count("output")) { std::string input_filename = vm["input"].as<std::string>(); std::string output_filename = vm["output"].as<std::string>(); if (fs::is_regular_file(input_filename)) { mbtiles_to_disk(input_filename, output_filename); } else if (fs::is_directory(input_filename)) { disk_to_mbtiles(input_filename, output_filename); } } if (vm.count("help")) { std::cout << desc << "\n"; return 1; } return 0; } <commit_msg>Adding metadata support to mbtiles import.<commit_after>#include <iostream> #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/format.hpp> #include <boost/regex.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/foreach.hpp> #include "include/sqlite3.h" #include "include/sqlite_types.hpp" void setup_mbtiles(std::string filename) { char* zErrMsg; namespace fs = boost::filesystem; sqlite3 *db; sqlite3_open(filename.c_str(), &db); sqlite3_exec(db, "create table tiles (zoom_level integer, tile_column " "integer, tile_row integer, tile_data blob); create table metadata " "(name text, value text); create unique index name on metadata (name);" "create unique index tile_index on tiles " "(zoom_level, tile_column, tile_row);", NULL, 0, &zErrMsg); sqlite3_close(db); } void add_metadata(sqlite3* db, std::string k, std::string v) { static sqlite3_stmt *insert_statement; std::string s = "INSERT INTO metadata (name, value) " " VALUES (?1, ?2);"; sqlite3_prepare_v2(db, s.c_str(), -1, &insert_statement, 0); sqlite3_bind_text(insert_statement, 1, k.c_str(), -1, SQLITE_STATIC); sqlite3_bind_text(insert_statement, 2, v.c_str(), -1, SQLITE_STATIC); sqlite3_step(insert_statement); sqlite3_reset(insert_statement); sqlite3_clear_bindings(insert_statement); } void disk_to_mbtiles(std::string input_filename, std::string output_filename) { namespace fs = boost::filesystem; double fsize; sqlite3 *db; sqlite3_open(output_filename.c_str(), &db); static sqlite3_stmt *insert_statement; std::string s = "INSERT INTO tiles (zoom_level, tile_column, tile_row, tile_data) " " VALUES (?1, ?2, ?3, ?4);"; sqlite3_prepare_v2(db, s.c_str(), -1, &insert_statement, 0); if (!fs::is_regular_file(output_filename)) { setup_mbtiles(output_filename); } std::string metadata_location = str(boost::format("%s/metadata.json") % input_filename); if (fs::is_regular_file(metadata_location)) { boost::property_tree::ptree pt; boost::property_tree::read_json(metadata_location, pt); std::set<std::string> metadata_entries; BOOST_FOREACH(boost::property_tree::ptree::value_type &v, pt.get_child("metadata")) add_metadata(db, v.first.data(), v.second.data()); } else { std::cerr << "metadata.json not found\n"; } // TODO: weak regex. static const boost::regex e("(\\w+)\\/(\\d+)\\/(\\d+)\\/(\\d+)\\.png"); for (boost::filesystem::recursive_directory_iterator end, dir(input_filename); dir != end; ++dir ) { if (fs::is_regular_file(*dir)) { boost::smatch what; if (boost::regex_match((*dir).string(), what, e, boost::match_any)) { fsize = fs::file_size(*dir); char* data = (char*) malloc(sizeof(char) * fsize); fs::ifstream f(*dir); while(!f.eof()) { f >> data; } f.close(); int z = atoi(what[1].str().c_str()); int x = atoi(what[3].str().c_str()); int y = atoi(what[4].str().c_str()); sqlite3_bind_int(insert_statement, 1, z); sqlite3_bind_int(insert_statement, 2, x); sqlite3_bind_int(insert_statement, 3, y); sqlite3_bind_blob(insert_statement, 4, data, fsize, SQLITE_TRANSIENT); sqlite3_step(insert_statement); sqlite3_reset(insert_statement); sqlite3_clear_bindings(insert_statement); free(data); } else { std::cout << "no match\n"; std::cout << (*dir).string() << "\n"; } } } sqlite3_finalize(insert_statement); sqlite3_close(db); } void mbtiles_to_disk(std::string input_filename, std::string output_filename) { namespace fs = boost::filesystem; sqlite_connection* dataset_ = new sqlite_connection(input_filename); std::ostringstream s; s << "SELECT zoom_level, tile_column, tile_row FROM tiles;"; sqlite_resultset* rs (dataset_->execute_query (s.str())); while (rs->is_valid() && rs->step_next()) { double z = rs->column_double(0); double x = rs->column_double(1); double y = rs->column_double(2); int size; const char* data = (const char *) rs->column_blob(3, size); fs::create_directories(str(boost::format("%s/%d/%d") % output_filename % z % x)); fs::ofstream file(str(boost::format("%s/%d/%d/%d.png") % output_filename % z % x % y)); file << data; file.close(); } } int main(int ac, char** av) { namespace po = boost::program_options; namespace fs = boost::filesystem; po::options_description desc("Allowed options"); desc.add_options() ("input", po::value<std::string>(), "input file") ("output", po::value<std::string>(), "output file") ("m", po::value<std::string>(), "metadata") ("help", "produce help message"); po::variables_map vm; po::store(po::command_line_parser(ac, av). options(desc).run(), vm); po::notify(vm); if (vm.count("input") && vm.count("output")) { std::string input_filename = vm["input"].as<std::string>(); std::string output_filename = vm["output"].as<std::string>(); if (fs::is_regular_file(input_filename)) { mbtiles_to_disk(input_filename, output_filename); } else if (fs::is_directory(input_filename)) { disk_to_mbtiles(input_filename, output_filename); } } if (vm.count("help")) { std::cout << desc << "\n"; return 1; } return 0; } <|endoftext|>
<commit_before> <commit_msg>Delete 1.cpp<commit_after><|endoftext|>
<commit_before>/* * daemon.cpp * * Created on: Apr 7, 2013 * Author: nikita.karnauhov@gmail.com */ #include <string> #include <stdexcept> #include <memory> #include <iostream> #include <sstream> #include <iomanip> #include <fstream> #include <list> #include <set> #include <thread> #include <mutex> #include <algorithm> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <fcntl.h> #include <netinet/in.h> #include <netdb.h> #include <poll.h> #include <arpa/inet.h> #include <errno.h> #include <string.h> #include <getopt.h> #include <alsa/asoundlib.h> #include <unap.pb.h> #include "log.h" #include "alsa_wrapper.h" #include "player.h" #include "settings.h" static void _print_usage(std::ostream &_os) { _os << "UNAPd, network audio receiver.\n" << "Usage: unapd [OPTION]...\n\n" << " -h, --help Print this message and exit.\n" << " -v, --version Display the version and exit.\n" << " -c, --config-path Set configuration file location.\n" << " -l, --log-path Set log file location.\n" << " -L, --log-level Set log verbosity level (0 to 4, use 0 to disable logging).\n" << " -d, --daemon Run as a daemon.\n" << " -n, --no-daemon Don't run as a daemon, display log messages (default).\n" << " -p, --pid-path PID file location.\n" << "" << std::flush; } static void _print_version() { std::cout << "UNAPd, network audio receiver.\n" << "Version 0.1" << std::endl; } static void _parse_options(int _nArgs, char *const _pArgs[]) { static struct option options[] = { {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, {"config-path", required_argument, 0, 'c'}, // These options have equivalents in settings file. {"log-path", required_argument, 0, 'l'}, {"log-level", required_argument, 0, 'L'}, {"daemon", 0, 0, 'd'}, {"no-daemon", 0, 0, 'n'}, {"pid-path", 0, 0, 'p'}, {0, 0, 0, 0} }; const char *strOptions = "hvc:l:L:dnp:"; int nOption = 0; SettingsParser sp; std::map<std::string, std::string> kvs; // Handle --help, --version and --config-path options. while (true) { const int c = getopt_long(_nArgs, _pArgs, strOptions, options, &nOption); if (c == -1) { if (optind < _nArgs) throw RuntimeError("Redundant argument: %s", _pArgs[optind]); break; } switch (c) { case 'h': _print_usage(std::cout); exit(EXIT_SUCCESS); case 'v': _print_version(); exit(EXIT_SUCCESS); case 'c': sp.parse_file(optarg); break; case '?': _print_usage(std::cerr); exit(EXIT_FAILURE); default: kvs[std::find_if(std::begin(options), std::end(options), [c](struct option &_opt) {return _opt.val == c;})->name] = optarg; break; } } for (auto &kv : kvs) sp.parse_option(kv.first, kv.second); g_settings = sp.get(); } static void _main(Log &_log) { std::string strHost("127.0.0.1"); std::string strPort("26751"); // int m_nSocket = socket(PF_INET, SOCK_DGRAM, 0); // // if (m_nSocket < 0) // throw std::runtime_error(strerror(errno)); // // struct sockaddr_in name; // // name.sin_family = AF_INET; // name.sin_port = htons(nPort); // // struct hostent *pHost = gethostbyname(strHost.c_str()); // // if (!pHost) // throw std::runtime_error(strerror(errno)); // // name.sin_addr = *(struct in_addr *)pHost->h_addr; struct addrinfo hints; struct addrinfo *serverinfo; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_flags = AI_PASSIVE; if (getaddrinfo(NULL, strPort.c_str(), &hints, &serverinfo) < 0) throw SystemError("getaddrinfo()"); const int nSocket = socket(serverinfo->ai_family, serverinfo->ai_socktype, serverinfo->ai_protocol); if (bind(nSocket, serverinfo->ai_addr, serverinfo->ai_addrlen) < 0) throw SystemError("bind()"); freeaddrinfo(serverinfo); struct pollfd fd{nSocket, POLLIN, 0}; size_t cBufferSize = 1024*100; // Should be enough, right? auto pBuf = std::unique_ptr<char[]>(new char[cBufferSize]); std::list<unap::Packet> packets; // unap::Packet p; // // player.init(p); // player.play(p); // // return EXIT_SUCCESS; while (true) { if (poll(&fd, 1, 1000) < 0) throw SystemError("poll()"); if (fd.revents & POLLIN) { struct sockaddr sender; socklen_t sendsize = sizeof(sender); bzero(&sender, sizeof(sender)); const int nPacketSize = recvfrom(fd.fd, pBuf.get(), cBufferSize, 0, &sender, &sendsize); char strSender[128]; if (nPacketSize < 0) throw SystemError("recvfrom()"); inet_ntop(sender.sa_family, &((struct sockaddr_in &)sender).sin_addr, strSender, sizeof(strSender)); unap::Packet &packet = *packets.emplace(packets.end()); if (!packet.ParseFromArray(pBuf.get(), nPacketSize)) { std::cerr << "Broken packet." << std::endl; continue; } Player *pPlayer = Player::get(packet, _log); if (!pPlayer->is_prepared()) { pPlayer->init(packet); pPlayer->run(); } pPlayer->play(packet); } } } int main(int _nArgs, char *const _pArgs[]) { Log log(""); try { _parse_options(_nArgs, _pArgs); if (!g_settings.strLogPath.empty()) log.open(g_settings.strLogPath); if (g_settings.bDaemon) log.close(""); _main(log); } catch (std::exception &e) { log.log(llError, e.what()); return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>Daemonize.<commit_after>/* * daemon.cpp * * Created on: Apr 7, 2013 * Author: nikita.karnauhov@gmail.com */ #include <string> #include <stdexcept> #include <memory> #include <iostream> #include <sstream> #include <iomanip> #include <fstream> #include <list> #include <set> #include <thread> #include <mutex> #include <algorithm> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <fcntl.h> #include <netinet/in.h> #include <netdb.h> #include <poll.h> #include <arpa/inet.h> #include <errno.h> #include <string.h> #include <getopt.h> #include <alsa/asoundlib.h> #include <unap.pb.h> #include "log.h" #include "alsa_wrapper.h" #include "player.h" #include "settings.h" static void _print_usage(std::ostream &_os) { _os << "UNAPd, network audio receiver.\n" << "Usage: unapd [OPTION]...\n\n" << " -h, --help Print this message and exit.\n" << " -v, --version Display the version and exit.\n" << " -c, --config-path Set configuration file location.\n" << " -l, --log-path Set log file location.\n" << " -L, --log-level Set log verbosity level (0 to 4, use 0 to disable logging).\n" << " -d, --daemon Run as a daemon.\n" << " -n, --no-daemon Don't run as a daemon, display log messages (default).\n" << " -p, --pid-path PID file location.\n" << "" << std::flush; } static void _print_version() { std::cout << "UNAPd, network audio receiver.\n" << "Version 0.1" << std::endl; } static void _parse_options(int _nArgs, char *const _pArgs[]) { static struct option options[] = { {"help", 0, 0, 'h'}, {"version", 0, 0, 'v'}, {"config-path", required_argument, 0, 'c'}, // These options have equivalents in settings file. {"log-path", required_argument, 0, 'l'}, {"log-level", required_argument, 0, 'L'}, {"daemon", 0, 0, 'd'}, {"no-daemon", 0, 0, 'n'}, {"pid-path", 0, 0, 'p'}, {0, 0, 0, 0} }; const char *strOptions = "hvc:l:L:dnp:"; int nOption = 0; SettingsParser sp; std::map<std::string, std::string> kvs; // Handle --help, --version and --config-path options. while (true) { const int c = getopt_long(_nArgs, _pArgs, strOptions, options, &nOption); if (c == -1) { if (optind < _nArgs) throw RuntimeError("Redundant argument: %s", _pArgs[optind]); break; } switch (c) { case 'h': _print_usage(std::cout); exit(EXIT_SUCCESS); case 'v': _print_version(); exit(EXIT_SUCCESS); case 'c': sp.parse_file(optarg); break; case '?': _print_usage(std::cerr); exit(EXIT_FAILURE); default: kvs[std::find_if(std::begin(options), std::end(options), [c](struct option &_opt) {return _opt.val == c;})->name] = optarg; break; } } for (auto &kv : kvs) sp.parse_option(kv.first, kv.second); g_settings = sp.get(); } static void _main(Log &_log) { std::string strHost("127.0.0.1"); std::string strPort("26751"); // int m_nSocket = socket(PF_INET, SOCK_DGRAM, 0); // // if (m_nSocket < 0) // throw std::runtime_error(strerror(errno)); // // struct sockaddr_in name; // // name.sin_family = AF_INET; // name.sin_port = htons(nPort); // // struct hostent *pHost = gethostbyname(strHost.c_str()); // // if (!pHost) // throw std::runtime_error(strerror(errno)); // // name.sin_addr = *(struct in_addr *)pHost->h_addr; struct addrinfo hints; struct addrinfo *serverinfo; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_flags = AI_PASSIVE; if (getaddrinfo(NULL, strPort.c_str(), &hints, &serverinfo) < 0) throw SystemError("getaddrinfo()"); const int nSocket = socket(serverinfo->ai_family, serverinfo->ai_socktype, serverinfo->ai_protocol); if (bind(nSocket, serverinfo->ai_addr, serverinfo->ai_addrlen) < 0) throw SystemError("bind()"); freeaddrinfo(serverinfo); struct pollfd fd{nSocket, POLLIN, 0}; size_t cBufferSize = 1024*100; // Should be enough, right? auto pBuf = std::unique_ptr<char[]>(new char[cBufferSize]); std::list<unap::Packet> packets; // unap::Packet p; // // player.init(p); // player.play(p); // // return EXIT_SUCCESS; while (true) { if (poll(&fd, 1, 1000) < 0) throw SystemError("poll()"); if (fd.revents & POLLIN) { struct sockaddr sender; socklen_t sendsize = sizeof(sender); bzero(&sender, sizeof(sender)); const int nPacketSize = recvfrom(fd.fd, pBuf.get(), cBufferSize, 0, &sender, &sendsize); char strSender[128]; if (nPacketSize < 0) throw SystemError("recvfrom()"); inet_ntop(sender.sa_family, &((struct sockaddr_in &)sender).sin_addr, strSender, sizeof(strSender)); unap::Packet &packet = *packets.emplace(packets.end()); if (!packet.ParseFromArray(pBuf.get(), nPacketSize)) { std::cerr << "Broken packet." << std::endl; continue; } Player *pPlayer = Player::get(packet, _log); if (!pPlayer->is_prepared()) { pPlayer->init(packet); pPlayer->run(); } pPlayer->play(packet); } } } int main(int _nArgs, char *const _pArgs[]) { Log log(""); try { _parse_options(_nArgs, _pArgs); if (!g_settings.strLogPath.empty()) log.open(g_settings.strLogPath); if (g_settings.bDaemon) { log.close(""); if (daemon(true, false) != 0) throw SystemError("daemon()"); } _main(log); } catch (std::exception &e) { log.log(llError, e.what()); return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2015 Intel Corporation. All Rights Reserved. #include "device.h" #include "sync.h" #include <array> using namespace rsimpl; rs_device::rs_device(std::shared_ptr<rsimpl::uvc::device> device, const rsimpl::static_device_info & info) : device(device), config(info), capturing(false), depth(config, RS_STREAM_DEPTH), color(config, RS_STREAM_COLOR), infrared(config, RS_STREAM_INFRARED), infrared2(config, RS_STREAM_INFRARED2), points(depth), rect_color(color), color_to_depth(color, depth), depth_to_color(depth, color), depth_to_rect_color(depth, rect_color), infrared2_to_depth(infrared2,depth), depth_to_infrared2(depth,infrared2) { streams[RS_STREAM_DEPTH ] = native_streams[RS_STREAM_DEPTH] = &depth; streams[RS_STREAM_COLOR ] = native_streams[RS_STREAM_COLOR] = &color; streams[RS_STREAM_INFRARED ] = native_streams[RS_STREAM_INFRARED] = &infrared; streams[RS_STREAM_INFRARED2] = native_streams[RS_STREAM_INFRARED2] = &infrared2; streams[RS_STREAM_POINTS] = &points; streams[RS_STREAM_RECTIFIED_COLOR] = &rect_color; streams[RS_STREAM_COLOR_ALIGNED_TO_DEPTH] = &color_to_depth; streams[RS_STREAM_DEPTH_ALIGNED_TO_COLOR] = &depth_to_color; streams[RS_STREAM_DEPTH_ALIGNED_TO_RECTIFIED_COLOR] = &depth_to_rect_color; streams[RS_STREAM_INFRARED2_ALIGNED_TO_DEPTH] = &infrared2_to_depth; streams[RS_STREAM_DEPTH_ALIGNED_TO_INFRARED2] = &depth_to_infrared2; } rs_device::~rs_device() { } bool rs_device::supports_option(rs_option option) const { if(uvc::is_pu_control(option)) return true; for(auto & o : config.info.options) if(o.option == option) return true; return false; } void rs_device::enable_stream(rs_stream stream, int width, int height, rs_format format, int fps) { if(capturing) throw std::runtime_error("streams cannot be reconfigured after having called rs_start_device()"); if(config.info.stream_subdevices[stream] == -1) throw std::runtime_error("unsupported stream"); config.requests[stream] = {true, width, height, format, fps}; for(auto & s : native_streams) s->archive.reset(); // Changing stream configuration invalidates the current stream info } void rs_device::enable_stream_preset(rs_stream stream, rs_preset preset) { if(capturing) throw std::runtime_error("streams cannot be reconfigured after having called rs_start_device()"); if(!config.info.presets[stream][preset].enabled) throw std::runtime_error("unsupported stream"); config.requests[stream] = config.info.presets[stream][preset]; for(auto & s : native_streams) s->archive.reset(); // Changing stream configuration invalidates the current stream info } void rs_device::disable_stream(rs_stream stream) { if(capturing) throw std::runtime_error("streams cannot be reconfigured after having called rs_start_device()"); if(config.info.stream_subdevices[stream] == -1) throw std::runtime_error("unsupported stream"); config.requests[stream] = {}; for(auto & s : native_streams) s->archive.reset(); // Changing stream configuration invalidates the current stream info } void rs_device::set_stream_callback(rs_stream stream, void (*on_frame)(rs_device * device, rs_frame_ref * frame, void * user), void * user) { config.callbacks[stream] = {this, on_frame, user}; } void rs_device::start() { if(capturing) throw std::runtime_error("cannot restart device without first stopping device"); auto selected_modes = config.select_modes(); auto archive = std::make_shared<frame_archive>(selected_modes, select_key_stream(selected_modes)); auto timestamp_reader = create_frame_timestamp_reader(); for(auto & s : native_streams) s->archive.reset(); // Starting capture invalidates the current stream info, if any exists from previous capture // Satisfy stream_requests as necessary for each subdevice, calling set_mode and // dispatching the uvc configuration for a requested stream to the hardware for(auto mode_selection : selected_modes) { // Create a stream buffer for each stream served by this subdevice mode for(auto & stream_mode : mode_selection.get_outputs()) { // If this is one of the streams requested by the user, store the buffer so they can access it if(config.requests[stream_mode.first].enabled) native_streams[stream_mode.first]->archive = archive; } // Copy the callbacks that apply to this stream, so that they can be captured by value std::vector<frame_callback> callbacks; std::vector<rs_stream> streams; for (auto & output : mode_selection.get_outputs()) { callbacks.push_back(config.callbacks[output.first]); streams.push_back(output.first); } // Initialize the subdevice and set it to the selected mode set_subdevice_mode(*device, mode_selection.mode.subdevice, mode_selection.mode.native_dims.x, mode_selection.mode.native_dims.y, mode_selection.mode.pf.fourcc, mode_selection.mode.fps, [mode_selection, archive, timestamp_reader, callbacks, streams](const void * frame) mutable { // Ignore any frames which appear corrupted or invalid if(!timestamp_reader->validate_frame(mode_selection.mode, frame)) return; // Determine the timestamp for this frame int timestamp = timestamp_reader->get_frame_timestamp(mode_selection.mode, frame); // Obtain buffers for unpacking the frame std::vector<byte *> dest; for(auto & output : mode_selection.get_outputs()) dest.push_back(archive->alloc_frame(output.first, timestamp)); // Unpack the frame mode_selection.unpack(dest.data(), reinterpret_cast<const byte *>(frame)); // If any frame callbacks were specified, dispatch them now for (size_t i = 0; i < dest.size(); ++i) { if (callbacks[i]) { auto frame_ref = archive->track_frame(streams[i]); if (frame_ref) { callbacks[i]((rs_frame_ref*)frame_ref); } } else { // Commit the frame to the archive archive->commit_frame(streams[i]); } } }); } this->archive = archive; on_before_start(selected_modes); start_streaming(*device, config.info.num_libuvc_transfer_buffers); capture_started = std::chrono::high_resolution_clock::now(); capturing = true; } void rs_device::stop() { if(!capturing) throw std::runtime_error("cannot stop device without first starting device"); stop_streaming(*device); archive->flush(); capturing = false; } void rs_device::wait_all_streams() { if(!capturing) return; if(!archive) return; archive->wait_for_frames(); } bool rs_device::poll_all_streams() { if(!capturing) return false; if(!archive) return false; return archive->poll_for_frames(); } rs_frameset* rs_device::wait_all_streams_safe() { if (!capturing) throw std::runtime_error("Can't call wait_for_frames_safe when the device is not capturing!"); if (!archive) throw std::runtime_error("Can't call wait_for_frames_safe when frame archive is not available!"); return (rs_frameset*)archive->wait_for_frames_safe(); } bool rs_device::poll_all_streams_safe(rs_frameset** frames) { if (!capturing) return false; if (!archive) return false; return archive->poll_for_frames_safe((frame_archive::frameset**)frames); } void rs_device::release_frames(rs_frameset * frameset) { archive->release_frameset((frame_archive::frameset *)frameset); } rs_frameset * rs_device::clone_frames(rs_frameset * frameset) { auto result = archive->clone_frameset((frame_archive::frameset *)frameset); if (!result) throw std::runtime_error("Not enough resources to clone frameset!"); return (rs_frameset*)result; } rs_frame_ref* rs_device::detach_frame(const rs_frameset* fs, rs_stream stream) { auto result = archive->detach_frame_ref((frame_archive::frameset *)fs, stream); if (!result) throw std::runtime_error("Not enough resources to tack detached frame!"); return (rs_frame_ref*)result; } void rs_device::release_frame(rs_frame_ref* ref) { archive->release_frame_ref((frame_archive::frame_ref *)ref); } rs_frame_ref* ::rs_device::clone_frame(rs_frame_ref* frame) { auto result = archive->clone_frame((frame_archive::frame_ref *)frame); if (!result) throw std::runtime_error("Not enough resources to clone frame!"); return (rs_frame_ref*)result; } void rs_device::get_option_range(rs_option option, double & min, double & max, double & step, double & def) { if(uvc::is_pu_control(option)) { int mn, mx, stp, df; uvc::get_pu_control_range(get_device(), config.info.stream_subdevices[RS_STREAM_COLOR], option, &mn, &mx, &stp, &df); min = mn; max = mx; step = stp; def = df; return; } for(auto & o : config.info.options) { if(o.option == option) { min = o.min; max = o.max; step = o.step; def = o.def; return; } } throw std::logic_error("range not specified"); } <commit_msg>Moving forward to frame callback continuations<commit_after>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2015 Intel Corporation. All Rights Reserved. #include "device.h" #include "sync.h" #include <array> using namespace rsimpl; rs_device::rs_device(std::shared_ptr<rsimpl::uvc::device> device, const rsimpl::static_device_info & info) : device(device), config(info), capturing(false), depth(config, RS_STREAM_DEPTH), color(config, RS_STREAM_COLOR), infrared(config, RS_STREAM_INFRARED), infrared2(config, RS_STREAM_INFRARED2), points(depth), rect_color(color), color_to_depth(color, depth), depth_to_color(depth, color), depth_to_rect_color(depth, rect_color), infrared2_to_depth(infrared2,depth), depth_to_infrared2(depth,infrared2) { streams[RS_STREAM_DEPTH ] = native_streams[RS_STREAM_DEPTH] = &depth; streams[RS_STREAM_COLOR ] = native_streams[RS_STREAM_COLOR] = &color; streams[RS_STREAM_INFRARED ] = native_streams[RS_STREAM_INFRARED] = &infrared; streams[RS_STREAM_INFRARED2] = native_streams[RS_STREAM_INFRARED2] = &infrared2; streams[RS_STREAM_POINTS] = &points; streams[RS_STREAM_RECTIFIED_COLOR] = &rect_color; streams[RS_STREAM_COLOR_ALIGNED_TO_DEPTH] = &color_to_depth; streams[RS_STREAM_DEPTH_ALIGNED_TO_COLOR] = &depth_to_color; streams[RS_STREAM_DEPTH_ALIGNED_TO_RECTIFIED_COLOR] = &depth_to_rect_color; streams[RS_STREAM_INFRARED2_ALIGNED_TO_DEPTH] = &infrared2_to_depth; streams[RS_STREAM_DEPTH_ALIGNED_TO_INFRARED2] = &depth_to_infrared2; } rs_device::~rs_device() { } bool rs_device::supports_option(rs_option option) const { if(uvc::is_pu_control(option)) return true; for(auto & o : config.info.options) if(o.option == option) return true; return false; } void rs_device::enable_stream(rs_stream stream, int width, int height, rs_format format, int fps) { if(capturing) throw std::runtime_error("streams cannot be reconfigured after having called rs_start_device()"); if(config.info.stream_subdevices[stream] == -1) throw std::runtime_error("unsupported stream"); config.requests[stream] = {true, width, height, format, fps}; for(auto & s : native_streams) s->archive.reset(); // Changing stream configuration invalidates the current stream info } void rs_device::enable_stream_preset(rs_stream stream, rs_preset preset) { if(capturing) throw std::runtime_error("streams cannot be reconfigured after having called rs_start_device()"); if(!config.info.presets[stream][preset].enabled) throw std::runtime_error("unsupported stream"); config.requests[stream] = config.info.presets[stream][preset]; for(auto & s : native_streams) s->archive.reset(); // Changing stream configuration invalidates the current stream info } void rs_device::disable_stream(rs_stream stream) { if(capturing) throw std::runtime_error("streams cannot be reconfigured after having called rs_start_device()"); if(config.info.stream_subdevices[stream] == -1) throw std::runtime_error("unsupported stream"); config.requests[stream] = {}; for(auto & s : native_streams) s->archive.reset(); // Changing stream configuration invalidates the current stream info } void rs_device::set_stream_callback(rs_stream stream, void (*on_frame)(rs_device * device, rs_frame_ref * frame, void * user), void * user) { config.callbacks[stream] = {this, on_frame, user}; } void rs_device::start() { if(capturing) throw std::runtime_error("cannot restart device without first stopping device"); auto selected_modes = config.select_modes(); auto archive = std::make_shared<frame_archive>(selected_modes, select_key_stream(selected_modes)); auto timestamp_reader = create_frame_timestamp_reader(); for(auto & s : native_streams) s->archive.reset(); // Starting capture invalidates the current stream info, if any exists from previous capture // Satisfy stream_requests as necessary for each subdevice, calling set_mode and // dispatching the uvc configuration for a requested stream to the hardware for(auto mode_selection : selected_modes) { // Create a stream buffer for each stream served by this subdevice mode for(auto & stream_mode : mode_selection.get_outputs()) { // If this is one of the streams requested by the user, store the buffer so they can access it if(config.requests[stream_mode.first].enabled) native_streams[stream_mode.first]->archive = archive; } // Copy the callbacks that apply to this stream, so that they can be captured by value std::vector<frame_callback> callbacks; std::vector<rs_stream> streams; for (auto & output : mode_selection.get_outputs()) { callbacks.push_back(config.callbacks[output.first]); streams.push_back(output.first); } // Initialize the subdevice and set it to the selected mode set_subdevice_mode(*device, mode_selection.mode.subdevice, mode_selection.mode.native_dims.x, mode_selection.mode.native_dims.y, mode_selection.mode.pf.fourcc, mode_selection.mode.fps, [mode_selection, archive, timestamp_reader, callbacks, streams](const void * frame, std::function<void()> continuation) mutable { frame_continuation release_and_enqueue(continuation); // Ignore any frames which appear corrupted or invalid if(!timestamp_reader->validate_frame(mode_selection.mode, frame)) return; // Determine the timestamp for this frame int timestamp = timestamp_reader->get_frame_timestamp(mode_selection.mode, frame); // Obtain buffers for unpacking the frame std::vector<byte *> dest; for(auto & output : mode_selection.get_outputs()) dest.push_back(archive->alloc_frame(output.first, timestamp)); // Unpack the frame mode_selection.unpack(dest.data(), reinterpret_cast<const byte *>(frame)); // If any frame callbacks were specified, dispatch them now for (size_t i = 0; i < dest.size(); ++i) { if (callbacks[i]) { auto frame_ref = archive->track_frame(streams[i]); if (frame_ref) { callbacks[i]((rs_frame_ref*)frame_ref); } } else { // Commit the frame to the archive archive->commit_frame(streams[i]); } } }); } this->archive = archive; on_before_start(selected_modes); start_streaming(*device, config.info.num_libuvc_transfer_buffers); capture_started = std::chrono::high_resolution_clock::now(); capturing = true; } void rs_device::stop() { if(!capturing) throw std::runtime_error("cannot stop device without first starting device"); stop_streaming(*device); archive->flush(); capturing = false; } void rs_device::wait_all_streams() { if(!capturing) return; if(!archive) return; archive->wait_for_frames(); } bool rs_device::poll_all_streams() { if(!capturing) return false; if(!archive) return false; return archive->poll_for_frames(); } rs_frameset* rs_device::wait_all_streams_safe() { if (!capturing) throw std::runtime_error("Can't call wait_for_frames_safe when the device is not capturing!"); if (!archive) throw std::runtime_error("Can't call wait_for_frames_safe when frame archive is not available!"); return (rs_frameset*)archive->wait_for_frames_safe(); } bool rs_device::poll_all_streams_safe(rs_frameset** frames) { if (!capturing) return false; if (!archive) return false; return archive->poll_for_frames_safe((frame_archive::frameset**)frames); } void rs_device::release_frames(rs_frameset * frameset) { archive->release_frameset((frame_archive::frameset *)frameset); } rs_frameset * rs_device::clone_frames(rs_frameset * frameset) { auto result = archive->clone_frameset((frame_archive::frameset *)frameset); if (!result) throw std::runtime_error("Not enough resources to clone frameset!"); return (rs_frameset*)result; } rs_frame_ref* rs_device::detach_frame(const rs_frameset* fs, rs_stream stream) { auto result = archive->detach_frame_ref((frame_archive::frameset *)fs, stream); if (!result) throw std::runtime_error("Not enough resources to tack detached frame!"); return (rs_frame_ref*)result; } void rs_device::release_frame(rs_frame_ref* ref) { archive->release_frame_ref((frame_archive::frame_ref *)ref); } rs_frame_ref* ::rs_device::clone_frame(rs_frame_ref* frame) { auto result = archive->clone_frame((frame_archive::frame_ref *)frame); if (!result) throw std::runtime_error("Not enough resources to clone frame!"); return (rs_frame_ref*)result; } void rs_device::get_option_range(rs_option option, double & min, double & max, double & step, double & def) { if(uvc::is_pu_control(option)) { int mn, mx, stp, df; uvc::get_pu_control_range(get_device(), config.info.stream_subdevices[RS_STREAM_COLOR], option, &mn, &mx, &stp, &df); min = mn; max = mx; step = stp; def = df; return; } for(auto & o : config.info.options) { if(o.option == option) { min = o.min; max = o.max; step = o.step; def = o.def; return; } } throw std::logic_error("range not specified"); } <|endoftext|>
<commit_before>#include "dhcurve.h" Local<Value> bnToBuf(const BIGNUM *bn) { int bytes = BN_num_bytes(bn); Local<Object> buffer = NanNewBufferHandle(bytes); if(BN_bn2bin(bn, (unsigned char *) Buffer::Data(buffer)) < 0) { NanThrowError("Failed to create Buffer from BIGNUM"); return NanUndefined(); } return buffer; } BIGNUM *bufToBn(const Local<Value> buf) { BIGNUM *r; if((r = BN_bin2bn((unsigned char *) Buffer::Data(buf), Buffer::Length(buf), NULL)) == NULL) { NanThrowError("Failed to create BIGNUM from Buffer"); return NULL; } return r; } EC_POINT *jsPointToPoint(const EC_GROUP *group, const Local<Object> obj) { EC_POINT *point = EC_POINT_new(group); if(point == NULL) { NanThrowError("Failed to create EC_POINT from Point"); return NULL; } S_BIGNUM x(bufToBn(obj->Get(NanNew<String>("x")))); if(x.get() == NULL) { NanThrowError("Failed to create BIGNUM from x"); return NULL; } S_BIGNUM y(bufToBn(obj->Get(NanNew<String>("y")))); if(y.get() == NULL) { NanThrowError("Failed to create BIGNUM from y"); return NULL; } ScopedOpenSSL<BN_CTX, BN_CTX_free> ctx(BN_CTX_new()); BN_CTX_start(ctx.get()); if(EC_POINT_set_affine_coordinates_GF2m(group, point, x.get(), y.get(), ctx.get()) == 0) { NanThrowError("Failed to set coords for EC_POINT"); BN_CTX_end(ctx.get()); return NULL; } BN_CTX_end(ctx.get()); return point; } NAN_METHOD(GetSharedSecret) { NanScope(); NanUtf8String namedCurve(args[0]); S_EC_KEY key(EC_KEY_new_by_curve_name(OBJ_sn2nid(*namedCurve))); if(key.get() == NULL) { NanThrowError("Key could not be created using curve name"); NanReturnUndefined(); } Local<Value> buf = args[1]; S_BIGNUM privateKey(bufToBn(buf)); if(privateKey.get() == NULL) { NanThrowError("Could not use private key"); NanReturnUndefined(); } EC_KEY_set_private_key(key.get(), (const BIGNUM *) privateKey.get()); const EC_GROUP *group = EC_KEY_get0_group(key.get()); S_EC_POINT peerKey(jsPointToPoint(group, Local<Object>::Cast(args[2]))); if(peerKey.get() == NULL) { NanThrowError("Could not use remote public key provided"); NanReturnUndefined(); } int length = Buffer::Length(buf); if((EC_GROUP_get_degree(group) + 7) / 8 != length) { NanThrowError("Private key is incorrect size"); NanReturnUndefined(); } char* secret = new char[length]; if(ECDH_compute_key(secret, length, peerKey.get(), key.get(), NULL) != length) { NanThrowError("Can not compute ECDH shared key"); delete secret; NanReturnUndefined(); } Local<Object> r = NanNewBufferHandle(secret, length); delete secret; NanReturnValue(r); } NAN_METHOD(GenerateKeyPair) { NanScope(); NanUtf8String namedCurve(args[0]); int curve = OBJ_sn2nid(*namedCurve); if(curve == NID_undef) { NanThrowError("Invalid curve name"); } S_EC_KEY key(EC_KEY_new_by_curve_name(curve)); if(key.get() == NULL) { NanThrowError("Key could not be created using curve name"); NanReturnUndefined(); } if(EC_KEY_generate_key(key.get()) == 0) { NanThrowError("Key failed to generate"); NanReturnUndefined(); } Local<Object> r = NanNew<Object>(); r->Set(NanNew<String>("privateKey"), bnToBuf(EC_KEY_get0_private_key(key.get()))); const EC_POINT *publicKey = EC_KEY_get0_public_key(key.get()); const EC_GROUP *group = EC_KEY_get0_group(key.get()); S_BIGNUM x(BN_new()); S_BIGNUM y(BN_new()); if(publicKey == NULL || group == NULL) { NanThrowError("Could not get public key"); NanReturnUndefined(); } EC_POINT_get_affine_coordinates_GFp(group, publicKey, x.get(), y.get(), NULL); Local<Object> point = NanNew<Object>(); point->Set(NanNew<String>("x"), bnToBuf(x.get())); point->Set(NanNew<String>("y"), bnToBuf(y.get())); r->Set(NanNew<String>("publicKey"), point); NanReturnValue(r); } void Init(Handle<Object> exports, Handle<Value> module) { NODE_SET_METHOD(exports, "generateKeyPair", GenerateKeyPair); NODE_SET_METHOD(exports, "getSharedSecret", GetSharedSecret); } NODE_MODULE(dhcurve, Init) <commit_msg>nan fixes<commit_after>#include "dhcurve.h" Local<Value> bnToBuf(const BIGNUM *bn) { int bytes = BN_num_bytes(bn); Local<Object> buffer = NanNewBufferHandle(bytes); if(BN_bn2bin(bn, (unsigned char *) Buffer::Data(buffer)) < 0) { NanThrowError("Failed to create Buffer from BIGNUM"); return NanUndefined(); } return buffer; } BIGNUM *bufToBn(const Local<Value> buf) { BIGNUM *r; if((r = BN_bin2bn((unsigned char *) Buffer::Data(buf), Buffer::Length(buf), NULL)) == NULL) { NanThrowError("Failed to create BIGNUM from Buffer"); return NULL; } return r; } EC_POINT *jsPointToPoint(const EC_GROUP *group, const Local<Object> obj) { EC_POINT *point = EC_POINT_new(group); if(point == NULL) { NanThrowError("Failed to create EC_POINT from Point"); return NULL; } S_BIGNUM x(bufToBn(obj->Get(NanNew<String>("x")))); if(x.get() == NULL) { NanThrowError("Failed to create BIGNUM from x"); return NULL; } S_BIGNUM y(bufToBn(obj->Get(NanNew<String>("y")))); if(y.get() == NULL) { NanThrowError("Failed to create BIGNUM from y"); return NULL; } ScopedOpenSSL<BN_CTX, BN_CTX_free> ctx(BN_CTX_new()); BN_CTX_start(ctx.get()); if(EC_POINT_set_affine_coordinates_GF2m(group, point, x.get(), y.get(), ctx.get()) == 0) { NanThrowError("Failed to set coords for EC_POINT"); BN_CTX_end(ctx.get()); return NULL; } BN_CTX_end(ctx.get()); return point; } NAN_METHOD(GetSharedSecret) { NanScope(); NanUtf8String namedCurve(args[0]); S_EC_KEY key(EC_KEY_new_by_curve_name(OBJ_sn2nid(*namedCurve))); if(key.get() == NULL) { NanThrowError("Key could not be created using curve name"); NanReturnUndefined(); } Local<Value> buf = args[1]; S_BIGNUM privateKey(bufToBn(buf)); if(privateKey.get() == NULL) { NanThrowError("Could not use private key"); NanReturnUndefined(); } EC_KEY_set_private_key(key.get(), (const BIGNUM *) privateKey.get()); const EC_GROUP *group = EC_KEY_get0_group(key.get()); S_EC_POINT peerKey(jsPointToPoint(group, Local<Object>::Cast(args[2]))); if(peerKey.get() == NULL) { NanThrowError("Could not use remote public key provided"); NanReturnUndefined(); } int length = Buffer::Length(buf); if((EC_GROUP_get_degree(group) + 7) / 8 != length) { NanThrowError("Private key is incorrect size"); NanReturnUndefined(); } char* secret = new char[length]; if(ECDH_compute_key(secret, length, peerKey.get(), key.get(), NULL) != length) { NanThrowError("Can not compute ECDH shared key"); delete secret; NanReturnUndefined(); } Local<Object> r = NanNewBufferHandle(secret, length); delete secret; NanReturnValue(r); } NAN_METHOD(GenerateKeyPair) { NanScope(); NanUtf8String namedCurve(args[0]); int curve = OBJ_sn2nid(*namedCurve); if(curve == NID_undef) { NanThrowError("Invalid curve name"); } S_EC_KEY key(EC_KEY_new_by_curve_name(curve)); if(key.get() == NULL) { NanThrowError("Key could not be created using curve name"); NanReturnUndefined(); } if(EC_KEY_generate_key(key.get()) == 0) { NanThrowError("Key failed to generate"); NanReturnUndefined(); } Local<Object> r = NanNew<Object>(); r->Set(NanNew<String>("privateKey"), bnToBuf(EC_KEY_get0_private_key(key.get()))); const EC_POINT *publicKey = EC_KEY_get0_public_key(key.get()); const EC_GROUP *group = EC_KEY_get0_group(key.get()); S_BIGNUM x(BN_new()); S_BIGNUM y(BN_new()); if(publicKey == NULL || group == NULL) { NanThrowError("Could not get public key"); NanReturnUndefined(); } EC_POINT_get_affine_coordinates_GFp(group, publicKey, x.get(), y.get(), NULL); Local<Object> point = NanNew<Object>(); point->Set(NanNew<String>("x"), bnToBuf(x.get())); point->Set(NanNew<String>("y"), bnToBuf(y.get())); r->Set(NanNew<String>("publicKey"), point); NanReturnValue(r); } void init(Handle<Object> exports) { NODE_SET_METHOD(exports, "generateKeyPair", GenerateKeyPair); NODE_SET_METHOD(exports, "getSharedSecret", GetSharedSecret); } NODE_MODULE(dhcurve, init) <|endoftext|>
<commit_before>/* * This file is part of Poedit (http://poedit.net) * * Copyright (C) 2000-2014 Vaclav Slavik * * 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 <wx/string.h> #include <wx/config.h> #include <wx/dir.h> #include <wx/ffile.h> #include <wx/filename.h> #include "digger.h" #include "extractor.h" #include "progressinfo.h" #include "gexecute.h" #include "utility.h" namespace { // concatenates catalogs using msgcat bool ConcatCatalogs(const wxArrayString& files, TempDirectory& tmpdir, wxString *outfile) { if (files.empty()) return false; if (files.size() == 1) { *outfile = files.front(); return true; } *outfile = tmpdir.CreateFileName("merged.pot"); wxString list; for ( wxArrayString::const_iterator i = files.begin(); i != files.end(); ++i ) { list += wxString::Format(" %s", QuoteCmdlineArg(*i)); } wxString cmd = wxString::Format("msgcat --force-po -o %s %s", QuoteCmdlineArg(*outfile), list.c_str()); bool succ = ExecuteGettext(cmd); if ( !succ ) { wxLogError(_("Failed command: %s"), cmd.c_str()); wxLogError(_("Failed to merge gettext catalogs.")); return false; } return true; } // Returns true if the filename is in 'paths' prefixes list bool FilenameMatchesPathsList(const wxString& fn, const wxArrayString& paths) { for (auto p: paths) { if (fn == p) return true; if (fn.StartsWith(p + "/")) return true; } return false; } } // anonymous namespace Catalog *SourceDigger::Dig(const wxArrayString& paths, const wxArrayString& excludePaths, const wxArrayString& keywords, const wxString& charset, UpdateResultReason& reason) { ExtractorsDB db; db.Read(wxConfig::Get()); m_progressInfo->UpdateMessage(_("Scanning files...")); wxArrayString *all_files = FindFiles(paths, excludePaths, db); if (all_files == NULL) { reason = UpdateResultReason::NoSourcesFound; return NULL; } TempDirectory tmpdir; wxArrayString partials; for (size_t i = 0; i < db.Data.size(); i++) { if ( all_files[i].empty() ) continue; // no files of this kind m_progressInfo->UpdateMessage( // TRANSLATORS: '%s' is replaced with the kind of the files (e.g. C++, PHP, ...) wxString::Format(_("Parsing %s files..."), db.Data[i].Name.c_str())); if (!DigFiles(tmpdir, partials, all_files[i], db.Data[i], keywords, charset)) { delete[] all_files; return NULL; } } delete[] all_files; wxString mergedFile; if ( !ConcatCatalogs(partials, tmpdir, &mergedFile) ) return NULL; // couldn't parse any source files Catalog *c = new Catalog(mergedFile, Catalog::CreationFlag_IgnoreHeader); if ( !c->IsOk() ) { wxLogError(_("Failed to load extracted catalog.")); delete c; return NULL; } return c; } // cmdline's length is limited by OS/shell, this is maximal number // of files we'll pass to the parser at one run: #define BATCH_SIZE 16 bool SourceDigger::DigFiles(TempDirectory& tmpdir, wxArrayString& outFiles, const wxArrayString& files, Extractor &extract, const wxArrayString& keywords, const wxString& charset) { wxArrayString batchfiles; wxArrayString tempfiles; size_t i, last = 0; while (last < files.GetCount()) { batchfiles.clear(); for (i = last; i < last + BATCH_SIZE && i < files.size(); i++) batchfiles.Add(files[i]); last = i; wxString tempfile = tmpdir.CreateFileName("extracted.pot"); if (!ExecuteGettext( extract.GetCommand(batchfiles, keywords, tempfile, charset))) { return false; } tempfiles.push_back(tempfile); m_progressInfo->UpdateGauge((int)batchfiles.GetCount()); if (m_progressInfo->Cancelled()) return false; } wxString outfile; if ( !ConcatCatalogs(tempfiles, tmpdir, &outfile) ) return false; // failed to parse any source files outFiles.push_back(outfile); return true; } wxArrayString *SourceDigger::FindFiles(const wxArrayString& paths, const wxArrayString& excludePaths, ExtractorsDB& db) { if (db.Data.empty()) return NULL; wxArrayString *p_files = new wxArrayString[db.Data.size()]; wxArrayString files; size_t i; for (i = 0; i < paths.GetCount(); i++) { if ( !FindInDir(paths[i], excludePaths, files) ) { wxLogTrace("poedit", "no files found in '%s'", paths[i]); } } // Sort the filenames in some well-defined order. This is because directory // traversal has, generally speaking, undefined order, and the order differs // between filesystems. Finally, the order is reflected in the created PO // files and it is much better for diffs if it remains consistent. files.Sort(); size_t filescnt = 0; for (i = 0; i < db.Data.size(); i++) { p_files[i] = db.Data[i].SelectParsable(files); filescnt += p_files[i].GetCount(); } m_progressInfo->SetGaugeMax((int)filescnt); if (filescnt == 0) return nullptr; return p_files; } int SourceDigger::FindInDir(const wxString& dirname, const wxArrayString& excludePaths, wxArrayString& files) { if (dirname.empty()) return 0; wxDir dir(dirname); if (!dir.IsOpened()) return 0; bool cont; wxString filename; int found = 0; cont = dir.GetFirst(&filename, wxEmptyString, wxDIR_FILES); while (cont) { const wxString f = (dirname == ".") ? filename : dirname + "/" + filename; cont = dir.GetNext(&filename); if (FilenameMatchesPathsList(f, excludePaths)) continue; files.Add(f); found++; } cont = dir.GetFirst(&filename, wxEmptyString, wxDIR_DIRS); while (cont) { const wxString f = (dirname == ".") ? filename : dirname + "/" + filename; cont = dir.GetNext(&filename); if (FilenameMatchesPathsList(f, excludePaths)) continue; found += FindInDir(f, excludePaths, files); } return found; } <commit_msg>Add support for extracting from individual files<commit_after>/* * This file is part of Poedit (http://poedit.net) * * Copyright (C) 2000-2014 Vaclav Slavik * * 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 <wx/string.h> #include <wx/config.h> #include <wx/dir.h> #include <wx/ffile.h> #include <wx/filename.h> #include "digger.h" #include "extractor.h" #include "progressinfo.h" #include "gexecute.h" #include "utility.h" namespace { // concatenates catalogs using msgcat bool ConcatCatalogs(const wxArrayString& files, TempDirectory& tmpdir, wxString *outfile) { if (files.empty()) return false; if (files.size() == 1) { *outfile = files.front(); return true; } *outfile = tmpdir.CreateFileName("merged.pot"); wxString list; for ( wxArrayString::const_iterator i = files.begin(); i != files.end(); ++i ) { list += wxString::Format(" %s", QuoteCmdlineArg(*i)); } wxString cmd = wxString::Format("msgcat --force-po -o %s %s", QuoteCmdlineArg(*outfile), list.c_str()); bool succ = ExecuteGettext(cmd); if ( !succ ) { wxLogError(_("Failed command: %s"), cmd.c_str()); wxLogError(_("Failed to merge gettext catalogs.")); return false; } return true; } // Returns true if the filename is in 'paths' prefixes list bool FilenameMatchesPathsList(const wxString& fn, const wxArrayString& paths) { for (auto p: paths) { if (fn == p) return true; if (fn.StartsWith(p + "/")) return true; } return false; } } // anonymous namespace Catalog *SourceDigger::Dig(const wxArrayString& paths, const wxArrayString& excludePaths, const wxArrayString& keywords, const wxString& charset, UpdateResultReason& reason) { ExtractorsDB db; db.Read(wxConfig::Get()); m_progressInfo->UpdateMessage(_("Scanning files...")); wxArrayString *all_files = FindFiles(paths, excludePaths, db); if (all_files == NULL) { reason = UpdateResultReason::NoSourcesFound; return NULL; } TempDirectory tmpdir; wxArrayString partials; for (size_t i = 0; i < db.Data.size(); i++) { if ( all_files[i].empty() ) continue; // no files of this kind m_progressInfo->UpdateMessage( // TRANSLATORS: '%s' is replaced with the kind of the files (e.g. C++, PHP, ...) wxString::Format(_("Parsing %s files..."), db.Data[i].Name.c_str())); if (!DigFiles(tmpdir, partials, all_files[i], db.Data[i], keywords, charset)) { delete[] all_files; return NULL; } } delete[] all_files; wxString mergedFile; if ( !ConcatCatalogs(partials, tmpdir, &mergedFile) ) return NULL; // couldn't parse any source files Catalog *c = new Catalog(mergedFile, Catalog::CreationFlag_IgnoreHeader); if ( !c->IsOk() ) { wxLogError(_("Failed to load extracted catalog.")); delete c; return NULL; } return c; } // cmdline's length is limited by OS/shell, this is maximal number // of files we'll pass to the parser at one run: #define BATCH_SIZE 16 bool SourceDigger::DigFiles(TempDirectory& tmpdir, wxArrayString& outFiles, const wxArrayString& files, Extractor &extract, const wxArrayString& keywords, const wxString& charset) { wxArrayString batchfiles; wxArrayString tempfiles; size_t i, last = 0; while (last < files.GetCount()) { batchfiles.clear(); for (i = last; i < last + BATCH_SIZE && i < files.size(); i++) batchfiles.Add(files[i]); last = i; wxString tempfile = tmpdir.CreateFileName("extracted.pot"); if (!ExecuteGettext( extract.GetCommand(batchfiles, keywords, tempfile, charset))) { return false; } tempfiles.push_back(tempfile); m_progressInfo->UpdateGauge((int)batchfiles.GetCount()); if (m_progressInfo->Cancelled()) return false; } wxString outfile; if ( !ConcatCatalogs(tempfiles, tmpdir, &outfile) ) return false; // failed to parse any source files outFiles.push_back(outfile); return true; } wxArrayString *SourceDigger::FindFiles(const wxArrayString& paths, const wxArrayString& excludePaths, ExtractorsDB& db) { if (db.Data.empty()) return NULL; wxArrayString *p_files = new wxArrayString[db.Data.size()]; wxArrayString files; size_t i; for (i = 0; i < paths.GetCount(); i++) { if (wxFileName::FileExists(paths[i])) { if ( FilenameMatchesPathsList(paths[i], excludePaths) ) { wxLogTrace("poedit", "no files found in '%s'", paths[i]); continue; } files.Add(paths[i]); } else if ( !FindInDir(paths[i], excludePaths, files) ) { wxLogTrace("poedit", "no files found in '%s'", paths[i]); } } // Sort the filenames in some well-defined order. This is because directory // traversal has, generally speaking, undefined order, and the order differs // between filesystems. Finally, the order is reflected in the created PO // files and it is much better for diffs if it remains consistent. files.Sort(); size_t filescnt = 0; for (i = 0; i < db.Data.size(); i++) { p_files[i] = db.Data[i].SelectParsable(files); filescnt += p_files[i].GetCount(); } m_progressInfo->SetGaugeMax((int)filescnt); if (filescnt == 0) return nullptr; return p_files; } int SourceDigger::FindInDir(const wxString& dirname, const wxArrayString& excludePaths, wxArrayString& files) { if (dirname.empty()) return 0; wxDir dir(dirname); if (!dir.IsOpened()) return 0; bool cont; wxString filename; int found = 0; cont = dir.GetFirst(&filename, wxEmptyString, wxDIR_FILES); while (cont) { const wxString f = (dirname == ".") ? filename : dirname + "/" + filename; cont = dir.GetNext(&filename); if (FilenameMatchesPathsList(f, excludePaths)) continue; files.Add(f); found++; } cont = dir.GetFirst(&filename, wxEmptyString, wxDIR_DIRS); while (cont) { const wxString f = (dirname == ".") ? filename : dirname + "/" + filename; cont = dir.GetNext(&filename); if (FilenameMatchesPathsList(f, excludePaths)) continue; found += FindInDir(f, excludePaths, files); } return found; } <|endoftext|>
<commit_before>/* * Copyright (C) 2009 Nokia Corporation. * * Contact: Marius Vollmer <marius.vollmer@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include "assoctree.h" #include <QDebug> /// Dumps a QVariant into a multi-line string for debugging purposes. QString AssocTree::dump(int level) const { QString s; for (int i = 0; i < level; i++) s += " "; if (type() == QVariant::String) s += toString() + "\n"; else if (type() == QVariant::List) { s += "[\n"; foreach(QVariant v, toList()) s += AssocTree(v).dump(level + 1); for (int i = 0; i < level; i++) s += " "; s += "]\n"; } return s; } /// Returns the name of this tree. QString AssocTree::name() const { if (type() != QVariant::List) return QString(); if (toList().size() == 0) return QString(); return toList().at(0).toString(); } /// Returns the sub-tree with the given name AssocTree AssocTree::node(const QString &name) const { const QVariant nameVariant(name); // So we can directly compare... if (type() != QVariant::List) return AssocTree(); foreach(const QVariant &child, toList()) { if (child.type() == QVariant::List && child.toList().count() >= 1 && child.toList().at(0) == nameVariant) return AssocTree(child); } return AssocTree(); } AssocTree AssocTree::node(const QString &name1, const QString &name2) const { return node(name1).node(name2); } AssocTree AssocTree::node(const QString &name1, const QString &name2, const QString &name3) const { return node(name1).node(name2).node(name3); } AssocTree AssocTree::node(const QString &name1, const QString &name2, const QString &name3, const QString &name4) const { return node(name1).node(name2).node(name3),node(name4); } AssocTree AssocTree::node(const QString &name1, const QString &name2, const QString &name3, const QString &name4, const QString &name5) const { return node(name1).node(name2).node(name3),node(name4).node(name5); } QVariant AssocTree::value() const { if (type() != QVariant::List) return QVariant(); if (toList().size() < 2) return QVariant(); return toList().at(1); } QVariant AssocTree::value(const QString &name1) const { return node(name1).value(); } QVariant AssocTree::value(const QString &name1, const QString &name2) const { return node(name1, name2).value(); } QVariant AssocTree::value(const QString &name1, const QString &name2, const QString &name3) const { return node(name1, name2, name3).value(); } QVariant AssocTree::value(const QString &name1, const QString &name2, const QString &name3, const QString &name4) const { return node(name1, name2, name3, name4).value(); } QVariant AssocTree::value(const QString &name1, const QString &name2, const QString &name3, const QString &name4, const QString &name5) const { return node(name1, name2, name3, name4, name5).value(); } const QVariantList AssocTree::nodes() const { if (type() == QVariant::List) return toList().mid(1); else return QVariantList(); } <commit_msg>Fix AssocTree::name() to deal with trees that are just strings.<commit_after>/* * Copyright (C) 2009 Nokia Corporation. * * Contact: Marius Vollmer <marius.vollmer@nokia.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include "assoctree.h" #include <QDebug> /// Dumps a QVariant into a multi-line string for debugging purposes. QString AssocTree::dump(int level) const { QString s; for (int i = 0; i < level; i++) s += " "; if (type() == QVariant::String) s += toString() + "\n"; else if (type() == QVariant::List) { s += "[\n"; foreach(QVariant v, toList()) s += AssocTree(v).dump(level + 1); for (int i = 0; i < level; i++) s += " "; s += "]\n"; } return s; } /// Returns the name of this tree. QString AssocTree::name() const { if (type() == QVariant::String) return toString(); if (type() != QVariant::List || toList().size() < 1) return QString(); return toList().at(0).toString(); } /// Returns the sub-tree with the given name AssocTree AssocTree::node(const QString &name) const { const QVariant nameVariant(name); // So we can directly compare... if (type() != QVariant::List) return AssocTree(); foreach(const QVariant &child, toList()) { if (child.type() == QVariant::List && child.toList().count() >= 1 && child.toList().at(0) == nameVariant) return AssocTree(child); } return AssocTree(); } AssocTree AssocTree::node(const QString &name1, const QString &name2) const { return node(name1).node(name2); } AssocTree AssocTree::node(const QString &name1, const QString &name2, const QString &name3) const { return node(name1).node(name2).node(name3); } AssocTree AssocTree::node(const QString &name1, const QString &name2, const QString &name3, const QString &name4) const { return node(name1).node(name2).node(name3),node(name4); } AssocTree AssocTree::node(const QString &name1, const QString &name2, const QString &name3, const QString &name4, const QString &name5) const { return node(name1).node(name2).node(name3),node(name4).node(name5); } QVariant AssocTree::value() const { if (type() != QVariant::List) return QVariant(); if (toList().size() < 2) return QVariant(); return toList().at(1); } QVariant AssocTree::value(const QString &name1) const { return node(name1).value(); } QVariant AssocTree::value(const QString &name1, const QString &name2) const { return node(name1, name2).value(); } QVariant AssocTree::value(const QString &name1, const QString &name2, const QString &name3) const { return node(name1, name2, name3).value(); } QVariant AssocTree::value(const QString &name1, const QString &name2, const QString &name3, const QString &name4) const { return node(name1, name2, name3, name4).value(); } QVariant AssocTree::value(const QString &name1, const QString &name2, const QString &name3, const QString &name4, const QString &name5) const { return node(name1, name2, name3, name4, name5).value(); } const QVariantList AssocTree::nodes() const { if (type() == QVariant::List) return toList().mid(1); else return QVariantList(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2012-2014 Yule Fox. All rights reserved. * http://www.yulefox.com/ */ #include <elf/db.h> #include <elf/log.h> #include <elf/memory.h> #include <elf/pc.h> #include <elf/thread.h> #include <elf/time.h> #include <deque> #include <map> #include <string> using namespace google::protobuf; namespace elf { enum query_type { QUERY_NO_RES, // no response QUERY_RAW, // response with raw result QUERY_FIELD, // response with PB field result QUERY_PB, // response with PB result }; struct query_t { query_type type; // type std::string cmd; // command oid_t oid; // associated object id MYSQL_RES *data; // query result pb_t *pb; // store query data std::string field; // pb field db_callback proc; // callback function elf::time64_t stamp; // request time stamp }; static MYSQL *s_mysql = NULL; static thread_t s_tid_req = 0; static xqueue<query_t *> s_queue_req; static xqueue<query_t *> s_queue_res; static void *handle(void *args); static void query(query_t *q); static void destroy(query_t *q); static void response(query_t *q); static void retrieve_pb(query_t *q); static void retrieve_field(query_t *q); static void *handle(void *args) { while (true) { query_t *q; s_queue_req.pop(q); query(q); } return NULL; } static void query(query_t *q) { try { assert(q); elf::time64_t ct = time_ms(); elf::time64_t delta = time_diff(ct, q->stamp); static elf::time64_t leap = 5000; // 5s static elf::time64_t times = 1; if (delta > leap * times) { LOG_WARN("db", "%d.%03ds: %s.", delta / 1000, delta % 1000, q->cmd.c_str()); ++times; } else if (delta < leap) { times = 1; } // query int status = mysql_query(s_mysql, q->cmd.c_str()); if (status != 0) { LOG_ERROR("db", "`%s` failed: %s.", q->cmd.c_str(), mysql_error(s_mysql)); destroy(q); return; } if (q->type == QUERY_NO_RES) { destroy(q); return; } q->data = mysql_store_result(s_mysql); if (q->data != NULL) { s_queue_res.push(q); } while (!mysql_next_result(s_mysql)) { MYSQL_RES *res = mysql_store_result(s_mysql); if (res) { mysql_free_result(res); } } } catch(...) { LOG_ERROR("db", "`%s` failed: %s.", q->cmd.c_str(), mysql_error(s_mysql)); } } static void destroy(query_t *q) { assert(q); if (q->data) { mysql_free_result(q->data); } E_DELETE(q->pb); E_DELETE(q); } static void retrieve_pb(query_t *q) { assert(q && q->data && q->pb); const Descriptor *des = q->pb->GetDescriptor(); const int field_num = mysql_num_fields(q->data); const MYSQL_ROW row = mysql_fetch_row(q->data); for (int c = 0; c < field_num; ++c) { const MYSQL_FIELD *ifd = mysql_fetch_field_direct(q->data, c); const FieldDescriptor *ofd = des->FindFieldByName(ifd->name); assert(ofd); if (row[c] == NULL || (strlen(row[c]) == 0)) { pb_set_field(q->pb, ofd, ""); } else { pb_set_field(q->pb, ofd, row[c]); } } } static void retrieve_field(query_t *q) { assert(q && q->data && q->pb); const Reflection *ref = q->pb->GetReflection(); const Descriptor *des = q->pb->GetDescriptor(); const FieldDescriptor *ctn = des->FindFieldByName(q->field); const int row_num = mysql_num_rows(q->data); const int field_num = mysql_num_fields(q->data); assert(ctn); for (int r = 0; r < row_num; ++r) { pb_t *item = ref->AddMessage(q->pb, ctn); const MYSQL_ROW row = mysql_fetch_row(q->data); des = item->GetDescriptor(); for (int c = 0; c < field_num; ++c) { const MYSQL_FIELD *ifd = mysql_fetch_field_direct(q->data, c); const FieldDescriptor *ofd = des->FindFieldByName(ifd->name); assert(ofd); if (row[c] == NULL || (strlen(row[c]) == 0)) { pb_set_field(item, ofd, ""); } else { pb_set_field(item, ofd, row[c]); } } } } int db_init(void) { MODULE_IMPORT_SWITCH; return ELF_RC_DB_OK; } int db_fini(void) { MODULE_IMPORT_SWITCH; thread_fini(s_tid_req); return ELF_RC_DB_OK; } int db_connect(const std::string &host, const std::string &user, const std::string &passwd, const std::string &db, unsigned int port) { try { char value = 1; if (s_mysql && 0 == mysql_ping(s_mysql)) { return ELF_RC_DB_OK; } s_mysql = mysql_init(NULL); mysql_options(s_mysql, MYSQL_OPT_RECONNECT, (char *)&value); mysql_options(s_mysql, MYSQL_SET_CHARSET_NAME, "utf8"); s_mysql = mysql_real_connect(s_mysql, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, NULL, CLIENT_MULTI_STATEMENTS); if (!s_mysql) { LOG_ERROR("db", "Connect DB failed: %s.", mysql_error(s_mysql)); return ELF_RC_DB_INIT_FAILED; } } catch(...) { LOG_ERROR("db", "Connect DB failed: %s.", mysql_error(s_mysql)); return ELF_RC_DB_INIT_FAILED; } s_tid_req = thread_init(handle, NULL); return ELF_RC_DB_OK; } int db_proc(void) { if (s_mysql == NULL) return -1; std::deque<query_t *> list; std::deque<query_t *>::iterator itr; s_queue_res.swap(list); for (itr = list.begin(); itr != list.end(); ++itr) { query_t *q = *itr; // object has not been destroyed response(q); } return 0; } void db_req(const char *cmd, db_callback proc, oid_t oid, pb_t *out, const std::string &field) { query_t *q = E_NEW query_t; if (proc == NULL) { q->type = QUERY_NO_RES; } else if (out == NULL) { q->type = QUERY_RAW; } else if (field == "") { q->type = QUERY_PB; } else { q->type = QUERY_FIELD; } q->cmd = cmd; q->stamp = time_ms(); q->oid = oid; q->pb = out; q->field = field; q->proc = proc; q->data = NULL; s_queue_req.push(q); } void response(query_t *q) { assert(q); switch (q->type) { case QUERY_RAW: q->proc(q->oid, q->data); break; case QUERY_PB: retrieve_pb(q); q->proc(q->oid, q->pb); break; case QUERY_FIELD: retrieve_field(q); q->proc(q->oid, q->pb); break; default: assert(0); break; } destroy(q); } db_rc db_query(const char *cmd) { assert(s_mysql); try { // query int status = mysql_query(s_mysql, cmd); if (status != 0) { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } do { MYSQL_RES *res = mysql_store_result(s_mysql); if (res) { mysql_free_result(res); } } while (!mysql_next_result(s_mysql)); return ELF_RC_DB_OK; } catch(...) { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } return ELF_RC_DB_OK; } db_rc db_query(const char *cmd, pb_t *out) { assert(s_mysql && out); LOG_TRACE("db", "Query DB: %s.", cmd); try { // query int status = mysql_query(s_mysql, cmd); if (status != 0) { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } MYSQL_RES *res = mysql_store_result(s_mysql); if (res) { const int row_num = mysql_num_rows(res); const Descriptor *des = out->GetDescriptor(); const int field_num = mysql_num_fields(res); const MYSQL_ROW row = mysql_fetch_row(res); for (int c = 0; row_num > 0 && c < field_num; ++c) { const MYSQL_FIELD *ifd = mysql_fetch_field_direct(res, c); const FieldDescriptor *ofd = des->FindFieldByName(ifd->name); assert(ofd); if (row[c] == NULL || (strlen(row[c]) == 0)) { pb_set_field(out, ofd, ""); } else { pb_set_field(out, ofd, row[c]); } } while (!mysql_next_result(s_mysql)) { MYSQL_RES *res = mysql_store_result(s_mysql); if (res) { mysql_free_result(res); } } return ELF_RC_DB_OK; } else if (mysql_field_count(s_mysql) == 0) { return ELF_RC_DB_OK; } else { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } } catch(...) { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } return ELF_RC_DB_OK; } db_rc db_query(const char *cmd, pb_t *out, const std::string &field) { assert(s_mysql && out); LOG_TRACE("db", "Query DB: %s.", cmd); try { // query int status = mysql_query(s_mysql, cmd); if (status != 0) { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } MYSQL_RES *res = mysql_store_result(s_mysql); if (res) { const int row_num = mysql_num_rows(res); const Reflection *ref = out->GetReflection(); const Descriptor *des = out->GetDescriptor(); const FieldDescriptor *ctn = des->FindFieldByName(field); const int field_num = mysql_num_fields(res); assert(ctn); for (int r = 0; r < row_num; ++r) { pb_t *item = ref->AddMessage(out, ctn); const MYSQL_ROW row = mysql_fetch_row(res); des = item->GetDescriptor(); for (int c = 0; c < field_num; ++c) { const MYSQL_FIELD *ifd = mysql_fetch_field_direct(res, c); const FieldDescriptor *ofd = des->FindFieldByName(ifd->name); assert(ofd); if (row[c] == NULL || (strlen(row[c]) == 0)) { pb_set_field(item, ofd, ""); } else { pb_set_field(item, ofd, row[c]); } } } mysql_free_result(res); while (!mysql_next_result(s_mysql)) { MYSQL_RES *res = mysql_store_result(s_mysql); if (res) { mysql_free_result(res); } } return ELF_RC_DB_OK; } else if (mysql_field_count(s_mysql) == 0) { return ELF_RC_DB_OK; } else { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } } catch(...) { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } return ELF_RC_DB_OK; } } // namespace elf <commit_msg>[FIX] db results.<commit_after>/* * Copyright (C) 2012-2014 Yule Fox. All rights reserved. * http://www.yulefox.com/ */ #include <elf/db.h> #include <elf/log.h> #include <elf/memory.h> #include <elf/pc.h> #include <elf/thread.h> #include <elf/time.h> #include <deque> #include <map> #include <string> using namespace google::protobuf; namespace elf { enum query_type { QUERY_NO_RES, // no response QUERY_RAW, // response with raw result QUERY_FIELD, // response with PB field result QUERY_PB, // response with PB result }; struct query_t { query_type type; // type std::string cmd; // command oid_t oid; // associated object id MYSQL_RES *data; // query result pb_t *pb; // store query data std::string field; // pb field db_callback proc; // callback function elf::time64_t stamp; // request time stamp }; static MYSQL *s_mysql = NULL; static thread_t s_tid_req = 0; static xqueue<query_t *> s_queue_req; static xqueue<query_t *> s_queue_res; static void *handle(void *args); static void query(query_t *q); static void destroy(query_t *q); static void response(query_t *q); static void retrieve_pb(query_t *q); static void retrieve_field(query_t *q); static void *handle(void *args) { while (true) { query_t *q; s_queue_req.pop(q); query(q); } return NULL; } static void query(query_t *q) { try { assert(q); elf::time64_t ct = time_ms(); elf::time64_t delta = time_diff(ct, q->stamp); static elf::time64_t leap = 5000; // 5s static elf::time64_t times = 1; if (delta > leap * times) { LOG_WARN("db", "%d.%03ds: %s.", delta / 1000, delta % 1000, q->cmd.c_str()); ++times; } else if (delta < leap) { times = 1; } // query int status = mysql_query(s_mysql, q->cmd.c_str()); if (status != 0) { LOG_ERROR("db", "`%s` failed: %s.", q->cmd.c_str(), mysql_error(s_mysql)); destroy(q); return; } if (q->type == QUERY_NO_RES) { destroy(q); return; } q->data = NULL; do { MYSQL_RES *res = mysql_store_result(s_mysql); if (res) { if (q->data == NULL) { q->data = res; s_queue_res.push(q); } else { mysql_free_result(res); } } } while (!mysql_next_result(s_mysql)); } catch(...) { LOG_ERROR("db", "`%s` failed: %s.", q->cmd.c_str(), mysql_error(s_mysql)); } } static void destroy(query_t *q) { assert(q); if (q->data) { mysql_free_result(q->data); } E_DELETE(q->pb); E_DELETE(q); } static void retrieve_pb(query_t *q) { assert(q && q->data && q->pb); const Descriptor *des = q->pb->GetDescriptor(); const int field_num = mysql_num_fields(q->data); const MYSQL_ROW row = mysql_fetch_row(q->data); for (int c = 0; c < field_num; ++c) { const MYSQL_FIELD *ifd = mysql_fetch_field_direct(q->data, c); const FieldDescriptor *ofd = des->FindFieldByName(ifd->name); assert(ofd); if (row[c] == NULL || (strlen(row[c]) == 0)) { pb_set_field(q->pb, ofd, ""); } else { pb_set_field(q->pb, ofd, row[c]); } } } static void retrieve_field(query_t *q) { assert(q && q->data && q->pb); const Reflection *ref = q->pb->GetReflection(); const Descriptor *des = q->pb->GetDescriptor(); const FieldDescriptor *ctn = des->FindFieldByName(q->field); const int row_num = mysql_num_rows(q->data); const int field_num = mysql_num_fields(q->data); assert(ctn); for (int r = 0; r < row_num; ++r) { pb_t *item = ref->AddMessage(q->pb, ctn); const MYSQL_ROW row = mysql_fetch_row(q->data); des = item->GetDescriptor(); for (int c = 0; c < field_num; ++c) { const MYSQL_FIELD *ifd = mysql_fetch_field_direct(q->data, c); const FieldDescriptor *ofd = des->FindFieldByName(ifd->name); assert(ofd); if (row[c] == NULL || (strlen(row[c]) == 0)) { pb_set_field(item, ofd, ""); } else { pb_set_field(item, ofd, row[c]); } } } } int db_init(void) { MODULE_IMPORT_SWITCH; return ELF_RC_DB_OK; } int db_fini(void) { MODULE_IMPORT_SWITCH; thread_fini(s_tid_req); return ELF_RC_DB_OK; } int db_connect(const std::string &host, const std::string &user, const std::string &passwd, const std::string &db, unsigned int port) { try { char value = 1; if (s_mysql && 0 == mysql_ping(s_mysql)) { return ELF_RC_DB_OK; } s_mysql = mysql_init(NULL); mysql_options(s_mysql, MYSQL_OPT_RECONNECT, (char *)&value); mysql_options(s_mysql, MYSQL_SET_CHARSET_NAME, "utf8"); s_mysql = mysql_real_connect(s_mysql, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, NULL, CLIENT_MULTI_STATEMENTS); if (!s_mysql) { LOG_ERROR("db", "Connect DB failed: %s.", mysql_error(s_mysql)); return ELF_RC_DB_INIT_FAILED; } } catch(...) { LOG_ERROR("db", "Connect DB failed: %s.", mysql_error(s_mysql)); return ELF_RC_DB_INIT_FAILED; } s_tid_req = thread_init(handle, NULL); return ELF_RC_DB_OK; } int db_proc(void) { if (s_mysql == NULL) return -1; std::deque<query_t *> list; std::deque<query_t *>::iterator itr; s_queue_res.swap(list); for (itr = list.begin(); itr != list.end(); ++itr) { query_t *q = *itr; // object has not been destroyed response(q); } return 0; } void db_req(const char *cmd, db_callback proc, oid_t oid, pb_t *out, const std::string &field) { query_t *q = E_NEW query_t; if (proc == NULL) { q->type = QUERY_NO_RES; } else if (out == NULL) { q->type = QUERY_RAW; } else if (field == "") { q->type = QUERY_PB; } else { q->type = QUERY_FIELD; } q->cmd = cmd; q->stamp = time_ms(); q->oid = oid; q->pb = out; q->field = field; q->proc = proc; q->data = NULL; s_queue_req.push(q); } void response(query_t *q) { assert(q); switch (q->type) { case QUERY_RAW: q->proc(q->oid, q->data); break; case QUERY_PB: retrieve_pb(q); q->proc(q->oid, q->pb); break; case QUERY_FIELD: retrieve_field(q); q->proc(q->oid, q->pb); break; default: assert(0); break; } destroy(q); } db_rc db_query(const char *cmd) { assert(s_mysql); try { // query int status = mysql_query(s_mysql, cmd); if (status != 0) { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } do { MYSQL_RES *res = mysql_store_result(s_mysql); if (res) { mysql_free_result(res); } } while (!mysql_next_result(s_mysql)); return ELF_RC_DB_OK; } catch(...) { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } return ELF_RC_DB_OK; } db_rc db_query(const char *cmd, pb_t *out) { assert(s_mysql && out); LOG_TRACE("db", "Query DB: %s.", cmd); try { // query int status = mysql_query(s_mysql, cmd); if (status != 0) { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } MYSQL_RES *res = mysql_store_result(s_mysql); if (res) { const int row_num = mysql_num_rows(res); const Descriptor *des = out->GetDescriptor(); const int field_num = mysql_num_fields(res); const MYSQL_ROW row = mysql_fetch_row(res); for (int c = 0; row_num > 0 && c < field_num; ++c) { const MYSQL_FIELD *ifd = mysql_fetch_field_direct(res, c); const FieldDescriptor *ofd = des->FindFieldByName(ifd->name); assert(ofd); if (row[c] == NULL || (strlen(row[c]) == 0)) { pb_set_field(out, ofd, ""); } else { pb_set_field(out, ofd, row[c]); } } while (!mysql_next_result(s_mysql)) { MYSQL_RES *res = mysql_store_result(s_mysql); if (res) { mysql_free_result(res); } } return ELF_RC_DB_OK; } else if (mysql_field_count(s_mysql) == 0) { return ELF_RC_DB_OK; } else { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } } catch(...) { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } return ELF_RC_DB_OK; } db_rc db_query(const char *cmd, pb_t *out, const std::string &field) { assert(s_mysql && out); LOG_TRACE("db", "Query DB: %s.", cmd); try { // query int status = mysql_query(s_mysql, cmd); if (status != 0) { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } MYSQL_RES *res = mysql_store_result(s_mysql); if (res) { const int row_num = mysql_num_rows(res); const Reflection *ref = out->GetReflection(); const Descriptor *des = out->GetDescriptor(); const FieldDescriptor *ctn = des->FindFieldByName(field); const int field_num = mysql_num_fields(res); assert(ctn); for (int r = 0; r < row_num; ++r) { pb_t *item = ref->AddMessage(out, ctn); const MYSQL_ROW row = mysql_fetch_row(res); des = item->GetDescriptor(); for (int c = 0; c < field_num; ++c) { const MYSQL_FIELD *ifd = mysql_fetch_field_direct(res, c); const FieldDescriptor *ofd = des->FindFieldByName(ifd->name); assert(ofd); if (row[c] == NULL || (strlen(row[c]) == 0)) { pb_set_field(item, ofd, ""); } else { pb_set_field(item, ofd, row[c]); } } } mysql_free_result(res); while (!mysql_next_result(s_mysql)) { MYSQL_RES *res = mysql_store_result(s_mysql); if (res) { mysql_free_result(res); } } return ELF_RC_DB_OK; } else if (mysql_field_count(s_mysql) == 0) { return ELF_RC_DB_OK; } else { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } } catch(...) { LOG_ERROR("db", "`%s` failed: %s.", cmd, mysql_error(s_mysql)); return ELF_RC_DB_EXECUTE_FAILED; } return ELF_RC_DB_OK; } } // namespace elf <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // File: $Source: /usr/sci/projects/Nektar/cvs/Nektar++/library/SpatialDomains/MeshGraph1D.cpp,v $ // // For more information, please see: http://www.nektar.info/ // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // Description: // // //////////////////////////////////////////////////////////////////////////////// #include "pchSpatialDomains.h" #include <SpatialDomains/MeshGraph1D.h> #include <SpatialDomains/ParseUtils.hpp> namespace Nektar { namespace SpatialDomains { MeshGraph1D::MeshGraph1D() { } MeshGraph1D::~MeshGraph1D() { } // \brief Read segments (and general MeshGraph) given filename. void MeshGraph1D::Read(std::string &infilename) { SetFileName(infilename); TiXmlDocument doc(infilename); bool loadOkay = doc.LoadFile(); ASSERTL0(loadOkay, (std::string("Unable to load file:") + infilename + ".").c_str()); Read(doc); } // \brief Read segments (and general MeshGraph) given TiXmlDocument. void MeshGraph1D::Read(TiXmlDocument &doc) { // Read mesh first MeshGraph::Read(doc); TiXmlHandle docHandle(&doc); TiXmlNode* node = NULL; TiXmlElement* mesh = NULL; /// Look for all geometry related data in GEOMETRY block. mesh = docHandle.FirstChildElement("NEKTAR").FirstChildElement("GEOMETRY").Element(); ASSERTL0(mesh, "Unable to find GEOMETRY tag in file."); ReadElements(doc); ReadComposites(doc); ReadDomain(doc); } void MeshGraph1D::ReadElements(TiXmlDocument &doc) { /// We know we have it since we made it this far. TiXmlHandle docHandle(&doc); TiXmlElement* mesh = docHandle.FirstChildElement("NEKTAR").FirstChildElement("GEOMETRY").Element(); TiXmlElement* field = NULL; /// Look for elements in ELEMENT block. field = mesh->FirstChildElement("ELEMENT"); ASSERTL0(field, "Unable to find ELEMENT tag in file."); int nextElementNumber = -1; /// All elements are of the form: "<S ID = n> ... </S>", with /// ? being the element type. TiXmlElement *segment = field->FirstChildElement("S"); while (segment) { nextElementNumber++; int indx; int err = segment->QueryIntAttribute("ID", &indx); ASSERTL0(err == TIXML_SUCCESS, "Unable to read element attribute ID."); ASSERTL0(indx == nextElementNumber, "Element IDs must begin with zero and be sequential."); TiXmlNode* elementChild = segment->FirstChild(); while(elementChild && elementChild->Type() != TiXmlNode::TEXT) { elementChild = elementChild->NextSibling(); } ASSERTL0(elementChild, "Unable to read element description body."); std::string elementStr = elementChild->ToText()->ValueStr(); /// Parse out the element components corresponding to type of element. /// Read two vertex numbers int vertex1, vertex2; std::istrstream elementDataStrm(elementStr.c_str()); try { elementDataStrm >> vertex1; elementDataStrm >> vertex2; ASSERTL0(!elementDataStrm.fail(), (std::string("Unable to read element data for SEGMENT: ") + elementStr).c_str()); SegGeomSharedPtr seg = MemoryManager<SegGeom>::AllocateSharedPtr(indx, GetVertex(vertex1), GetVertex(vertex2)); m_seggeoms.push_back(seg); } catch(...) { NEKERROR(ErrorUtil::efatal, (std::string("Unable to read element data for segment: ") + elementStr).c_str()); } /// Keep looking for additional segments segment = segment->NextSiblingElement("S"); } ASSERTL0(nextElementNumber >= 0, "At least one element must be specified."); } void MeshGraph1D::ReadComposites(TiXmlDocument &doc) { TiXmlHandle docHandle(&doc); /// We know we have it since we made it this far. TiXmlElement* mesh = docHandle.FirstChildElement("NEKTAR").FirstChildElement("GEOMETRY").Element(); TiXmlElement* field = NULL; ASSERTL0(mesh, "Unable to find GEOMETRY tag in file."); /// Look for elements in ELEMENT block. field = mesh->FirstChildElement("COMPOSITE"); ASSERTL0(field, "Unable to find COMPOSITE tag in file."); TiXmlElement *node = field->FirstChildElement("C"); // Sequential counter for the composite numbers. int nextCompositeNumber = -1; while (node) { /// All elements are of the form: "<? ID="#"> ... </?>", with /// ? being the element type. nextCompositeNumber++; int indx; int err = node->QueryIntAttribute("ID", &indx); ASSERTL0(err == TIXML_SUCCESS, "Unable to read attribute ID."); ASSERTL0(indx == nextCompositeNumber, "Composite IDs must begin with zero and be sequential."); TiXmlNode* compositeChild = node->FirstChild(); // This is primarily to skip comments that may be present. // Comments appear as nodes just like elements. // We are specifically looking for text in the body // of the definition. while(compositeChild && compositeChild->Type() != TiXmlNode::TEXT) { compositeChild = compositeChild->NextSibling(); } ASSERTL0(compositeChild, "Unable to read composite definition body."); std::string compositeStr = compositeChild->ToText()->ValueStr(); /// Parse out the element components corresponding to type of element. std::istrstream compositeDataStrm(compositeStr.c_str()); try { bool first = true; std::string prevCompositeElementStr; while (!compositeDataStrm.fail()) { std::string compositeElementStr; compositeDataStrm >> compositeElementStr; if (!compositeDataStrm.fail()) { if (first) { first = false; Composite curVector = MemoryManager<std::vector<GeometrySharedPtr> >::AllocateSharedPtr(); m_MeshCompositeVector.push_back(curVector); } if (compositeElementStr.length() > 0) { ResolveGeomRef(prevCompositeElementStr, compositeElementStr); } prevCompositeElementStr = compositeElementStr; } } } catch(...) { NEKERROR(ErrorUtil::efatal, (std::string("Unable to read COMPOSITE data for composite: ") + compositeStr).c_str()); } /// Keep looking for additional composite definitions. node = node->NextSiblingElement("C"); } ASSERTL0(nextCompositeNumber >= 0, "At least one composite must be specified."); } // Take the string that is the composite reference and find the // pointer to the Geometry object corresponding to it. // Only allow segments to be grouped for 1D mesh. void MeshGraph1D::ResolveGeomRef(const std::string &prevToken, const std::string &token) { try { std::istringstream tokenStream(token); std::istringstream prevTokenStream(prevToken); char type; char prevType; tokenStream >> type; std::string::size_type indxBeg = token.find_first_of('[') + 1; std::string::size_type indxEnd = token.find_last_of(']') - 1; ASSERTL0(indxBeg <= indxEnd, (std::string("Error reading index definition:") + token).c_str()); std::string indxStr = token.substr(indxBeg, indxEnd - indxBeg + 1); typedef vector<unsigned int> SeqVectorType; SeqVectorType seqVector; if (!ParseUtils::GenerateSeqVector(indxStr.c_str(), seqVector)) { NEKERROR(ErrorUtil::efatal, (std::string("Ill-formed sequence definition: ") + indxStr).c_str()); } prevTokenStream >> prevType; // All composites must be of the same dimension. bool validSequence = (prevToken.empty() || // No previous, then current is just fine. (type == 'V' && prevType == 'V') || (type == 'S' && prevType == 'S')); ASSERTL0(validSequence, (std::string("Invalid combination of composite items: ") + type + " and " + prevType + ".").c_str()); switch(type) { case 'V': // Vertex for (SeqVectorType::iterator iter=seqVector.begin(); iter!=seqVector.end(); ++iter) { if (*iter >= m_vertset.size()) { char errStr[16] = ""; ::sprintf(errStr, "%d", *iter); NEKERROR(ErrorUtil::ewarning, (std::string("Unknown vertex index: ") + errStr).c_str()); } else { m_MeshCompositeVector.back()->push_back(m_vertset[*iter]); } } break; case 'S': // Segment for (SeqVectorType::iterator iter=seqVector.begin(); iter!=seqVector.end(); ++iter) { if (*iter >= m_seggeoms.size()) { char errStr[16] = ""; ::sprintf(errStr, "%d", *iter); NEKERROR(ErrorUtil::ewarning, (std::string("Unknown segment index: ") + errStr).c_str()); } else { m_MeshCompositeVector.back()->push_back(m_seggeoms[*iter]); } } break; default: NEKERROR(ErrorUtil::efatal, (std::string("Unrecognized composite token: ") + token).c_str()); } } catch(...) { NEKERROR(ErrorUtil::efatal, (std::string("Problem processing composite token: ") + token).c_str()); } return; } void MeshGraph1D::Write(std::string &outfilename) { } }; //end of namespace }; //end of namespace // // $Log: MeshGraph1D.cpp,v $ // Revision 1.13 2007/07/24 16:52:09 jfrazier // Added domain code. // // Revision 1.12 2007/07/23 16:54:30 jfrazier // Change a dynamic allocation using new to memory manager allocate. // // Revision 1.11 2007/07/05 04:21:10 jfrazier // Changed id format and propagated from 1d to 2d. // // Revision 1.10 2007/06/10 02:27:10 jfrazier // Another checkin with an incremental completion of the boundary conditions reader. // // Revision 1.9 2007/06/07 23:55:24 jfrazier // Intermediate revisions to add parsing for boundary conditions file. // // Revision 1.8 2007/03/14 21:24:08 sherwin // Update for working version of MultiRegions up to ExpList1D // // Revision 1.7 2006/10/15 06:18:58 sherwin // Moved NekPoint out of namespace LibUtilities // // Revision 1.6 2006/09/26 23:41:53 jfrazier // Updated to account for highest level NEKTAR tag and changed the geometry tag to GEOMETRY. // // Revision 1.5 2006/06/01 14:15:30 sherwin // Added typdef of boost wrappers and made GeoFac a boost shared pointer. // // Revision 1.4 2006/05/23 19:56:33 jfrazier // These build and run, but the expansion pieces are commented out // because they would not run. // // Revision 1.3 2006/05/16 22:28:31 sherwin // Updates to add in FaceComponent call to constructors // // Revision 1.2 2006/05/16 20:12:59 jfrazier // Minor fixes to correct bugs. // // Revision 1.1 2006/05/04 18:59:01 kirby // *** empty log message *** // // Revision 1.17 2006/04/09 02:08:35 jfrazier // Added precompiled header. // // Revision 1.16 2006/04/04 23:12:37 jfrazier // More updates to readers. Still work to do on MeshGraph2D to store tris and quads. // // Revision 1.15 2006/03/25 00:58:29 jfrazier // Many changes dealing with fundamental structure and reading/writing. // // Revision 1.14 2006/03/12 14:20:43 sherwin // // First compiling version of SpatialDomains and associated modifications // // Revision 1.13 2006/03/12 07:42:03 sherwin // // Updated member names and StdRegions call. Still has not been compiled // // Revision 1.12 2006/02/26 21:19:43 bnelson // Fixed a variety of compiler errors caused by updates to the coding standard. // // Revision 1.11 2006/02/19 01:37:33 jfrazier // Initial attempt at bringing into conformance with the coding standard. Still more work to be done. Has not been compiled. // // <commit_msg>Fixed for new MemoryManager call<commit_after>//////////////////////////////////////////////////////////////////////////////// // // File: $Source: /usr/sci/projects/Nektar/cvs/Nektar++/library/SpatialDomains/MeshGraph1D.cpp,v $ // // For more information, please see: http://www.nektar.info/ // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // Description: // // //////////////////////////////////////////////////////////////////////////////// #include "pchSpatialDomains.h" #include <SpatialDomains/MeshGraph1D.h> #include <SpatialDomains/ParseUtils.hpp> namespace Nektar { namespace SpatialDomains { MeshGraph1D::MeshGraph1D() { } MeshGraph1D::~MeshGraph1D() { } // \brief Read segments (and general MeshGraph) given filename. void MeshGraph1D::Read(std::string &infilename) { SetFileName(infilename); TiXmlDocument doc(infilename); bool loadOkay = doc.LoadFile(); ASSERTL0(loadOkay, (std::string("Unable to load file:") + infilename + ".").c_str()); Read(doc); } // \brief Read segments (and general MeshGraph) given TiXmlDocument. void MeshGraph1D::Read(TiXmlDocument &doc) { // Read mesh first MeshGraph::Read(doc); TiXmlHandle docHandle(&doc); TiXmlNode* node = NULL; TiXmlElement* mesh = NULL; /// Look for all geometry related data in GEOMETRY block. mesh = docHandle.FirstChildElement("NEKTAR").FirstChildElement("GEOMETRY").Element(); ASSERTL0(mesh, "Unable to find GEOMETRY tag in file."); ReadElements(doc); ReadComposites(doc); ReadDomain(doc); } void MeshGraph1D::ReadElements(TiXmlDocument &doc) { /// We know we have it since we made it this far. TiXmlHandle docHandle(&doc); TiXmlElement* mesh = docHandle.FirstChildElement("NEKTAR").FirstChildElement("GEOMETRY").Element(); TiXmlElement* field = NULL; /// Look for elements in ELEMENT block. field = mesh->FirstChildElement("ELEMENT"); ASSERTL0(field, "Unable to find ELEMENT tag in file."); int nextElementNumber = -1; /// All elements are of the form: "<S ID = n> ... </S>", with /// ? being the element type. TiXmlElement *segment = field->FirstChildElement("S"); while (segment) { nextElementNumber++; int indx; int err = segment->QueryIntAttribute("ID", &indx); ASSERTL0(err == TIXML_SUCCESS, "Unable to read element attribute ID."); ASSERTL0(indx == nextElementNumber, "Element IDs must begin with zero and be sequential."); TiXmlNode* elementChild = segment->FirstChild(); while(elementChild && elementChild->Type() != TiXmlNode::TEXT) { elementChild = elementChild->NextSibling(); } ASSERTL0(elementChild, "Unable to read element description body."); std::string elementStr = elementChild->ToText()->ValueStr(); /// Parse out the element components corresponding to type of element. /// Read two vertex numbers int vertex1, vertex2; std::istrstream elementDataStrm(elementStr.c_str()); try { elementDataStrm >> vertex1; elementDataStrm >> vertex2; ASSERTL0(!elementDataStrm.fail(), (std::string("Unable to read element data for SEGMENT: ") + elementStr).c_str()); VertexComponentSharedPtr v1 = GetVertex(vertex1); VertexComponentSharedPtr v2 = GetVertex(vertex2); SegGeomSharedPtr seg = MemoryManager<SegGeom>::AllocateSharedPtr(indx, v1,v2); m_seggeoms.push_back(seg); } catch(...) { NEKERROR(ErrorUtil::efatal, (std::string("Unable to read element data for segment: ") + elementStr).c_str()); } /// Keep looking for additional segments segment = segment->NextSiblingElement("S"); } ASSERTL0(nextElementNumber >= 0, "At least one element must be specified."); } void MeshGraph1D::ReadComposites(TiXmlDocument &doc) { TiXmlHandle docHandle(&doc); /// We know we have it since we made it this far. TiXmlElement* mesh = docHandle.FirstChildElement("NEKTAR").FirstChildElement("GEOMETRY").Element(); TiXmlElement* field = NULL; ASSERTL0(mesh, "Unable to find GEOMETRY tag in file."); /// Look for elements in ELEMENT block. field = mesh->FirstChildElement("COMPOSITE"); ASSERTL0(field, "Unable to find COMPOSITE tag in file."); TiXmlElement *node = field->FirstChildElement("C"); // Sequential counter for the composite numbers. int nextCompositeNumber = -1; while (node) { /// All elements are of the form: "<? ID="#"> ... </?>", with /// ? being the element type. nextCompositeNumber++; int indx; int err = node->QueryIntAttribute("ID", &indx); ASSERTL0(err == TIXML_SUCCESS, "Unable to read attribute ID."); ASSERTL0(indx == nextCompositeNumber, "Composite IDs must begin with zero and be sequential."); TiXmlNode* compositeChild = node->FirstChild(); // This is primarily to skip comments that may be present. // Comments appear as nodes just like elements. // We are specifically looking for text in the body // of the definition. while(compositeChild && compositeChild->Type() != TiXmlNode::TEXT) { compositeChild = compositeChild->NextSibling(); } ASSERTL0(compositeChild, "Unable to read composite definition body."); std::string compositeStr = compositeChild->ToText()->ValueStr(); /// Parse out the element components corresponding to type of element. std::istrstream compositeDataStrm(compositeStr.c_str()); try { bool first = true; std::string prevCompositeElementStr; while (!compositeDataStrm.fail()) { std::string compositeElementStr; compositeDataStrm >> compositeElementStr; if (!compositeDataStrm.fail()) { if (first) { first = false; Composite curVector = MemoryManager<std::vector<GeometrySharedPtr> >::AllocateSharedPtr(); m_MeshCompositeVector.push_back(curVector); } if (compositeElementStr.length() > 0) { ResolveGeomRef(prevCompositeElementStr, compositeElementStr); } prevCompositeElementStr = compositeElementStr; } } } catch(...) { NEKERROR(ErrorUtil::efatal, (std::string("Unable to read COMPOSITE data for composite: ") + compositeStr).c_str()); } /// Keep looking for additional composite definitions. node = node->NextSiblingElement("C"); } ASSERTL0(nextCompositeNumber >= 0, "At least one composite must be specified."); } // Take the string that is the composite reference and find the // pointer to the Geometry object corresponding to it. // Only allow segments to be grouped for 1D mesh. void MeshGraph1D::ResolveGeomRef(const std::string &prevToken, const std::string &token) { try { std::istringstream tokenStream(token); std::istringstream prevTokenStream(prevToken); char type; char prevType; tokenStream >> type; std::string::size_type indxBeg = token.find_first_of('[') + 1; std::string::size_type indxEnd = token.find_last_of(']') - 1; ASSERTL0(indxBeg <= indxEnd, (std::string("Error reading index definition:") + token).c_str()); std::string indxStr = token.substr(indxBeg, indxEnd - indxBeg + 1); typedef vector<unsigned int> SeqVectorType; SeqVectorType seqVector; if (!ParseUtils::GenerateSeqVector(indxStr.c_str(), seqVector)) { NEKERROR(ErrorUtil::efatal, (std::string("Ill-formed sequence definition: ") + indxStr).c_str()); } prevTokenStream >> prevType; // All composites must be of the same dimension. bool validSequence = (prevToken.empty() || // No previous, then current is just fine. (type == 'V' && prevType == 'V') || (type == 'S' && prevType == 'S')); ASSERTL0(validSequence, (std::string("Invalid combination of composite items: ") + type + " and " + prevType + ".").c_str()); switch(type) { case 'V': // Vertex for (SeqVectorType::iterator iter=seqVector.begin(); iter!=seqVector.end(); ++iter) { if (*iter >= m_vertset.size()) { char errStr[16] = ""; ::sprintf(errStr, "%d", *iter); NEKERROR(ErrorUtil::ewarning, (std::string("Unknown vertex index: ") + errStr).c_str()); } else { m_MeshCompositeVector.back()->push_back(m_vertset[*iter]); } } break; case 'S': // Segment for (SeqVectorType::iterator iter=seqVector.begin(); iter!=seqVector.end(); ++iter) { if (*iter >= m_seggeoms.size()) { char errStr[16] = ""; ::sprintf(errStr, "%d", *iter); NEKERROR(ErrorUtil::ewarning, (std::string("Unknown segment index: ") + errStr).c_str()); } else { m_MeshCompositeVector.back()->push_back(m_seggeoms[*iter]); } } break; default: NEKERROR(ErrorUtil::efatal, (std::string("Unrecognized composite token: ") + token).c_str()); } } catch(...) { NEKERROR(ErrorUtil::efatal, (std::string("Problem processing composite token: ") + token).c_str()); } return; } void MeshGraph1D::Write(std::string &outfilename) { } }; //end of namespace }; //end of namespace // // $Log: MeshGraph1D.cpp,v $ // Revision 1.14 2007/07/26 01:38:32 jfrazier // Cleanup of some attribute reading code. // // Revision 1.13 2007/07/24 16:52:09 jfrazier // Added domain code. // // Revision 1.12 2007/07/23 16:54:30 jfrazier // Change a dynamic allocation using new to memory manager allocate. // // Revision 1.11 2007/07/05 04:21:10 jfrazier // Changed id format and propagated from 1d to 2d. // // Revision 1.10 2007/06/10 02:27:10 jfrazier // Another checkin with an incremental completion of the boundary conditions reader. // // Revision 1.9 2007/06/07 23:55:24 jfrazier // Intermediate revisions to add parsing for boundary conditions file. // // Revision 1.8 2007/03/14 21:24:08 sherwin // Update for working version of MultiRegions up to ExpList1D // // Revision 1.7 2006/10/15 06:18:58 sherwin // Moved NekPoint out of namespace LibUtilities // // Revision 1.6 2006/09/26 23:41:53 jfrazier // Updated to account for highest level NEKTAR tag and changed the geometry tag to GEOMETRY. // // Revision 1.5 2006/06/01 14:15:30 sherwin // Added typdef of boost wrappers and made GeoFac a boost shared pointer. // // Revision 1.4 2006/05/23 19:56:33 jfrazier // These build and run, but the expansion pieces are commented out // because they would not run. // // Revision 1.3 2006/05/16 22:28:31 sherwin // Updates to add in FaceComponent call to constructors // // Revision 1.2 2006/05/16 20:12:59 jfrazier // Minor fixes to correct bugs. // // Revision 1.1 2006/05/04 18:59:01 kirby // *** empty log message *** // // Revision 1.17 2006/04/09 02:08:35 jfrazier // Added precompiled header. // // Revision 1.16 2006/04/04 23:12:37 jfrazier // More updates to readers. Still work to do on MeshGraph2D to store tris and quads. // // Revision 1.15 2006/03/25 00:58:29 jfrazier // Many changes dealing with fundamental structure and reading/writing. // // Revision 1.14 2006/03/12 14:20:43 sherwin // // First compiling version of SpatialDomains and associated modifications // // Revision 1.13 2006/03/12 07:42:03 sherwin // // Updated member names and StdRegions call. Still has not been compiled // // Revision 1.12 2006/02/26 21:19:43 bnelson // Fixed a variety of compiler errors caused by updates to the coding standard. // // Revision 1.11 2006/02/19 01:37:33 jfrazier // Initial attempt at bringing into conformance with the coding standard. Still more work to be done. Has not been compiled. // // <|endoftext|>
<commit_before>#include "engine.h" #include "random.h" #include "Updatable.h" #include "collisionable.h" #include "audio/source.h" #include "io/keybinding.h" #include "soundManager.h" #include "windowManager.h" #include "scriptInterface.h" #include "multiplayer_server.h" #include <thread> #include <SDL.h> #ifdef STEAMSDK #include "steam/steam_api.h" #include "steam/steam_api_flat.h" #endif #ifdef DEBUG #include <typeinfo> int DEBUG_PobjCount; PObject* DEBUG_PobjListStart; #endif Engine* engine; Engine::Engine() { engine = this; #ifdef STEAMSDK if (SteamAPI_RestartAppIfNecessary(1907040)) exit(1); if (!SteamAPI_Init()) { LOG(Error, "Failed to initialize steam API."); exit(1); } SteamNetworkingUtils()->InitRelayNetworkAccess(); LOG(Debug, "StreamID:", SteamAPI_ISteamUser_GetSteamID(SteamAPI_SteamUser())); #endif #ifdef WIN32 // Setup crash reporter (Dr. MinGW) if available. exchndl = DynamicLibrary::open("exchndl.dll"); if (exchndl) { auto pfnExcHndlInit = exchndl->getFunction<void(*)(void)>("ExcHndlInit"); if (pfnExcHndlInit) { pfnExcHndlInit(); LOG(INFO) << "Crash Reporter ON"; } else { exchndl.reset(); } } #endif // WIN32 SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0"); SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); // Have clicking on a window to get focus generate mouse events. For multimonitor support. #ifdef SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH SDL_SetHint(SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH, "1"); #elif defined(SDL_HINT_MOUSE_TOUCH_EVENTS) SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "0"); SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0"); #endif SDL_Init(SDL_INIT_EVERYTHING); SDL_ShowCursor(false); SDL_StopTextInput(); atexit(SDL_Quit); initRandom(); CollisionManager::initialize(); gameSpeed = 1.0f; running = true; elapsedTime = 0.0f; soundManager = new SoundManager(); } Engine::~Engine() { Window::all_windows.clear(); updatableList.clear(); delete soundManager; soundManager = nullptr; } void Engine::registerObject(string name, P<PObject> obj) { objectMap[name] = obj; } P<PObject> Engine::getObject(string name) { if (!objectMap[name]) return NULL; return objectMap[name]; } void Engine::runMainLoop() { if (Window::all_windows.size() == 0) { sp::SystemStopwatch frame_timer; while(running) { float delta = frame_timer.restart(); if (delta > 0.5f) delta = 0.5f; if (delta < 0.001f) delta = 0.001f; delta *= gameSpeed; foreach(Updatable, u, updatableList) u->update(delta); elapsedTime += delta; CollisionManager::handleCollisions(delta); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); #ifdef STEAMSDK SteamAPI_RunCallbacks(); #endif std::this_thread::sleep_for(std::chrono::duration<float>(1.f/60.f - delta)); } }else{ sp::audio::Source::startAudioSystem(); sp::SystemStopwatch frame_timer; #ifdef DEBUG sp::SystemTimer debug_output_timer; debug_output_timer.repeat(5); #endif while(running) { // Handle events SDL_Event event; while (SDL_PollEvent(&event)) { handleEvent(event); } #ifdef DEBUG if (debug_output_timer.isExpired()) LOG(DEBUG) << "Object count: " << DEBUG_PobjCount << " " << updatableList.size(); #endif float delta = frame_timer.restart(); if (delta > 0.5f) delta = 0.5f; if (delta < 0.001f) delta = 0.001f; delta *= gameSpeed; EngineTiming engine_timing; sp::SystemStopwatch engine_timing_stopwatch; foreach(Updatable, u, updatableList) { u->update(delta); } elapsedTime += delta; engine_timing.update = engine_timing_stopwatch.restart(); CollisionManager::handleCollisions(delta); engine_timing.collision = engine_timing_stopwatch.restart(); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); #ifdef STEAMSDK SteamAPI_RunCallbacks(); #endif // Clear the window for(auto window : Window::all_windows) window->render(); engine_timing.render = engine_timing_stopwatch.restart(); engine_timing.server_update = 0.0f; if (game_server) engine_timing.server_update = game_server->getUpdateTime(); last_engine_timing = engine_timing; sp::io::Keybinding::allPostUpdate(); } soundManager->stopMusic(); sp::audio::Source::stopAudioSystem(); } } void Engine::handleEvent(SDL_Event& event) { if (event.type == SDL_QUIT) running = false; #ifdef DEBUG if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) running = false; if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_l) { int n = 0; printf("------------------------\n"); std::unordered_map<string,int> totals; for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext) { printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name()); if (!obj->isDestroyed()) { totals[typeid(*obj).name()]=totals[typeid(*obj).name()]+1; } } printf("--non-destroyed totals--\n"); int grand_total=0; for (auto entry : totals) { printf("%4d %s\n", entry.second, entry.first.c_str()); grand_total+=entry.second; } printf("%4d %s\n",grand_total,"All PObjects"); printf("------------------------\n"); } #endif unsigned int window_id = 0; switch(event.type) { case SDL_KEYDOWN: #ifdef __EMSCRIPTEN__ if (!audio_started) { audio::AudioSource::startAudioSystem(); audio_started = true; } #endif case SDL_KEYUP: window_id = event.key.windowID; break; case SDL_MOUSEMOTION: window_id = event.motion.windowID; break; case SDL_MOUSEBUTTONDOWN: #ifdef __EMSCRIPTEN__ if (!audio_started) { audio::AudioSource::startAudioSystem(); audio_started = true; } #endif case SDL_MOUSEBUTTONUP: window_id = event.button.windowID; break; case SDL_MOUSEWHEEL: window_id = event.wheel.windowID; break; case SDL_WINDOWEVENT: window_id = event.window.windowID; break; case SDL_FINGERDOWN: case SDL_FINGERUP: case SDL_FINGERMOTION: #if SDL_VERSION_ATLEAST(2, 0, 12) window_id = event.tfinger.windowID; #else window_id = SDL_GetWindowID(SDL_GetMouseFocus()); #endif break; case SDL_TEXTEDITING: window_id = event.edit.windowID; break; case SDL_TEXTINPUT: window_id = event.text.windowID; break; } if (window_id != 0) { foreach(Window, window, Window::all_windows) if (window->window && SDL_GetWindowID(static_cast<SDL_Window*>(window->window)) == window_id) window->handleEvent(event); } sp::io::Keybinding::handleEvent(event); } void Engine::setGameSpeed(float speed) { gameSpeed = speed; } float Engine::getGameSpeed() { return gameSpeed; } float Engine::getElapsedTime() { return elapsedTime; } Engine::EngineTiming Engine::getEngineTiming() { return last_engine_timing; } void Engine::shutdown() { running = false; } <commit_msg>Fix typo in debug log<commit_after>#include "engine.h" #include "random.h" #include "Updatable.h" #include "collisionable.h" #include "audio/source.h" #include "io/keybinding.h" #include "soundManager.h" #include "windowManager.h" #include "scriptInterface.h" #include "multiplayer_server.h" #include <thread> #include <SDL.h> #ifdef STEAMSDK #include "steam/steam_api.h" #include "steam/steam_api_flat.h" #endif #ifdef DEBUG #include <typeinfo> int DEBUG_PobjCount; PObject* DEBUG_PobjListStart; #endif Engine* engine; Engine::Engine() { engine = this; #ifdef STEAMSDK if (SteamAPI_RestartAppIfNecessary(1907040)) exit(1); if (!SteamAPI_Init()) { LOG(Error, "Failed to initialize steam API."); exit(1); } SteamNetworkingUtils()->InitRelayNetworkAccess(); LOG(Debug, "SteamID:", SteamAPI_ISteamUser_GetSteamID(SteamAPI_SteamUser())); #endif #ifdef WIN32 // Setup crash reporter (Dr. MinGW) if available. exchndl = DynamicLibrary::open("exchndl.dll"); if (exchndl) { auto pfnExcHndlInit = exchndl->getFunction<void(*)(void)>("ExcHndlInit"); if (pfnExcHndlInit) { pfnExcHndlInit(); LOG(INFO) << "Crash Reporter ON"; } else { exchndl.reset(); } } #endif // WIN32 SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0"); SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"); // Have clicking on a window to get focus generate mouse events. For multimonitor support. #ifdef SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH SDL_SetHint(SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH, "1"); #elif defined(SDL_HINT_MOUSE_TOUCH_EVENTS) SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "0"); SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0"); #endif SDL_Init(SDL_INIT_EVERYTHING); SDL_ShowCursor(false); SDL_StopTextInput(); atexit(SDL_Quit); initRandom(); CollisionManager::initialize(); gameSpeed = 1.0f; running = true; elapsedTime = 0.0f; soundManager = new SoundManager(); } Engine::~Engine() { Window::all_windows.clear(); updatableList.clear(); delete soundManager; soundManager = nullptr; } void Engine::registerObject(string name, P<PObject> obj) { objectMap[name] = obj; } P<PObject> Engine::getObject(string name) { if (!objectMap[name]) return NULL; return objectMap[name]; } void Engine::runMainLoop() { if (Window::all_windows.size() == 0) { sp::SystemStopwatch frame_timer; while(running) { float delta = frame_timer.restart(); if (delta > 0.5f) delta = 0.5f; if (delta < 0.001f) delta = 0.001f; delta *= gameSpeed; foreach(Updatable, u, updatableList) u->update(delta); elapsedTime += delta; CollisionManager::handleCollisions(delta); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); #ifdef STEAMSDK SteamAPI_RunCallbacks(); #endif std::this_thread::sleep_for(std::chrono::duration<float>(1.f/60.f - delta)); } }else{ sp::audio::Source::startAudioSystem(); sp::SystemStopwatch frame_timer; #ifdef DEBUG sp::SystemTimer debug_output_timer; debug_output_timer.repeat(5); #endif while(running) { // Handle events SDL_Event event; while (SDL_PollEvent(&event)) { handleEvent(event); } #ifdef DEBUG if (debug_output_timer.isExpired()) LOG(DEBUG) << "Object count: " << DEBUG_PobjCount << " " << updatableList.size(); #endif float delta = frame_timer.restart(); if (delta > 0.5f) delta = 0.5f; if (delta < 0.001f) delta = 0.001f; delta *= gameSpeed; EngineTiming engine_timing; sp::SystemStopwatch engine_timing_stopwatch; foreach(Updatable, u, updatableList) { u->update(delta); } elapsedTime += delta; engine_timing.update = engine_timing_stopwatch.restart(); CollisionManager::handleCollisions(delta); engine_timing.collision = engine_timing_stopwatch.restart(); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); #ifdef STEAMSDK SteamAPI_RunCallbacks(); #endif // Clear the window for(auto window : Window::all_windows) window->render(); engine_timing.render = engine_timing_stopwatch.restart(); engine_timing.server_update = 0.0f; if (game_server) engine_timing.server_update = game_server->getUpdateTime(); last_engine_timing = engine_timing; sp::io::Keybinding::allPostUpdate(); } soundManager->stopMusic(); sp::audio::Source::stopAudioSystem(); } } void Engine::handleEvent(SDL_Event& event) { if (event.type == SDL_QUIT) running = false; #ifdef DEBUG if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) running = false; if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_l) { int n = 0; printf("------------------------\n"); std::unordered_map<string,int> totals; for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext) { printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name()); if (!obj->isDestroyed()) { totals[typeid(*obj).name()]=totals[typeid(*obj).name()]+1; } } printf("--non-destroyed totals--\n"); int grand_total=0; for (auto entry : totals) { printf("%4d %s\n", entry.second, entry.first.c_str()); grand_total+=entry.second; } printf("%4d %s\n",grand_total,"All PObjects"); printf("------------------------\n"); } #endif unsigned int window_id = 0; switch(event.type) { case SDL_KEYDOWN: #ifdef __EMSCRIPTEN__ if (!audio_started) { audio::AudioSource::startAudioSystem(); audio_started = true; } #endif case SDL_KEYUP: window_id = event.key.windowID; break; case SDL_MOUSEMOTION: window_id = event.motion.windowID; break; case SDL_MOUSEBUTTONDOWN: #ifdef __EMSCRIPTEN__ if (!audio_started) { audio::AudioSource::startAudioSystem(); audio_started = true; } #endif case SDL_MOUSEBUTTONUP: window_id = event.button.windowID; break; case SDL_MOUSEWHEEL: window_id = event.wheel.windowID; break; case SDL_WINDOWEVENT: window_id = event.window.windowID; break; case SDL_FINGERDOWN: case SDL_FINGERUP: case SDL_FINGERMOTION: #if SDL_VERSION_ATLEAST(2, 0, 12) window_id = event.tfinger.windowID; #else window_id = SDL_GetWindowID(SDL_GetMouseFocus()); #endif break; case SDL_TEXTEDITING: window_id = event.edit.windowID; break; case SDL_TEXTINPUT: window_id = event.text.windowID; break; } if (window_id != 0) { foreach(Window, window, Window::all_windows) if (window->window && SDL_GetWindowID(static_cast<SDL_Window*>(window->window)) == window_id) window->handleEvent(event); } sp::io::Keybinding::handleEvent(event); } void Engine::setGameSpeed(float speed) { gameSpeed = speed; } float Engine::getGameSpeed() { return gameSpeed; } float Engine::getElapsedTime() { return elapsedTime; } Engine::EngineTiming Engine::getEngineTiming() { return last_engine_timing; } void Engine::shutdown() { running = false; } <|endoftext|>
<commit_before>#include "filter.hpp" using namespace std; namespace vg{ Filter::Filter(){ } Filter::~Filter(){ } void Filter::set_min_depth(int depth){ min_depth = depth; } void Filter::set_min_qual(int qual){ min_qual = qual; } void Filter::set_min_percent_identity(double pct_id){ min_percent_identity = pct_id; } void Filter::set_avg_qual(double avg_qual){ min_avg_qual = avg_qual; } void Filter::set_filter_matches(bool fm){ filter_matches = fm; } void Filter::set_remove_failing_alignments(bool fm){ remove_failing_alignments = fm; } /** * * Looks for alignments that transition from one path to another * over their length. This may occur for one of several reasons: * 1. The read covers a translocation * 2. The read looks a lot like two different (but highly-similar paths) * 3. The read is shattered (e.g. as in chromothripsis) * * Default behavior: if the Alignment is path divergent, return an empty Alignment * Inverse behavior: if the Alignment is path divergent, return the Alignment */ Alignment Filter::path_divergence_filter(Alignment& aln){ } /** * Looks for alignments that change direction over their length. * This may happen because of: * 1. Mapping artifacts * 2. Cycles * 3. Highly repetitive regions * 4. Inversions (if you're lucky enough) * * Default behavior: if the Alignment reverses, return an empty Alignment. * inverse behavior: if the Alignment reverses, return the Alignment. */ Alignment Filter::reversing_filter(Alignment& aln){ Path path = aln.path(); bool prev = false; for (int i = 1; i < path.mapping_size(); i++){ Mapping mapping = path.mapping(i); Position pos = mapping.position(); bool prev = path.mapping(i - 1).position().is_reverse(); if (prev | pos.is_reverse()){ return (inverse ? aln : Alignment()); } } return inverse ? Alignment() : aln; } /** * Looks for Alignments that have large overhangs at the end of them. * * Default behavior: if an alignment has a right- or left- clip that is longer * than the maximum allowed, return an empty alignment. * * Inverse Behavior: if the alignment has a clip that is larger than the * maximum allowed at either end, return the alignment. */ void Filter::set_softclip_filter(int max_clip){ max_softclip = max_clip; } void Filter::set_splitread_filter(bool dsr){ do_splitread = dsr; } /** * CLI: vg filter -d 10 -q 40 -r -R * -r: track depth of both novel variants and those in the graph. * -R: remove edits that fail the filter (otherwise toss the whole alignment) */ Alignment Filter::depth_filter(Alignment& aln){ Path path = aln.path(); //TODO handle reversing mappings for (int i = 0; i < path.mapping_size(); i++){ Mapping mapping = path.mapping(i); Position start_pos = mapping.position(); int64_t start_node = start_pos.node_id(); int64_t start_offset = start_pos.offset(); int64_t curr_offset_in_graph = 0; int64_t curr_offset_in_alignment = 0; stringstream pst; pst << start_node << "_" << curr_offset_in_graph; string p_hash = pst.str(); for (int j = 0; j < mapping.edit_size(); j++){ Edit ee = mapping.edit(j); if (ee.from_length() == ee.to_length() && ee.sequence() == ""){ if (!filter_matches){ continue; } } stringstream est; est << ee.from_length() << "_" << ee.to_length() << "_" + ee.sequence(); string e_hash = est.str(); #pragma omp critical(write) pos_to_edit_to_depth[p_hash][e_hash] += 1; /** * If an edit fails the filter, either return a new empty alignment * OR * return a new alignment identical to the old one EXCEPT where * the offending edit has been replaced by a match to the reference. */ if (pos_to_edit_to_depth[p_hash][e_hash] < min_depth){ if (remove_failing_alignments){ return Alignment(); } else { Alignment edited_aln = Alignment(aln); edited_aln.mutable_path()->mutable_mapping(i)->mutable_edit(j)->set_sequence(""); edited_aln.mutable_path()->mutable_mapping(i)->mutable_edit(j)->set_from_length(ee.from_length()); edited_aln.mutable_path()->mutable_mapping(i)->mutable_edit(j)->set_to_length(ee.from_length()); return edited_aln; } } } return aln; } } Alignment Filter::qual_filter(Alignment& aln){ string quals = aln.quality(); int offset = 0; for (int i = 0; i < quals.size(); i++){ if (((int) quals[i] - offset) < min_qual){ if (remove_failing_alignments){ return Alignment(); } else{ //TODO: Should we really edit out poor-quality bases?? // It's complex and awkward. return Alignment(); } } } return aln; } Alignment Filter::coverage_filter(Alignment& aln){ } Alignment Filter::avg_qual_filter(Alignment& aln){ double total_qual = 0.0; // If the parameter for window size is zero, set the local equivalent // to the entire size of the qual scores. int win_len = window_len; // >= 1 ? window_len : aln.quality().size(); cerr << "UNTESTED" << endl; exit(1); std::function<double(int64_t, int64_t)> calc_avg_qual = [](int64_t total_qual, int64_t length){ return ((double) total_qual / (double) length); }; /** * Helper function. * Sums qual scores from start : start + window_length * if start + window_len > qualstr.size(), return a negative float * otherwise return the average quality within the window * */ std::function<double(string, int, int)> window_qual = [&](string qualstr, int start, int window_length){ if (start + window_length > qualstr.size()){ return -1.0; } total_qual = 0.0; for (int i = start; i < start + window_length; i++){ total_qual += (int) qualstr[i]; } return calc_avg_qual(total_qual, window_length); }; //TODO: handle reversing alignments string quals = aln.quality(); for (int i = 0; i < quals.size() - win_len; i++){ double w_qual = window_qual(quals, i, win_len); if ( w_qual < 1){ break; } if (w_qual < min_avg_qual){ return Alignment(); } } return aln; } Alignment Filter::soft_clip_filter(Alignment& aln){ //Find overhangs - portions of the read that // are inserted at the ends. if (aln.path().mapping_size() > 0){ Path path = aln.path(); Edit left_edit = path.mapping(0).edit(0); Edit right_edit = path.mapping(path.mapping_size() - 1).edit(path.mapping(0).edit_size() - 1); int left_overhang = left_edit.to_length() - left_edit.from_length(); int right_overhang = right_edit.to_length() - right_edit.from_length(); if (left_overhang > max_softclip || right_overhang > max_softclip){ return Alignment(); } return aln; } else{ if (aln.sequence().length() > max_softclip){ return Alignment(); } cerr << "WARNING: SHORT ALIGNMENT: " << aln.sequence().size() << "bp" << endl << "WITH NO MAPPINGS TO REFERENCE" << endl << "CONSIDER REMOVING IT FROM ANALYSIS" << endl; return aln; } } /** * Split reads map to two separate paths in the graph OR vastly separated non-consecutive * nodes in a single path. * * They're super important for detecting structural variants, so we may want to * filter them out or collect only split reads. */ Alignment Filter::split_read_filter(Alignment& aln){ //TODO binary search for breakpoint in read would be awesome. Path path = aln.path(); //check if nodes are on same path(s) int top_side = path.mapping_size(); int bottom_side = 0; bool diverges = false; string main_path = ""; while (top_side > bottom_side){ //main_path = path_of_node(path.mapping(bottom_side); // //Check if paths are different //if (divergent(node1, node2){ // diverges = true; //} top_side--; bottom_side++; } //TODO check this; I'm not sure this is a fully safe conditional: // reg: diverges: return ALN() // reg: !diverges: return aln // inv: diverges: return return aln; // inv: !diverges: return ALN() if ((diverges && !inverse) || (!diverges && inverse)){ return Alignment(); } else{ return aln; } } /** * Filter reads that are less than <PCTID> reference. * I.E. if a read matches the reference along 80% of its * length, and your cutoff is 90% PCTID, throw it out. */ Alignment Filter::percent_identity_filter(Alignment& aln){ double read_pctid = 0.0; //read pct_id = len(matching sequence / len(total sequence) int64_t aln_total_len = aln.sequence().size(); int64_t aln_match_len = 0; std::function<double(int64_t, int64_t)> calc_pct_id = [](int64_t rp, int64_t ttlp){ return ((double) rp / (double) ttlp); }; Path path = aln.path(); //TODO handle reversing mappings for (int i = 0; i < path.mapping_size(); i++){ Mapping mapping = path.mapping(i); for (int j = 0; j < mapping.edit_size(); j++){ Edit ee = mapping.edit(j); if (ee.from_length() == ee.to_length() && ee.sequence() == ""){ aln_match_len += ee.to_length(); } } } if (calc_pct_id(aln_match_len, aln_total_len) < min_percent_identity){ return Alignment(); } return aln; } } <commit_msg>Added ternary operators (for handling inverse queries) to all return statements in filter.coo<commit_after>#include "filter.hpp" using namespace std; namespace vg{ Filter::Filter(){ } Filter::~Filter(){ } void Filter::set_min_depth(int depth){ min_depth = depth; } void Filter::set_min_qual(int qual){ min_qual = qual; } void Filter::set_min_percent_identity(double pct_id){ min_percent_identity = pct_id; } void Filter::set_avg_qual(double avg_qual){ min_avg_qual = avg_qual; } void Filter::set_filter_matches(bool fm){ filter_matches = fm; } void Filter::set_remove_failing_alignments(bool fm){ remove_failing_alignments = fm; } /** * * Looks for alignments that transition from one path to another * over their length. This may occur for one of several reasons: * 1. The read covers a translocation * 2. The read looks a lot like two different (but highly-similar paths) * 3. The read is shattered (e.g. as in chromothripsis) * * Default behavior: if the Alignment is path divergent, return an empty Alignment, else return aln * Inverse behavior: if the Alignment is path divergent, return aln, else return an empty Alignment */ Alignment Filter::path_divergence_filter(Alignment& aln){ return inverse ? Alignment() : aln; } /** * Looks for alignments that change direction over their length. * This may happen because of: * 1. Mapping artifacts * 2. Cycles * 3. Highly repetitive regions * 4. Inversions (if you're lucky enough) * * Default behavior: if the Alignment reverses, return an empty Alignment. * inverse behavior: if the Alignment reverses, return the Alignment. */ Alignment Filter::reversing_filter(Alignment& aln){ Path path = aln.path(); bool prev = false; for (int i = 1; i < path.mapping_size(); i++){ Mapping mapping = path.mapping(i); Position pos = mapping.position(); bool prev = path.mapping(i - 1).position().is_reverse(); if (prev | pos.is_reverse()){ return (inverse ? aln : Alignment()); } } return inverse ? Alignment() : aln; } /** * Looks for Alignments that have large overhangs at the end of them. * * Default behavior: if an alignment has a right- or left- clip that is longer * than the maximum allowed, return an empty alignment. * * Inverse Behavior: if the alignment has a clip that is larger than the * maximum allowed at either end, return the alignment. */ void Filter::set_softclip_filter(int max_clip){ max_softclip = max_clip; } void Filter::set_splitread_filter(bool dsr){ do_splitread = dsr; } /** * CLI: vg filter -d 10 -q 40 -r -R * -r: track depth of both novel variants and those in the graph. * -R: remove edits that fail the filter (otherwise toss the whole alignment) */ Alignment Filter::depth_filter(Alignment& aln){ Path path = aln.path(); //TODO handle reversing mappings for (int i = 0; i < path.mapping_size(); i++){ Mapping mapping = path.mapping(i); Position start_pos = mapping.position(); int64_t start_node = start_pos.node_id(); int64_t start_offset = start_pos.offset(); int64_t curr_offset_in_graph = 0; int64_t curr_offset_in_alignment = 0; stringstream pst; pst << start_node << "_" << curr_offset_in_graph; string p_hash = pst.str(); for (int j = 0; j < mapping.edit_size(); j++){ Edit ee = mapping.edit(j); if (ee.from_length() == ee.to_length() && ee.sequence() == ""){ if (!filter_matches){ continue; } } stringstream est; est << ee.from_length() << "_" << ee.to_length() << "_" + ee.sequence(); string e_hash = est.str(); #pragma omp critical(write) pos_to_edit_to_depth[p_hash][e_hash] += 1; /** * If an edit fails the filter, either return a new empty alignment * OR * return a new alignment identical to the old one EXCEPT where * the offending edit has been replaced by a match to the reference. */ if (pos_to_edit_to_depth[p_hash][e_hash] < min_depth){ if (remove_failing_alignments){ return inverse ? aln : Alignment(); } else { Alignment edited_aln = Alignment(aln); edited_aln.mutable_path()->mutable_mapping(i)->mutable_edit(j)->set_sequence(""); edited_aln.mutable_path()->mutable_mapping(i)->mutable_edit(j)->set_from_length(ee.from_length()); edited_aln.mutable_path()->mutable_mapping(i)->mutable_edit(j)->set_to_length(ee.from_length()); return edited_aln; } } } return inverse ? Alignment() : aln; } } Alignment Filter::qual_filter(Alignment& aln){ string quals = aln.quality(); int offset = 0; for (int i = 0; i < quals.size(); i++){ if (((int) quals[i] - offset) < min_qual){ if (remove_failing_alignments){ return Alignment(); } else{ //TODO: Should we really edit out poor-quality bases?? // It's complex and awkward. return inverse ? aln : Alignment(); } } } return inverse ? Alignment() : aln; } Alignment Filter::coverage_filter(Alignment& aln){ } Alignment Filter::avg_qual_filter(Alignment& aln){ double total_qual = 0.0; // If the parameter for window size is zero, set the local equivalent // to the entire size of the qual scores. int win_len = window_len; // >= 1 ? window_len : aln.quality().size(); cerr << "UNTESTED" << endl; exit(1); std::function<double(int64_t, int64_t)> calc_avg_qual = [](int64_t total_qual, int64_t length){ return ((double) total_qual / (double) length); }; /** * Helper function. * Sums qual scores from start : start + window_length * if start + window_len > qualstr.size(), return a negative float * otherwise return the average quality within the window * */ std::function<double(string, int, int)> window_qual = [&](string qualstr, int start, int window_length){ if (start + window_length > qualstr.size()){ return -1.0; } total_qual = 0.0; for (int i = start; i < start + window_length; i++){ total_qual += (int) qualstr[i]; } return calc_avg_qual(total_qual, window_length); }; //TODO: handle reversing alignments string quals = aln.quality(); for (int i = 0; i < quals.size() - win_len; i++){ double w_qual = window_qual(quals, i, win_len); if ( w_qual < 0.0){ break; } if (w_qual < min_avg_qual){ return inverse ? aln : Alignment(); } } return inverse ? Alignment() : aln; } Alignment Filter::soft_clip_filter(Alignment& aln){ //Find overhangs - portions of the read that // are inserted at the ends. if (aln.path().mapping_size() > 0){ Path path = aln.path(); Edit left_edit = path.mapping(0).edit(0); Edit right_edit = path.mapping(path.mapping_size() - 1).edit(path.mapping(0).edit_size() - 1); int left_overhang = left_edit.to_length() - left_edit.from_length(); int right_overhang = right_edit.to_length() - right_edit.from_length(); if (left_overhang > max_softclip || right_overhang > max_softclip){ return Alignment(); } return inverse ? Alignment() : aln; } else{ if (aln.sequence().length() > max_softclip){ return Alignment(); } cerr << "WARNING: SHORT ALIGNMENT: " << aln.sequence().size() << "bp" << endl << "WITH NO MAPPINGS TO REFERENCE" << endl << "CONSIDER REMOVING IT FROM ANALYSIS" << endl; return inverse ? Alignment() : aln; } } /** * Split reads map to two separate paths in the graph OR vastly separated non-consecutive * nodes in a single path. * * They're super important for detecting structural variants, so we may want to * filter them out or collect only split reads. */ Alignment Filter::split_read_filter(Alignment& aln){ //TODO binary search for breakpoint in read would be awesome. Path path = aln.path(); //check if nodes are on same path(s) int top_side = path.mapping_size(); int bottom_side = 0; bool diverges = false; string main_path = ""; while (top_side > bottom_side){ //main_path = path_of_node(path.mapping(bottom_side); // //Check if paths are different //if (divergent(node1, node2){ // diverges = true; //} top_side--; bottom_side++; } //TODO check this; I'm not sure this is a fully safe conditional: // reg: diverges: return ALN() // reg: !diverges: return aln // inv: diverges: return return aln; // inv: !diverges: return ALN() if ((diverges)){ return inverse ? aln : Alignment(); } else{ return inverse ? Alignment() : aln; } } /** * Filter reads that are less than <PCTID> reference. * I.E. if a read matches the reference along 80% of its * length, and your cutoff is 90% PCTID, throw it out. */ Alignment Filter::percent_identity_filter(Alignment& aln){ double read_pctid = 0.0; //read pct_id = len(matching sequence / len(total sequence) int64_t aln_total_len = aln.sequence().size(); int64_t aln_match_len = 0; std::function<double(int64_t, int64_t)> calc_pct_id = [](int64_t rp, int64_t ttlp){ return ((double) rp / (double) ttlp); }; Path path = aln.path(); //TODO handle reversing mappings for (int i = 0; i < path.mapping_size(); i++){ Mapping mapping = path.mapping(i); for (int j = 0; j < mapping.edit_size(); j++){ Edit ee = mapping.edit(j); if (ee.from_length() == ee.to_length() && ee.sequence() == ""){ aln_match_len += ee.to_length(); } } } if (calc_pct_id(aln_match_len, aln_total_len) < min_percent_identity){ return inverse ? aln : Alignment(); } return inverse ? Alignment() : aln; } } <|endoftext|>
<commit_before>#include "rts/gc.h" namespace rts { using std::uint64_t; using std::unordered_set; using std::mutex; thread_local hec * hec::current; unordered_set<hec*> hecs; mutex gc_mutex; boost::lockfree::queue<gc_ptr> global_mark_queue[8]; void gc_ptr::lvb_slow_path(uint64_t * address, int trigger) { uint64_t old = addr; if (trigger | triggers::contraction) { unique = 0; } // this object was white, make it grey. if (trigger | triggers::nmt) { nmt = !nmt; if (unique) { // For anything locally unique we should walk the local subspace, chasing any unique references // and doing opportunistic graph reduction. When we consume k unique references we can // afford O(k) work. This means we'd act like a semispace copying collector for // objects that are known unique, and only ever pass to the marking system things // with multiple (potential) references. This also avoids crafting an indirection // upon enqueuing a unique closure for marking. It also generalizes Wadler's garbage collection // trick for eliminating certain forms of space leaks. // // This would be sufficient to handle things like a GRIN primitive for + being applied // to known integers, for instance. } else { if (space <= 8) hec::current->local_mark_queue[space].push(*this); else global_mark_queue[space - 8].push(*this); } } if (trigger | triggers::relocation) { // this page is actively being relocated. cooperate // grab a handle to the information about this page that is being relocated // try to claim this object // if we succeed, and it is not yet relocated, relocate it // regardless set addr equal to the new location } if (trigger | triggers::contraction && type == types::closure) { // we're actually going to write this answer into the _closure_ we made // addr = new_indirection(addr); } __sync_val_compare_and_swap(address,old,addr); } } <commit_msg>note the opportunity for __swap_fetch_and_or for nmt triggers<commit_after>#include "rts/gc.h" namespace rts { using std::uint64_t; using std::unordered_set; using std::mutex; thread_local hec * hec::current; unordered_set<hec*> hecs; mutex gc_mutex; boost::lockfree::queue<gc_ptr> global_mark_queue[8]; void gc_ptr::lvb_slow_path(uint64_t * address, int trigger) { uint64_t old = addr; if (trigger | triggers::contraction) { unique = 0; } // this object was white, make it grey. if (trigger | triggers::nmt) { nmt = !nmt; if (unique) { // For anything locally unique we should walk the local subspace, chasing any unique references // and doing opportunistic graph reduction. When we consume k unique references we can // afford O(k) work. This means we'd act like a semispace copying collector for // objects that are known unique, and only ever pass to the marking system things // with multiple (potential) references. This also avoids crafting an indirection // upon enqueuing a unique closure for marking. It also generalizes Wadler's garbage collection // trick for eliminating certain forms of space leaks. // // This would be sufficient to handle things like a GRIN primitive for + being applied // to known integers, for instance. } else { if (space <= 8) hec::current->local_mark_queue[space].push(*this); else global_mark_queue[space - 8].push(*this); } } if (trigger | triggers::relocation) { // this page is actively being relocated. cooperate // grab a handle to the information about this page that is being relocated // try to claim this object // if we succeed, and it is not yet relocated, relocate it // regardless set addr equal to the new location } if (trigger | triggers::contraction && type == types::closure) { // we're actually going to write this answer into the _closure_ we made // addr = new_indirection(addr); } // TODO: use __sync_fetch_and_or / __sync_fetch_and_and to swap when trigger = triggers::nmt exactly __sync_val_compare_and_swap(address,old,addr); } } <|endoftext|>
<commit_before>// @(#)root/graf:$Id$ // Author: Olivier Couet /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include <stdlib.h> #include "Riostream.h" #include "TROOT.h" #include "TGaxisModLab.h" ClassImp(TGaxisModLab) /** \class TGaxisModLab \ingroup BasicGraphics TGaxis helper class used to store the modified labels. */ //////////////////////////////////////////////////////////////////////////////// /// TGaxisModLab default constructor. TGaxisModLab::TGaxisModLab() { fLabNum = 0; fTextAngle = -1.; fTextSize = -1.; fTextAlign = -1; fTextColor = -1; fTextFont = -1; fLabText = ""; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label number. void TGaxisModLab::SetLabNum(Int_t l) { if (l!=0) fLabNum = l; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label angle. void TGaxisModLab::SetAngle(Double_t a) { if (a>=0.) fTextAngle = a; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label size. void TGaxisModLab::SetSize(Double_t s) { if (s>=0.) fTextSize = s; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label alignment. void TGaxisModLab::SetAlign(Int_t a) { if (a>0) fTextAlign = a; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label color. void TGaxisModLab::SetColor(Int_t c) { if (c>0) fTextColor = c; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label font. void TGaxisModLab::SetFont(Int_t f) { if (f>0) fTextFont = 0; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label text. void TGaxisModLab::SetText(TString s) { fLabText = s; } //////////////////////////////////////////////////////////////////////////////// /// Stream an object of class TGaxisModLab. void TGaxisModLab::Streamer(TBuffer &R__b) { if (R__b.IsReading()) { UInt_t R__s, R__c; Version_t R__v = R__b.ReadVersion(&R__s, &R__c); if (R__v > 3) { R__b.ReadClassBuffer(TGaxisModLab::Class(), this, R__v, R__s, R__c); return; } } else { R__b.WriteClassBuffer(TGaxisModLab::Class(),this); } }<commit_msg>No need for a streamer<commit_after>// @(#)root/graf:$Id$ // Author: Olivier Couet /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include <stdlib.h> #include "Riostream.h" #include "TROOT.h" #include "TGaxisModLab.h" ClassImp(TGaxisModLab) /** \class TGaxisModLab \ingroup BasicGraphics TGaxis helper class used to store the modified labels. */ //////////////////////////////////////////////////////////////////////////////// /// TGaxisModLab default constructor. TGaxisModLab::TGaxisModLab() { fLabNum = 0; fTextAngle = -1.; fTextSize = -1.; fTextAlign = -1; fTextColor = -1; fTextFont = -1; fLabText = ""; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label number. void TGaxisModLab::SetLabNum(Int_t l) { if (l!=0) fLabNum = l; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label angle. void TGaxisModLab::SetAngle(Double_t a) { if (a>=0.) fTextAngle = a; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label size. void TGaxisModLab::SetSize(Double_t s) { if (s>=0.) fTextSize = s; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label alignment. void TGaxisModLab::SetAlign(Int_t a) { if (a>0) fTextAlign = a; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label color. void TGaxisModLab::SetColor(Int_t c) { if (c>0) fTextColor = c; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label font. void TGaxisModLab::SetFont(Int_t f) { if (f>0) fTextFont = 0; } //////////////////////////////////////////////////////////////////////////////// /// Set modified label text. void TGaxisModLab::SetText(TString s) { fLabText = s; } //////////////////////////////////////////////////////////////////////////////// /// Stream an object of class TGaxisModLab. void TGaxisModLab::Streamer(TBuffer &R__b) { }<|endoftext|>
<commit_before>#include "MainWindow.hpp" #include "ui_mainwindow.h" #include <QScrollBar> #include <iostream> #include "../framework/ModuleManager.hpp" using namespace std; using namespace uipf; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); // Create model modelStep = new QStringListModel(this); modelModule = new QStringListModel(this); modelTableParams = new ProcessingStepParams(this); modelTableInputs = new ProcessingStepInputs(this); // Glue model and view together ui->listProcessingSteps->setModel(modelStep); ui->tableParams->setModel(modelTableParams); ui->tableInputs->setModel(modelTableInputs); ui->comboModule->setModel(modelModule); // Add additional feature so that // we can manually modify the data in ListView // It may be triggered by hitting any key or double-click etc. ui->listProcessingSteps-> setEditTriggers(QAbstractItemView::AnyKeyPressed | QAbstractItemView::DoubleClicked); // react to changes in the ListView // TODO improve this to react on any selection change: http://stackoverflow.com/questions/2468514/how-to-get-the-selectionchange-event-in-qt connect(ui->listProcessingSteps, SIGNAL(clicked(const QModelIndex &)), this, SLOT(on_listProcessingSteps_activated(const QModelIndex &))); connect(modelStep, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &, const QVector<int> &)), this, SLOT(stepNameChanged())); // commands for menu bar createActions(); createMenus(); // sets undo and redo to inactive undoAct->setEnabled(false); redoAct->setEnabled(false); // sets run and stop to inactive runAct->setEnabled(false); stopAct->setEnabled(false); // sets save to inactive saveAct->setEnabled(false); setWindowTitle(tr("uipf")); setMinimumSize(400, 400); resize(480, 320); connect(Logger::instance(), SIGNAL (logEvent(const Logger::LogType&,const std::string&)), this, SLOT (on_appendToLog(const Logger::LogType&,const std::string&))); new_Data_Flow(); } void MainWindow::on_appendToLog(const Logger::LogType& eType,const std::string& strText) { // For colored Messages we need html :-/ QString strColor = (eType == Logger::WARNING ? "Blue" : eType == Logger::ERROR ? "Red" : "Green"); QString alertHtml = "<font color=\""+strColor+"\">" + QString(strText.c_str()) + "</font>"; ui->tbLog->appendHtml(alertHtml); ui->tbLog->verticalScrollBar()->setValue(ui->tbLog->verticalScrollBar()->maximum()); } MainWindow::~MainWindow() { delete ui; delete modelStep; delete modelModule; delete modelTableParams; delete modelTableInputs; } // sets a Module list void MainWindow::setModuleList(QStringList list){ modelModule->setStringList(list); } // Add button clicked // Adding at the end void MainWindow::on_addButton_clicked() { // Get the position of the selected item int row = modelStep->rowCount(); // Enable add one or more rows modelStep->insertRows(row,1); // Get the row for Edit mode QModelIndex index = modelStep->index(row); // Enable item selection and put it edit mode ui->listProcessingSteps->setCurrentIndex(index); configChanged(); QString newName = QString::fromStdString("new step"); modelStep->setData(index, newName, Qt::EditRole); ProcessingStep proSt; proSt.name = newName.toStdString(); conf_.addProcessingStep(proSt); ui->listProcessingSteps->edit(index); } void MainWindow::stepNameChanged(){ string newName = ui->listProcessingSteps->model()->data(ui->listProcessingSteps->currentIndex()).toString().toStdString(); int currentStepNumber = ui->listProcessingSteps->currentIndex().row(); string oldName = "new step"; int i=0; map<string, ProcessingStep> chain = conf_.getProcessingChain(); for (auto it = chain.begin(); it!=chain.end(); ++it) { if (i == currentStepNumber) { oldName = it->first; } } if(oldName.compare(newName) != 0){ configChanged(); ProcessingStep proStOld = conf_.getProcessingChain()[oldName]; ProcessingStep proStNew = conf_.getProcessingChain()[oldName]; proStNew.name = newName; conf_.removeProcessingStep(proStOld.name); conf_.addProcessingStep(proStNew); } } // Delete button clicked void MainWindow::on_deleteButton_clicked() { // Get the position modelStep->removeRows(ui->listProcessingSteps->currentIndex().row(),1); } // gets called when a processing step is selected void MainWindow::on_listProcessingSteps_activated(const QModelIndex & index) { map<string, ProcessingStep> chain = conf_.getProcessingChain(); string selectedStep = ui->listProcessingSteps->model()->data(ui->listProcessingSteps->currentIndex()).toString().toStdString(); cout << "selected " << selectedStep << endl; ProcessingStep proStep = chain[selectedStep]; modelTableParams->setProcessingStep(proStep); modelTableInputs->setProcessingStep(proStep); } void MainWindow::new_Data_Flow() { // run is now activated runAct->setEnabled(true); // configuration changed configChanged(); Configuration conf; conf_ = conf; QStringList list; modelStep->setStringList(list); } void MainWindow::load_Data_Flow() { // run is now activated runAct->setEnabled(true); // configuration changed configChanged(); QString fn = QFileDialog::getOpenFileName(this, tr("Open File..."),QString(), tr("YAML-Files (*.yaml);;All Files (*)")); currentFileName = fn.toStdString(); saveAct->setEnabled(true); conf_.load(currentFileName); // only for debug, print the loaded config conf_.print(); // set the names of the processing steps: QStringList list; map<string, ProcessingStep> chain = conf_.getProcessingChain(); for (auto it = chain.begin(); it!=chain.end(); ++it) { list << it->first.c_str(); } modelStep->setStringList(list); } void MainWindow::save_Data_Flow() { conf_.store(currentFileName); } void MainWindow::save_Data_Flow_as() { QString fn = QFileDialog::getSaveFileName(this, tr("Save as..."), QString(), tr("YAML files (*.yaml);;All Files (*)")); if (! (fn.endsWith(".yaml", Qt::CaseInsensitive)) ) fn += ".yaml"; // default currentFileName = fn.toStdString(); saveAct->setEnabled(true); conf_.store(fn.toStdString()); } void MainWindow::about() { QMessageBox::about(this, tr("About uipf"), tr("This application allows the user by using given library of modules to create his own configuration and to execute it. Created by the project: 'A Unified Framework for Digital Image Processing in Computer Vision and Remote Sensing' at Technische Universitaet Berlin. Version 1.0")); } // sets the current configuration to the previous one void MainWindow::undo() { if(!undoStack.empty()){ // move the current config to the redo stack redoStack.push(conf_); // get the last config stored in undo stack conf_ = undoStack.top(); // delete the last config from the undo stack undoStack.pop(); // set the names of the processing steps: QStringList list; map<string, ProcessingStep> chain = conf_.getProcessingChain(); for (auto it = chain.begin(); it!=chain.end(); ++it) { list << it->first.c_str(); } modelStep->setStringList(list); // set the undo/redo in the menu bar gray if inactive or black, if active redoAct->setEnabled(true); if(!undoStack.empty()){ undoAct->setEnabled(true); } else{ undoAct->setEnabled(false); } } } // sets the current configuration back to the next one void MainWindow::redo() { if(!redoStack.empty()){ // move the current config to the undo stack undoStack.push(conf_); // get the last config stored in redo stack conf_ = redoStack.top(); // delete the last config from the redo stack redoStack.pop(); // set the names of the processing steps: QStringList list; map<string, ProcessingStep> chain = conf_.getProcessingChain(); for (auto it = chain.begin(); it!=chain.end(); ++it) { list << it->first.c_str(); } modelStep->setStringList(list); // set the undo/redo in the menu bar gray if inactive or black, if active undoAct->setEnabled(true); if(!redoStack.empty()){ redoAct->setEnabled(true); } else{ redoAct->setEnabled(false); } } } // feeds the undo and redo stacks with the current configs // has to be called BEFORE the config has changed! void MainWindow::configChanged(){ // configuration changed undoStack.push(conf_); while(! redoStack.empty()){ redoStack.pop(); } // set the undo to active and redo to inactive undoAct->setEnabled(true); redoAct->setEnabled(false); } // run the current configuration void MainWindow::run() { // stop is now activated stopAct->setEnabled(true); ModuleManager mm; mm.run(conf_); // TODO inactivate stop, when finished! } void MainWindow::stop() { // TODO } void MainWindow::createActions() { newAct = new QAction(tr("&New"), this); newAct->setShortcuts(QKeySequence::New); newAct->setStatusTip(tr("Create a new configuration")); connect(newAct, SIGNAL(triggered()), this, SLOT(new_Data_Flow())); openAct = new QAction(tr("&Open..."), this); openAct->setShortcuts(QKeySequence::Open); openAct->setStatusTip(tr("Open an existing configuration")); connect(openAct, SIGNAL(triggered()), this, SLOT(load_Data_Flow())); saveAct = new QAction(tr("&Save"), this); saveAct->setShortcuts(QKeySequence::Save); saveAct->setStatusTip(tr("Save the configuration to disk")); connect(saveAct, SIGNAL(triggered()), this, SLOT(save_Data_Flow())); saveAsAct = new QAction(tr("Save &as..."), this); saveAsAct->setShortcuts(QKeySequence::SaveAs); saveAsAct->setStatusTip(tr("Save the configuration to disk")); connect(saveAsAct, SIGNAL(triggered()), this, SLOT(save_Data_Flow_as())); exitAct = new QAction(tr("E&xit"), this); exitAct->setShortcuts(QKeySequence::Quit); exitAct->setStatusTip(tr("Exit the application")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); aboutAct = new QAction(tr("&About"), this); aboutAct->setShortcuts(QKeySequence::WhatsThis); aboutAct->setStatusTip(tr("Show the application's About box")); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); undoAct = new QAction(tr("&Undo"), this); undoAct->setShortcuts(QKeySequence::Undo); undoAct->setStatusTip(tr("Undo the last operation")); connect(undoAct, SIGNAL(triggered()), this, SLOT(undo())); redoAct = new QAction(tr("&Redo"), this); redoAct->setShortcuts(QKeySequence::Redo); redoAct->setStatusTip(tr("Redo the last operation")); connect(redoAct, SIGNAL(triggered()), this, SLOT(redo())); runAct = new QAction(tr("&Run"), this); runAct->setStatusTip(tr("Run the configuration")); connect(runAct, SIGNAL(triggered()), this, SLOT(run())); stopAct = new QAction(tr("&Stop"), this); stopAct->setStatusTip(tr("Stop the execution of the configuration")); connect(stopAct, SIGNAL(triggered()), this, SLOT(stop())); } void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(newAct); fileMenu->addAction(openAct); fileMenu->addAction(saveAct); fileMenu->addAction(saveAsAct); fileMenu->addSeparator(); fileMenu->addAction(exitAct); editMenu = menuBar()->addMenu(tr("&Edit")); editMenu->addAction(undoAct); editMenu->addAction(redoAct); configMenu = menuBar()->addMenu(tr("&Configuration")); configMenu->addAction(runAct); configMenu->addAction(stopAct); helpMenu = menuBar()->addMenu(tr("&Help")); helpMenu->addAction(aboutAct); } <commit_msg>GUI window enhancements<commit_after>#include "MainWindow.hpp" #include "ui_mainwindow.h" #include <QScrollBar> #include <iostream> #include "../framework/ModuleManager.hpp" using namespace std; using namespace uipf; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow){ ui->setupUi(this); // Create model modelStep = new QStringListModel(this); modelModule = new QStringListModel(this); modelTableParams = new ProcessingStepParams(this); modelTableInputs = new ProcessingStepInputs(this); // Glue model and view together ui->listProcessingSteps->setModel(modelStep); ui->tableParams->setModel(modelTableParams); ui->tableInputs->setModel(modelTableInputs); ui->comboModule->setModel(modelModule); // Add additional feature so that we can manually modify the data in ListView (List of Step Names) // It may be triggered by hitting any key or double-click etc. ui->listProcessingSteps-> setEditTriggers(QAbstractItemView::AnyKeyPressed |QAbstractItemView::DoubleClicked); // react to changes in the ListView // TODO improve this to react on any selection change: http://stackoverflow.com/questions/2468514/how-to-get-the-selectionchange-event-in-qt connect(ui->listProcessingSteps, SIGNAL(clicked(const QModelIndex &)), this, SLOT(on_listProcessingSteps_activated(const QModelIndex &))); // react to changes in the entries of the ListView connect(modelStep, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &, const QVector<int> &)), this, SLOT(stepNameChanged())); // commands for menu bar createActions(); createMenus(); // sets undo and redo to inactive undoAct->setEnabled(false); redoAct->setEnabled(false); // sets run and stop to inactive runAct->setEnabled(false); stopAct->setEnabled(false); // sets save to inactive saveAct->setEnabled(false); // window settings setWindowTitle(tr("uipf")); setMinimumSize(400, 400); resize(480, 320); // logger connect(Logger::instance(), SIGNAL (logEvent(const Logger::LogType&,const std::string&)), this, SLOT (on_appendToLog(const Logger::LogType&,const std::string&))); // when starting the program, at first always start a new Data Flow new_Data_Flow(); } // destructor MainWindow::~MainWindow() { delete ui; delete modelStep; delete modelModule; delete modelTableParams; delete modelTableInputs; } // sets a Module list /* list list of all availanle modules */ void MainWindow::setModuleList(QStringList list){ modelModule->setStringList(list); } // From here: SLOTS ------------------------------------------------------------------------------------------------------------------------------- // TODO: comment! void MainWindow::on_appendToLog(const Logger::LogType& eType,const std::string& strText) { // For colored Messages we need html :-/ QString strColor = (eType == Logger::WARNING ? "Blue" : eType == Logger::ERROR ? "Red" : "Green"); QString alertHtml = "<font color=\""+strColor+"\">" + QString(strText.c_str()) + "</font>"; ui->tbLog->appendHtml(alertHtml); ui->tbLog->verticalScrollBar()->setValue(ui->tbLog->verticalScrollBar()->maximum()); } // Add button clicked - allows to add a new Processing Step // Step is always added at the end of the list void MainWindow::on_addButton_clicked() { // Get the position of the selected item int row = modelStep->rowCount(); // Enable add one or more rows modelStep->insertRows(row,1); // Get the row for Edit mode QModelIndex index = modelStep->index(row); // Enable item selection and put it edit mode ui->listProcessingSteps->setCurrentIndex(index); // before config changes, we need to update our redo/undo stacks configChanged(); // set default name "new step i" bool nameAlreadyExists = true; int i=0; string name = "new step " + std::to_string(i); map<string, ProcessingStep> chain = conf_.getProcessingChain(); while(nameAlreadyExists){ if (chain.count(name)){ i++; name = "new step " + std::to_string(i); } else { nameAlreadyExists = false; } } QString newName = QString::fromStdString(name); modelStep->setData(index, newName, Qt::EditRole); // add new Processing Step to the configuration chain ProcessingStep proSt; proSt.name = newName.toStdString(); conf_.addProcessingStep(proSt); // the name can be changed ui->listProcessingSteps->edit(index); } // updates the name of a step, when changed void MainWindow::stepNameChanged(){ // get the new name string newName = ui->listProcessingSteps->model()->data(ui->listProcessingSteps->currentIndex()).toString().toStdString(); int currentStepNumber = ui->listProcessingSteps->currentIndex().row(); // get the old name by looking at the index of the selected row string oldName; int i=0; map<string, ProcessingStep> chain = conf_.getProcessingChain(); for (auto it = chain.begin(); it!=chain.end(); ++it) { if (i == currentStepNumber) { oldName = it->first; } i++; } // TODO check whether the new name does not already exist // if the name was really changed if(oldName.compare(newName) != 0){ configChanged(); cout << "map counts old name: " << conf_.getProcessingChain().count(oldName) << endl; // create the processing step with the old name and the processing step with the new name ProcessingStep proStOld = conf_.getProcessingChain()[oldName]; ProcessingStep proStNew = conf_.getProcessingChain()[oldName]; proStNew.name = newName; cout << "old name: " << proStOld.name << endl; cout << "new name: " << proStNew.name << endl; // remove the processing step with the old name and add the processing step with the new name conf_.removeProcessingStep(proStOld.name); conf_.addProcessingStep(proStNew); } } // Delete button clicked void MainWindow::on_deleteButton_clicked() { // Get the position modelStep->removeRows(ui->listProcessingSteps->currentIndex().row(),1); } // gets called when a processing step is selected void MainWindow::on_listProcessingSteps_activated(const QModelIndex & index) { map<string, ProcessingStep> chain = conf_.getProcessingChain(); string selectedStep = ui->listProcessingSteps->model()->data(ui->listProcessingSteps->currentIndex()).toString().toStdString(); cout << "selected " << selectedStep << endl; ProcessingStep proStep = chain[selectedStep]; modelTableParams->setProcessingStep(proStep); modelTableInputs->setProcessingStep(proStep); } void MainWindow::new_Data_Flow() { // save is not activated saveAct->setEnabled(false); // run is now activated runAct->setEnabled(true); currentFileName = "newFile"; setWindowTitle(tr("newFile - uipf")); // configuration changed configChanged(); Configuration conf; conf_ = conf; QStringList list; modelStep->setStringList(list); } void MainWindow::load_Data_Flow() { // run is now activated runAct->setEnabled(true); // configuration changed configChanged(); QString fn = QFileDialog::getOpenFileName(this, tr("Open File..."),QString(), tr("YAML-Files (*.yaml);;All Files (*)")); currentFileName = fn.toStdString(); string winTitle = currentFileName + " - uipf"; setWindowTitle(tr(winTitle.c_str())); saveAct->setEnabled(true); conf_.load(currentFileName); // only for debug, print the loaded config conf_.print(); // set the names of the processing steps: QStringList list; map<string, ProcessingStep> chain = conf_.getProcessingChain(); for (auto it = chain.begin(); it!=chain.end(); ++it) { list << it->first.c_str(); } modelStep->setStringList(list); } // only possible, if the configuration has already been stored in some file void MainWindow::save_Data_Flow() { conf_.store(currentFileName); } // by default the name is the current name of the configuration file // the suffix of the file is always set to '.yaml' // the currently opened configuration switches to the stored file void MainWindow::save_Data_Flow_as() { QString fn = QFileDialog::getSaveFileName(this, tr("Save as..."), QString::fromStdString(currentFileName), tr("YAML files (*.yaml);;All Files (*)")); if (! (fn.endsWith(".yaml", Qt::CaseInsensitive)) ) fn += ".yaml"; // default currentFileName = fn.toStdString(); string winTitle = currentFileName + " - uipf"; setWindowTitle(tr(winTitle.c_str())); saveAct->setEnabled(true); conf_.store(fn.toStdString()); } void MainWindow::about() { QMessageBox::about(this, tr("About uipf"), tr("This application allows the user by using given library of modules to create his own configuration and to execute it. Created by the project: 'A Unified Framework for Digital Image Processing in Computer Vision and Remote Sensing' at Technische Universitaet Berlin. Version 1.0")); } // sets the current configuration to the previous one void MainWindow::undo() { if(!undoStack.empty()){ // move the current config to the redo stack redoStack.push(conf_); // get the last config stored in undo stack conf_ = undoStack.top(); // delete the last config from the undo stack undoStack.pop(); // set the names of the processing steps: QStringList list; map<string, ProcessingStep> chain = conf_.getProcessingChain(); for (auto it = chain.begin(); it!=chain.end(); ++it) { list << it->first.c_str(); } modelStep->setStringList(list); // set the undo/redo in the menu bar gray if inactive or black, if active redoAct->setEnabled(true); if(!undoStack.empty()){ undoAct->setEnabled(true); } else{ undoAct->setEnabled(false); } } } // sets the current configuration back to the next one void MainWindow::redo() { if(!redoStack.empty()){ // move the current config to the undo stack undoStack.push(conf_); // get the last config stored in redo stack conf_ = redoStack.top(); // delete the last config from the redo stack redoStack.pop(); // set the names of the processing steps: QStringList list; map<string, ProcessingStep> chain = conf_.getProcessingChain(); for (auto it = chain.begin(); it!=chain.end(); ++it) { list << it->first.c_str(); } modelStep->setStringList(list); // set the undo/redo in the menu bar gray if inactive or black, if active undoAct->setEnabled(true); if(!redoStack.empty()){ redoAct->setEnabled(true); } else{ redoAct->setEnabled(false); } } } // feeds the undo and redo stacks with the current configs // has to be called BEFORE the config has changed! void MainWindow::configChanged(){ // configuration changed undoStack.push(conf_); while(! redoStack.empty()){ redoStack.pop(); } // set the undo to active and redo to inactive undoAct->setEnabled(true); redoAct->setEnabled(false); } // run the current configuration void MainWindow::run() { // stop is now activated stopAct->setEnabled(true); ModuleManager mm; mm.run(conf_); // TODO inactivate stop, when finished! } void MainWindow::stop() { // TODO } // Up to here: SLOTS ------------------------------------------------------------------------------------------------------------------------------- void MainWindow::createActions() { newAct = new QAction(tr("&New"), this); newAct->setShortcuts(QKeySequence::New); newAct->setStatusTip(tr("Create a new configuration")); connect(newAct, SIGNAL(triggered()), this, SLOT(new_Data_Flow())); openAct = new QAction(tr("&Open..."), this); openAct->setShortcuts(QKeySequence::Open); openAct->setStatusTip(tr("Open an existing configuration")); connect(openAct, SIGNAL(triggered()), this, SLOT(load_Data_Flow())); saveAct = new QAction(tr("&Save"), this); saveAct->setShortcuts(QKeySequence::Save); saveAct->setStatusTip(tr("Save the configuration to disk")); connect(saveAct, SIGNAL(triggered()), this, SLOT(save_Data_Flow())); saveAsAct = new QAction(tr("Save &as..."), this); saveAsAct->setShortcuts(QKeySequence::SaveAs); saveAsAct->setStatusTip(tr("Save the configuration to disk")); connect(saveAsAct, SIGNAL(triggered()), this, SLOT(save_Data_Flow_as())); exitAct = new QAction(tr("E&xit"), this); exitAct->setShortcuts(QKeySequence::Quit); exitAct->setStatusTip(tr("Exit the application")); connect(exitAct, SIGNAL(triggered()), this, SLOT(close())); aboutAct = new QAction(tr("&About"), this); aboutAct->setShortcuts(QKeySequence::WhatsThis); aboutAct->setStatusTip(tr("Show the application's About box")); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); undoAct = new QAction(tr("&Undo"), this); undoAct->setShortcuts(QKeySequence::Undo); undoAct->setStatusTip(tr("Undo the last operation")); connect(undoAct, SIGNAL(triggered()), this, SLOT(undo())); redoAct = new QAction(tr("&Redo"), this); redoAct->setShortcuts(QKeySequence::Redo); redoAct->setStatusTip(tr("Redo the last operation")); connect(redoAct, SIGNAL(triggered()), this, SLOT(redo())); runAct = new QAction(tr("&Run"), this); runAct->setStatusTip(tr("Run the configuration")); connect(runAct, SIGNAL(triggered()), this, SLOT(run())); stopAct = new QAction(tr("&Stop"), this); stopAct->setStatusTip(tr("Stop the execution of the configuration")); connect(stopAct, SIGNAL(triggered()), this, SLOT(stop())); } void MainWindow::createMenus() { fileMenu = menuBar()->addMenu(tr("&File")); fileMenu->addAction(newAct); fileMenu->addAction(openAct); fileMenu->addAction(saveAct); fileMenu->addAction(saveAsAct); fileMenu->addSeparator(); fileMenu->addAction(exitAct); editMenu = menuBar()->addMenu(tr("&Edit")); editMenu->addAction(undoAct); editMenu->addAction(redoAct); configMenu = menuBar()->addMenu(tr("&Configuration")); configMenu->addAction(runAct); configMenu->addAction(stopAct); helpMenu = menuBar()->addMenu(tr("&Help")); helpMenu->addAction(aboutAct); } <|endoftext|>
<commit_before>#include <windows.h> #include <assert.h> #include <stdio.h> #include "game.h" #include "game_memory.h" #include "game_basictypes.h" #include "win32_debug.h" LRESULT CALLBACK GameWindowCallback(HWND, UINT, WPARAM, LPARAM); gamestate_t GameState = {0}; uint MapFile(const char *Filename, gamememory_t *Memory) { // If Memory is null or of size zero, just return file's size LARGE_INTEGER FileSize = {0}; HANDLE FileHandle = CreateFile(Filename, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (FileHandle == INVALID_HANDLE_VALUE) { assert(!"File not found"); } GetFileSizeEx(FileHandle, &FileSize); if (Memory && Memory->Size >= FileSize.QuadPart) { char *Source = (char *)malloc(FileSize.QuadPart); DWORD Read; ReadFile(FileHandle, Source, FileSize.QuadPart, &Read, 0); // TODO: MemoryType_char isn't quite right, but there's no datatype for this CopyMemory(Memory->Data, Source, FileSize.QuadPart); free(Source); } else { assert(!"File too big"); } CloseHandle(FileHandle); return FileSize.QuadPart; } static WNDCLASSEX RegisterGameWindowClass(HINSTANCE instance) { WNDCLASSEX cls = {0}; cls.cbSize = sizeof(WNDCLASSEX); cls.style = CS_HREDRAW | CS_VREDRAW; cls.lpfnWndProc = GameWindowCallback; cls.hInstance = instance; cls.lpszClassName = GAME_TITLE; cls.hIcon = LoadIcon(0, IDI_APPLICATION); RegisterClassEx(&cls); return cls; } static void AllocateGameMemory(gamestate_t *GameState, uint64 Size) { SYSTEM_INFO SystemInfo; GetSystemInfo(&SystemInfo); LOGF("Allocating %d. Page size of computer is %d.", Size, SystemInfo.dwPageSize); GameState->Memory.Size = Size; GameState->Memory.Data = VirtualAlloc(0, Size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); } static void DeallocateGameMemory(gamestate_t *GameState) { VirtualFree(GameState->Memory.Data, 0, MEM_RELEASE); GameState->Memory.Size = 0; } static HWND CreateGameWindow() { HWND wnd = {0}; HINSTANCE instance = GetModuleHandleA(0); RegisterGameWindowClass(instance); wnd = CreateWindowA(GAME_TITLE, GAME_TITLE, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, // x & y CW_USEDEFAULT, CW_USEDEFAULT, // width & height 0, 0, instance, 0); return wnd; } static gameapi_t LoadGame() { gameapi_t api = {0}; #if defined(MULTIMA_DEBUG) api.Handle = LoadLibraryA("game_debug.dll"); #else api.Handle = LoadLibraryA("game.dll"); #endif assert(api.Handle != 0); api.Log = Log; api.MapFile = MapFile; api.RunFrame = (runframe_f) GetProcAddress((HMODULE)api.Handle, "RunFrame"); assert(api.RunFrame != 0); return api; } static void UnloadGame(gameapi_t *api) { if (api->Handle) { FreeLibrary((HMODULE) api->Handle); api->Handle = 0; } FreeConsole(); } static LRESULT GameWindowCallback(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_ERASEBKGND: return 1; case WM_ACTIVATE: GameState.Running = (LOWORD(wParam) != WA_INACTIVE); return 0; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(wnd, msg, wParam, lParam); } static void UnloadScreenBuffer(gamestate_t *GameState) { VirtualFree(GameState->DrawBuffer.Buffer, 0, MEM_RELEASE); GameState->DrawBuffer.Buffer = 0; } static BITMAPINFO bmi = {0}; static void InitScreenBuffer(gamestate_t *GameState, HWND hwnd) { bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = GameState->DrawBuffer.Width; bmi.bmiHeader.biHeight = -GameState->DrawBuffer.Height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; // 4 is bytes per pixel (32 bits) const int BufferSize = GameState->DrawBuffer.Width * GameState->DrawBuffer.Height * 4; LPVOID memory = VirtualAlloc(0, BufferSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); GameState->DrawBuffer.Buffer = memory; } static void FetchInput(gameinput_t *Input) { #define CHECK(Vkey, Var) \ { \ SHORT Result = GetAsyncKeyState(Vkey); \ Input->Var = (Result < 0); \ } CHECK(VK_SHIFT, Shift); CHECK(VK_CONTROL, Ctrl); CHECK(VK_LEFT, Left); CHECK(VK_RIGHT, Right); CHECK(VK_UP, Up); CHECK(VK_DOWN, Down); #undef CHECK } int WinMain(HINSTANCE instance, HINSTANCE prev, LPSTR cmd, int cmdshow) { gameapi_t GameApi = LoadGame(); HWND hwnd = CreateGameWindow(); ShowWindow(hwnd, cmdshow); UpdateWindow(hwnd); MSG msg = {0}; GameState.DrawBuffer.Width = 640; GameState.DrawBuffer.Height = 480; InitScreenBuffer(&GameState, hwnd); const uint MemorySize = MEGABYTES(32); AllocateGameMemory(&GameState, MemorySize); float Scale = 1.0f; LARGE_INTEGER StartCounter = {0}; uint64 FrameTargetMS = 16; // 60 FPS timeBeginPeriod(1); LARGE_INTEGER Frequency; QueryPerformanceFrequency(&Frequency); HDC hdc = GetDC(hwnd); bool GameRunning = true; while (GameRunning) { QueryPerformanceCounter(&StartCounter); while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { switch (msg.message) { case WM_QUIT: GameRunning = false; break; default: TranslateMessage(&msg); DispatchMessage(&msg); break; } } FetchInput(&GameState.Input); #if defined(MULTIMA_DEBUG) ClearLog(); #endif GameApi.RunFrame(&GameApi, &GameState); const int res = StretchDIBits( hdc, 0, 0, (uint)(Scale * GameState.DrawBuffer.Width), (uint)(Scale * GameState.DrawBuffer.Height), 0, 0, GameState.DrawBuffer.Width, GameState.DrawBuffer.Height, GameState.DrawBuffer.Buffer, &bmi, DIB_RGB_COLORS, SRCCOPY ); LARGE_INTEGER EndCounter = {0}; QueryPerformanceCounter(&EndCounter); GameState.DeltaTime = EndCounter.QuadPart - StartCounter.QuadPart; uint64 FrameTimeMS = (1000 * GameState.DeltaTime) / Frequency.QuadPart; if (FrameTimeMS < FrameTargetMS) { Sleep(FrameTargetMS - FrameTimeMS); } char WindowTitle[128] = {0}; _snprintf(WindowTitle, sizeof(WindowTitle), "%s - %3d ms / %4d ticks", GAME_TITLE, FrameTimeMS, GameState.DeltaTime); SetWindowText(hwnd, WindowTitle); } UnloadGame(&GameApi); UnloadScreenBuffer(&GameState); DeallocateGameMemory(&GameState); timeEndPeriod(1); return 0; } <commit_msg>Disabled Sleep in platform layer for now<commit_after>#include <windows.h> #include <assert.h> #include <stdio.h> #include "game.h" #include "game_memory.h" #include "game_basictypes.h" #include "win32_debug.h" LRESULT CALLBACK GameWindowCallback(HWND, UINT, WPARAM, LPARAM); gamestate_t GameState = {0}; uint MapFile(const char *Filename, gamememory_t *Memory) { // If Memory is null or of size zero, just return file's size LARGE_INTEGER FileSize = {0}; HANDLE FileHandle = CreateFile(Filename, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (FileHandle == INVALID_HANDLE_VALUE) { assert(!"File not found"); } GetFileSizeEx(FileHandle, &FileSize); if (Memory && Memory->Size >= FileSize.QuadPart) { char *Source = (char *)malloc(FileSize.QuadPart); DWORD Read; ReadFile(FileHandle, Source, FileSize.QuadPart, &Read, 0); // TODO: MemoryType_char isn't quite right, but there's no datatype for this CopyMemory(Memory->Data, Source, FileSize.QuadPart); free(Source); } else { assert(!"File too big"); } CloseHandle(FileHandle); return FileSize.QuadPart; } static WNDCLASSEX RegisterGameWindowClass(HINSTANCE instance) { WNDCLASSEX cls = {0}; cls.cbSize = sizeof(WNDCLASSEX); cls.style = CS_HREDRAW | CS_VREDRAW; cls.lpfnWndProc = GameWindowCallback; cls.hInstance = instance; cls.lpszClassName = GAME_TITLE; cls.hIcon = LoadIcon(0, IDI_APPLICATION); RegisterClassEx(&cls); return cls; } static void AllocateGameMemory(gamestate_t *GameState, uint64 Size) { SYSTEM_INFO SystemInfo; GetSystemInfo(&SystemInfo); LOGF("Allocating %d. Page size of computer is %d.", Size, SystemInfo.dwPageSize); GameState->Memory.Size = Size; GameState->Memory.Data = VirtualAlloc(0, Size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); } static void DeallocateGameMemory(gamestate_t *GameState) { VirtualFree(GameState->Memory.Data, 0, MEM_RELEASE); GameState->Memory.Size = 0; } static HWND CreateGameWindow() { HWND wnd = {0}; HINSTANCE instance = GetModuleHandleA(0); RegisterGameWindowClass(instance); wnd = CreateWindowA(GAME_TITLE, GAME_TITLE, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, // x & y CW_USEDEFAULT, CW_USEDEFAULT, // width & height 0, 0, instance, 0); return wnd; } static gameapi_t LoadGame() { gameapi_t api = {0}; #if defined(MULTIMA_DEBUG) api.Handle = LoadLibraryA("game_debug.dll"); #else api.Handle = LoadLibraryA("game.dll"); #endif assert(api.Handle != 0); api.Log = Log; api.MapFile = MapFile; api.RunFrame = (runframe_f) GetProcAddress((HMODULE)api.Handle, "RunFrame"); assert(api.RunFrame != 0); return api; } static void UnloadGame(gameapi_t *api) { if (api->Handle) { FreeLibrary((HMODULE) api->Handle); api->Handle = 0; } FreeConsole(); } static LRESULT GameWindowCallback(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_ERASEBKGND: return 1; case WM_ACTIVATE: GameState.Running = (LOWORD(wParam) != WA_INACTIVE); return 0; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(wnd, msg, wParam, lParam); } static void UnloadScreenBuffer(gamestate_t *GameState) { VirtualFree(GameState->DrawBuffer.Buffer, 0, MEM_RELEASE); GameState->DrawBuffer.Buffer = 0; } static BITMAPINFO bmi = {0}; static void InitScreenBuffer(gamestate_t *GameState, HWND hwnd) { bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bmi.bmiHeader.biWidth = GameState->DrawBuffer.Width; bmi.bmiHeader.biHeight = -GameState->DrawBuffer.Height; bmi.bmiHeader.biPlanes = 1; bmi.bmiHeader.biBitCount = 32; bmi.bmiHeader.biCompression = BI_RGB; // 4 is bytes per pixel (32 bits) const int BufferSize = GameState->DrawBuffer.Width * GameState->DrawBuffer.Height * 4; LPVOID memory = VirtualAlloc(0, BufferSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); GameState->DrawBuffer.Buffer = memory; } static void FetchInput(gameinput_t *Input) { #define CHECK(Vkey, Var) \ { \ SHORT Result = GetAsyncKeyState(Vkey); \ Input->Var = (Result < 0); \ } CHECK(VK_SHIFT, Shift); CHECK(VK_CONTROL, Ctrl); CHECK(VK_LEFT, Left); CHECK(VK_RIGHT, Right); CHECK(VK_UP, Up); CHECK(VK_DOWN, Down); #undef CHECK } int WinMain(HINSTANCE instance, HINSTANCE prev, LPSTR cmd, int cmdshow) { gameapi_t GameApi = LoadGame(); HWND hwnd = CreateGameWindow(); ShowWindow(hwnd, cmdshow); UpdateWindow(hwnd); MSG msg = {0}; GameState.DrawBuffer.Width = 640; GameState.DrawBuffer.Height = 480; InitScreenBuffer(&GameState, hwnd); const uint MemorySize = MEGABYTES(32); AllocateGameMemory(&GameState, MemorySize); float Scale = 1.0f; LARGE_INTEGER StartCounter = {0}; uint64 FrameTargetMS = 16; // 60 FPS timeBeginPeriod(1); LARGE_INTEGER Frequency; QueryPerformanceFrequency(&Frequency); HDC hdc = GetDC(hwnd); bool GameRunning = true; while (GameRunning) { QueryPerformanceCounter(&StartCounter); while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { switch (msg.message) { case WM_QUIT: GameRunning = false; break; default: TranslateMessage(&msg); DispatchMessage(&msg); break; } } FetchInput(&GameState.Input); #if defined(MULTIMA_DEBUG) ClearLog(); #endif GameApi.RunFrame(&GameApi, &GameState); const int res = StretchDIBits( hdc, 0, 0, (uint)(Scale * GameState.DrawBuffer.Width), (uint)(Scale * GameState.DrawBuffer.Height), 0, 0, GameState.DrawBuffer.Width, GameState.DrawBuffer.Height, GameState.DrawBuffer.Buffer, &bmi, DIB_RGB_COLORS, SRCCOPY ); LARGE_INTEGER EndCounter = {0}; QueryPerformanceCounter(&EndCounter); GameState.DeltaTime = EndCounter.QuadPart - StartCounter.QuadPart; uint64 FrameTimeMS = (1000 * GameState.DeltaTime) / Frequency.QuadPart; #if 0 // TODO: Enabling this makes the game stutter. Find a better alternative (vsync?) if (FrameTimeMS < FrameTargetMS) { Sleep(FrameTargetMS - FrameTimeMS); } #endif char WindowTitle[128] = {0}; _snprintf(WindowTitle, sizeof(WindowTitle), "%s - %3d ms / %4d ticks", GAME_TITLE, FrameTimeMS, GameState.DeltaTime); SetWindowText(hwnd, WindowTitle); } UnloadGame(&GameApi); UnloadScreenBuffer(&GameState); DeallocateGameMemory(&GameState); timeEndPeriod(1); return 0; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_VCL_INC_IOS_IOSINST_HXX #define INCLUDED_VCL_INC_IOS_IOSINST_HXX #include <premac.h> #include <CoreGraphics/CoreGraphics.h> #include <postmac.h> #include <tools/link.hxx> #include "headless/svpinst.hxx" #include "headless/svpframe.hxx" class IosSalFrame; class IosSalInstance : public SvpSalInstance { public: IosSalInstance( SalYieldMutex *pMutex ); virtual ~IosSalInstance(); static IosSalInstance *getInstance(); virtual SalSystem* CreateSalSystem() SAL_OVERRIDE; void GetWorkArea( Rectangle& rRect ); SalFrame* CreateFrame( SalFrame* pParent, sal_uLong nStyle ); SalFrame* CreateChildFrame( SystemParentData* pParent, sal_uLong nStyle ); SalFrame *getFocusFrame() const; }; #endif // INCLUDED_VCL_INC_IOS_IOSINST_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>WaE: -Winconsistent-missing-override<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_VCL_INC_IOS_IOSINST_HXX #define INCLUDED_VCL_INC_IOS_IOSINST_HXX #include <premac.h> #include <CoreGraphics/CoreGraphics.h> #include <postmac.h> #include <tools/link.hxx> #include "headless/svpinst.hxx" #include "headless/svpframe.hxx" class IosSalFrame; class IosSalInstance : public SvpSalInstance { public: IosSalInstance( SalYieldMutex *pMutex ); virtual ~IosSalInstance(); static IosSalInstance *getInstance(); virtual SalSystem* CreateSalSystem() SAL_OVERRIDE; void GetWorkArea( Rectangle& rRect ); SalFrame* CreateFrame( SalFrame* pParent, sal_uLong nStyle ) SAL_OVERRIDE; SalFrame* CreateChildFrame( SystemParentData* pParent, sal_uLong nStyle ) SAL_OVERRIDE; SalFrame *getFocusFrame() const; }; #endif // INCLUDED_VCL_INC_IOS_IOSINST_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pngread.hxx,v $ * $Revision: 1.3 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SV_PNGREAD_HXX #define _SV_PNGREAD_HXX #include <vcl/dllapi.h> #include <vcl/bitmapex.hxx> #include <vector> // ------------- // - PNGReader - // ------------- namespace vcl { class PNGReaderImpl; class VCL_DLLPUBLIC PNGReader { PNGReaderImpl* mpImpl; public: /* the PNG chunks are read within the c'tor, so the stream will be positioned at the end of the PNG */ PNGReader( SvStream& rStm ); ~PNGReader(); BitmapEx Read(); // retrieve every chunk that resides inside the PNG struct ChunkData { sal_uInt32 nType; std::vector< sal_uInt8 > aData; }; const std::vector< ChunkData >& GetChunks() const; // TODO: when incompatible changes are possible again // the preview size hint should be redone static void SetPreviewSizeHint( const Size& r ) { aPreviewSizeHint = r; } static void DisablePreviewMode() { aPreviewSizeHint = Size(0,0); } private: static Size aPreviewSizeHint; }; } #endif // _SV_PNGREAD_HXX <commit_msg>INTEGRATION: CWS vcl89 (1.3.16); FILE MERGED 2008/05/07 12:08:20 pl 1.3.16.1: #i89111# remove static member abomination<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pngread.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SV_PNGREAD_HXX #define _SV_PNGREAD_HXX #include <vcl/dllapi.h> #include <vcl/bitmapex.hxx> #include <vector> // ------------- // - PNGReader - // ------------- namespace vcl { class PNGReaderImpl; class VCL_DLLPUBLIC PNGReader { PNGReaderImpl* mpImpl; public: /* the PNG chunks are read within the c'tor, so the stream will be positioned at the end of the PNG */ PNGReader( SvStream& rStm ); ~PNGReader(); /* an empty preview size hint (=default) will read the whole image */ BitmapEx Read( const Size& i_rPreviewHint = Size() ); // retrieve every chunk that resides inside the PNG struct ChunkData { sal_uInt32 nType; std::vector< sal_uInt8 > aData; }; const std::vector< ChunkData >& GetChunks() const; }; } #endif // _SV_PNGREAD_HXX <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: IBM Corporation * * Copyright: 2008 by IBM Corporation * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ /************************************************************************* * @file * For LWP filter architecture prototype ************************************************************************/ #include "lwplaypiece.hxx" #include "lwpfilehdr.hxx" LwpRotor::LwpRotor() : m_nRotation(0) {} LwpRotor::~LwpRotor() {} void LwpRotor:: Read(LwpObjectStream *pStrm) { m_nRotation = pStrm->QuickReadInt16(); } LwpLayoutGeometry::LwpLayoutGeometry(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) , m_nWidth(0) , m_nHeight(0) , m_ContentOrientation(0) {} LwpLayoutGeometry::~LwpLayoutGeometry() {} void LwpLayoutGeometry::Read() { LwpVirtualPiece::Read(); if(LwpFileHeader::m_nFileRevision >= 0x000B) { m_nWidth = m_pObjStrm->QuickReadInt32(); m_nHeight = m_pObjStrm->QuickReadInt32(); m_Origin.Read(m_pObjStrm); m_AbsoluteOrigin.Read(m_pObjStrm); m_ContainerRotor.Read(m_pObjStrm); m_ContentOrientation = m_pObjStrm->QuickReaduInt8(); m_pObjStrm->SkipExtra(); } } void LwpLayoutGeometry::Parse(IXFStream* /*pOutputStream*/) {} LwpLayoutScale::LwpLayoutScale(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutScale::~LwpLayoutScale() {} void LwpLayoutScale::Read() { LwpVirtualPiece::Read(); if(LwpFileHeader::m_nFileRevision >= 0x000B) { m_nScaleMode = m_pObjStrm->QuickReaduInt16(); m_nScalePercentage = m_pObjStrm->QuickReaduInt32(); m_nScaleWidth = m_pObjStrm->QuickReadInt32(); m_nScaleHeight = m_pObjStrm->QuickReadInt32(); m_nContentRotation = m_pObjStrm->QuickReaduInt16(); m_Offset.Read(m_pObjStrm); m_nPlacement = m_pObjStrm->QuickReaduInt16(); m_pObjStrm->SkipExtra(); } } void LwpLayoutScale::Parse(IXFStream* /*pOutputStream*/) {} LwpLayoutMargins::LwpLayoutMargins(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutMargins::~LwpLayoutMargins() {} void LwpLayoutMargins::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_Margins.Read(m_pObjStrm); m_ExtMargins.Read(m_pObjStrm); m_ExtraMargins.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutMargins::Parse(IXFStream* /*pOutputStream*/) {} LwpLayoutBorder::LwpLayoutBorder(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutBorder::~LwpLayoutBorder() {} void LwpLayoutBorder::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_BorderStuff.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutBorder::Parse(IXFStream* /*pOutputStream*/) {} LwpLayoutBackground::LwpLayoutBackground(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutBackground::~LwpLayoutBackground() {} void LwpLayoutBackground::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_BackgroundStuff.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutBackground::Parse(IXFStream* /*pOutputStream*/) {} LwpExternalBorder::LwpExternalBorder() {} LwpExternalBorder::~LwpExternalBorder() {} void LwpExternalBorder:: Read(LwpObjectStream *pStrm) { if( LwpFileHeader::m_nFileRevision >= 0x000F ) { //enum {BORDER,JOIN}; m_LeftName.Read(pStrm); m_TopName.Read(pStrm); m_RightName.Read(pStrm); m_BottomName.Read(pStrm); // TODO: Do not know what it is for /*cLeftName = CStyleMgr::GetUniqueMetaFileName(cLeftName,BORDER); cRightName = CStyleMgr::GetUniqueMetaFileName(cRightName,BORDER); cTopName = CStyleMgr::GetUniqueMetaFileName(cTopName,BORDER); cBottomName = CStyleMgr::GetUniqueMetaFileName(cBottomName,BORDER);*/ pStrm->SkipExtra(); } } LwpLayoutExternalBorder::LwpLayoutExternalBorder(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutExternalBorder::~LwpLayoutExternalBorder() {} void LwpLayoutExternalBorder::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_ExtranalBorder.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutExternalBorder::Parse(IXFStream* /*pOutputStream*/) {} LwpColumnInfo::LwpColumnInfo() {} LwpColumnInfo::~LwpColumnInfo() {} void LwpColumnInfo:: Read(LwpObjectStream *pStrm) { m_nWidth = pStrm->QuickReadInt32(); m_nGap = pStrm->QuickReadInt32(); } LwpLayoutColumns::LwpLayoutColumns(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm),m_pColumns(NULL) {} LwpLayoutColumns::~LwpLayoutColumns() { if(m_pColumns) { delete[] m_pColumns; m_pColumns = NULL; } } void LwpLayoutColumns::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_nNumCols = m_pObjStrm->QuickReaduInt16(); m_pColumns = new LwpColumnInfo[m_nNumCols]; for(int i=0; i<m_nNumCols; i++) { m_pColumns[i].Read(m_pObjStrm); } m_pObjStrm->SkipExtra(); } } double LwpLayoutColumns::GetColWidth(sal_uInt16 nIndex) { if(nIndex >= m_nNumCols) { return 0; } return m_pColumns[nIndex].GetWidth(); } double LwpLayoutColumns::GetColGap(sal_uInt16 nIndex) { if(nIndex >= m_nNumCols) { return 0; } return m_pColumns[nIndex].GetGap(); } void LwpLayoutColumns::Parse(IXFStream* /*pOutputStream*/) {} LwpLayoutGutters::LwpLayoutGutters(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutGutters::~LwpLayoutGutters() {} void LwpLayoutGutters::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_BorderBuffer.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutGutters::Parse(IXFStream* /*pOutputStream*/) {} LwpJoinStuff::LwpJoinStuff() {} LwpJoinStuff::~LwpJoinStuff() {} #include "lwpstyledef.hxx" void LwpJoinStuff:: Read(LwpObjectStream *pStrm) { m_nWidth = pStrm->QuickReadInt32(); m_nHeight = pStrm->QuickReadInt32(); m_nPercentage = pStrm->QuickReaduInt16(); m_nID = pStrm->QuickReaduInt16(); m_nCorners = pStrm->QuickReaduInt16(); m_nScaling = pStrm->QuickReaduInt16(); m_Color.Read(pStrm); pStrm->SkipExtra(); // Bug fix: if reading in from something older than Release 9 // then check for the external ID and change it to solid. if (LwpFileHeader::m_nFileRevision < 0x0010) { if (m_nID & EXTERNAL_ID) m_nID = MITRE; } } LwpLayoutJoins::LwpLayoutJoins(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutJoins::~LwpLayoutJoins() {} void LwpLayoutJoins::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_JoinStuff.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutJoins::Parse(IXFStream* /*pOutputStream*/) {} LwpLayoutShadow::LwpLayoutShadow(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutShadow::~LwpLayoutShadow() {} void LwpLayoutShadow::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_Shadow.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutShadow::Parse(IXFStream* /*pOutputStream*/) {} /************************************************************************** * @descr: Constructor * @param: * @param: * @return: **************************************************************************/ LwpLayoutRelativityGuts::LwpLayoutRelativityGuts() { m_nRelType = LAY_PARENT_RELATIVE; m_nRelFromWhere = LAY_UPPERLEFT; m_RelDistance.SetX(0); m_RelDistance.SetY(0); m_nTether = LAY_UPPERLEFT; m_nTetherWhere = LAY_BORDER; m_nFlags = 0; } /************************************************************************** * @descr: Read LayoutRelativityGuts' information. * @param: * @param: * @return: **************************************************************************/ void LwpLayoutRelativityGuts::Read(LwpObjectStream *pStrm) { m_nRelType = pStrm->QuickReaduInt8(); m_nRelFromWhere = pStrm->QuickReaduInt8(); m_RelDistance.Read(pStrm); m_nTether = pStrm->QuickReaduInt8(); m_nTetherWhere = pStrm->QuickReaduInt8(); if(LwpFileHeader::m_nFileRevision >= 0x000B) { m_nFlags = pStrm->QuickReaduInt8(); } else { m_nFlags = 0; } } /************************************************************************** * @descr: Constructor * @param: * @param: * @return: **************************************************************************/ LwpLayoutRelativity::LwpLayoutRelativity(LwpObjectHeader &objHdr, LwpSvStream *pStrm) : LwpVirtualPiece(objHdr, pStrm) { } /************************************************************************** * @descr: destructor * @param: * @param: * @return: **************************************************************************/ LwpLayoutRelativity::~LwpLayoutRelativity() { } void LwpLayoutRelativity::Read() { LwpVirtualPiece::Read(); if(LwpFileHeader::m_nFileRevision >= 0x000B) { m_RelGuts.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutRelativity::Parse(IXFStream * /*pOutputStream*/) { } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>coverity#738725: Unitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: IBM Corporation * * Copyright: 2008 by IBM Corporation * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ /************************************************************************* * @file * For LWP filter architecture prototype ************************************************************************/ #include "lwplaypiece.hxx" #include "lwpfilehdr.hxx" LwpRotor::LwpRotor() : m_nRotation(0) {} LwpRotor::~LwpRotor() {} void LwpRotor:: Read(LwpObjectStream *pStrm) { m_nRotation = pStrm->QuickReadInt16(); } LwpLayoutGeometry::LwpLayoutGeometry(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) , m_nWidth(0) , m_nHeight(0) , m_ContentOrientation(0) {} LwpLayoutGeometry::~LwpLayoutGeometry() {} void LwpLayoutGeometry::Read() { LwpVirtualPiece::Read(); if(LwpFileHeader::m_nFileRevision >= 0x000B) { m_nWidth = m_pObjStrm->QuickReadInt32(); m_nHeight = m_pObjStrm->QuickReadInt32(); m_Origin.Read(m_pObjStrm); m_AbsoluteOrigin.Read(m_pObjStrm); m_ContainerRotor.Read(m_pObjStrm); m_ContentOrientation = m_pObjStrm->QuickReaduInt8(); m_pObjStrm->SkipExtra(); } } void LwpLayoutGeometry::Parse(IXFStream* /*pOutputStream*/) {} LwpLayoutScale::LwpLayoutScale(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutScale::~LwpLayoutScale() {} void LwpLayoutScale::Read() { LwpVirtualPiece::Read(); if(LwpFileHeader::m_nFileRevision >= 0x000B) { m_nScaleMode = m_pObjStrm->QuickReaduInt16(); m_nScalePercentage = m_pObjStrm->QuickReaduInt32(); m_nScaleWidth = m_pObjStrm->QuickReadInt32(); m_nScaleHeight = m_pObjStrm->QuickReadInt32(); m_nContentRotation = m_pObjStrm->QuickReaduInt16(); m_Offset.Read(m_pObjStrm); m_nPlacement = m_pObjStrm->QuickReaduInt16(); m_pObjStrm->SkipExtra(); } } void LwpLayoutScale::Parse(IXFStream* /*pOutputStream*/) {} LwpLayoutMargins::LwpLayoutMargins(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutMargins::~LwpLayoutMargins() {} void LwpLayoutMargins::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_Margins.Read(m_pObjStrm); m_ExtMargins.Read(m_pObjStrm); m_ExtraMargins.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutMargins::Parse(IXFStream* /*pOutputStream*/) {} LwpLayoutBorder::LwpLayoutBorder(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutBorder::~LwpLayoutBorder() {} void LwpLayoutBorder::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_BorderStuff.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutBorder::Parse(IXFStream* /*pOutputStream*/) {} LwpLayoutBackground::LwpLayoutBackground(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutBackground::~LwpLayoutBackground() {} void LwpLayoutBackground::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_BackgroundStuff.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutBackground::Parse(IXFStream* /*pOutputStream*/) {} LwpExternalBorder::LwpExternalBorder() {} LwpExternalBorder::~LwpExternalBorder() {} void LwpExternalBorder:: Read(LwpObjectStream *pStrm) { if( LwpFileHeader::m_nFileRevision >= 0x000F ) { //enum {BORDER,JOIN}; m_LeftName.Read(pStrm); m_TopName.Read(pStrm); m_RightName.Read(pStrm); m_BottomName.Read(pStrm); // TODO: Do not know what it is for /*cLeftName = CStyleMgr::GetUniqueMetaFileName(cLeftName,BORDER); cRightName = CStyleMgr::GetUniqueMetaFileName(cRightName,BORDER); cTopName = CStyleMgr::GetUniqueMetaFileName(cTopName,BORDER); cBottomName = CStyleMgr::GetUniqueMetaFileName(cBottomName,BORDER);*/ pStrm->SkipExtra(); } } LwpLayoutExternalBorder::LwpLayoutExternalBorder(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutExternalBorder::~LwpLayoutExternalBorder() {} void LwpLayoutExternalBorder::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_ExtranalBorder.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutExternalBorder::Parse(IXFStream* /*pOutputStream*/) {} LwpColumnInfo::LwpColumnInfo() : m_nWidth(0) , m_nGap(0) {} LwpColumnInfo::~LwpColumnInfo() {} void LwpColumnInfo:: Read(LwpObjectStream *pStrm) { m_nWidth = pStrm->QuickReadInt32(); m_nGap = pStrm->QuickReadInt32(); } LwpLayoutColumns::LwpLayoutColumns(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm),m_pColumns(NULL) {} LwpLayoutColumns::~LwpLayoutColumns() { if(m_pColumns) { delete[] m_pColumns; m_pColumns = NULL; } } void LwpLayoutColumns::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_nNumCols = m_pObjStrm->QuickReaduInt16(); m_pColumns = new LwpColumnInfo[m_nNumCols]; for(int i=0; i<m_nNumCols; i++) { m_pColumns[i].Read(m_pObjStrm); } m_pObjStrm->SkipExtra(); } } double LwpLayoutColumns::GetColWidth(sal_uInt16 nIndex) { if(nIndex >= m_nNumCols) { return 0; } return m_pColumns[nIndex].GetWidth(); } double LwpLayoutColumns::GetColGap(sal_uInt16 nIndex) { if(nIndex >= m_nNumCols) { return 0; } return m_pColumns[nIndex].GetGap(); } void LwpLayoutColumns::Parse(IXFStream* /*pOutputStream*/) {} LwpLayoutGutters::LwpLayoutGutters(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutGutters::~LwpLayoutGutters() {} void LwpLayoutGutters::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_BorderBuffer.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutGutters::Parse(IXFStream* /*pOutputStream*/) {} LwpJoinStuff::LwpJoinStuff() {} LwpJoinStuff::~LwpJoinStuff() {} #include "lwpstyledef.hxx" void LwpJoinStuff:: Read(LwpObjectStream *pStrm) { m_nWidth = pStrm->QuickReadInt32(); m_nHeight = pStrm->QuickReadInt32(); m_nPercentage = pStrm->QuickReaduInt16(); m_nID = pStrm->QuickReaduInt16(); m_nCorners = pStrm->QuickReaduInt16(); m_nScaling = pStrm->QuickReaduInt16(); m_Color.Read(pStrm); pStrm->SkipExtra(); // Bug fix: if reading in from something older than Release 9 // then check for the external ID and change it to solid. if (LwpFileHeader::m_nFileRevision < 0x0010) { if (m_nID & EXTERNAL_ID) m_nID = MITRE; } } LwpLayoutJoins::LwpLayoutJoins(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutJoins::~LwpLayoutJoins() {} void LwpLayoutJoins::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_JoinStuff.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutJoins::Parse(IXFStream* /*pOutputStream*/) {} LwpLayoutShadow::LwpLayoutShadow(LwpObjectHeader& objHdr, LwpSvStream* pStrm) : LwpVirtualPiece(objHdr, pStrm) {} LwpLayoutShadow::~LwpLayoutShadow() {} void LwpLayoutShadow::Read() { LwpVirtualPiece::Read(); if( LwpFileHeader::m_nFileRevision >= 0x000B ) { m_Shadow.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutShadow::Parse(IXFStream* /*pOutputStream*/) {} /************************************************************************** * @descr: Constructor * @param: * @param: * @return: **************************************************************************/ LwpLayoutRelativityGuts::LwpLayoutRelativityGuts() { m_nRelType = LAY_PARENT_RELATIVE; m_nRelFromWhere = LAY_UPPERLEFT; m_RelDistance.SetX(0); m_RelDistance.SetY(0); m_nTether = LAY_UPPERLEFT; m_nTetherWhere = LAY_BORDER; m_nFlags = 0; } /************************************************************************** * @descr: Read LayoutRelativityGuts' information. * @param: * @param: * @return: **************************************************************************/ void LwpLayoutRelativityGuts::Read(LwpObjectStream *pStrm) { m_nRelType = pStrm->QuickReaduInt8(); m_nRelFromWhere = pStrm->QuickReaduInt8(); m_RelDistance.Read(pStrm); m_nTether = pStrm->QuickReaduInt8(); m_nTetherWhere = pStrm->QuickReaduInt8(); if(LwpFileHeader::m_nFileRevision >= 0x000B) { m_nFlags = pStrm->QuickReaduInt8(); } else { m_nFlags = 0; } } /************************************************************************** * @descr: Constructor * @param: * @param: * @return: **************************************************************************/ LwpLayoutRelativity::LwpLayoutRelativity(LwpObjectHeader &objHdr, LwpSvStream *pStrm) : LwpVirtualPiece(objHdr, pStrm) { } /************************************************************************** * @descr: destructor * @param: * @param: * @return: **************************************************************************/ LwpLayoutRelativity::~LwpLayoutRelativity() { } void LwpLayoutRelativity::Read() { LwpVirtualPiece::Read(); if(LwpFileHeader::m_nFileRevision >= 0x000B) { m_RelGuts.Read(m_pObjStrm); m_pObjStrm->SkipExtra(); } } void LwpLayoutRelativity::Parse(IXFStream * /*pOutputStream*/) { } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "KVTranslator.h" #include <QMutex> #include <QUrl> #include <QStandardPaths> #include <QDir> #include <QByteArray> #include <QEventLoop> #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> #include <QJsonValue> #include <QDateTime> #include <QNetworkRequest> #include <QNetworkReply> #include <QDebug> #include "KVUtil.h" KVTranslator* KVTranslator::m_instance = 0; // -- Singleton Instance KVTranslator* KVTranslator::instance() { static QMutex mutex; if(!m_instance) { mutex.lock(); if(!m_instance) m_instance = new KVTranslator; mutex.unlock(); } return m_instance; } // -- KVTranslator::KVTranslator(QObject *parent): QObject(parent), isLoaded(false), JST(32400) { cacheFile.setFileName(QDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).filePath("translation.json")); } KVTranslator::~KVTranslator() { } bool KVTranslator::loaded() { return isLoaded; } void KVTranslator::loadTranslation(QString language) { if(cacheFile.exists()) { cacheFile.open(QIODevice::ReadOnly | QIODevice::Unbuffered); parseTranslationData(cacheFile.readAll()); cacheFile.close(); } QNetworkReply *reply = manager.get(QNetworkRequest(QString("http://api.comeonandsl.am/translation/%1/").arg(language))); connect(reply, SIGNAL(finished()), this, SLOT(translationRequestFinished())); } void KVTranslator::translationRequestFinished() { // Read the response body QNetworkReply *reply(qobject_cast<QNetworkReply*>(QObject::sender())); if(reply->error() != QNetworkReply::NoError) { emit loadFailed(QString("Network Error: %1").arg(reply->errorString())); return; } QByteArray body(reply->readAll()); parseTranslationData(body); qDebug() << "Network translation loaded!"; cacheFile.open(QIODevice::WriteOnly | QIODevice::Truncate); cacheFile.write(body); cacheFile.close(); } void KVTranslator::parseTranslationData(const QByteArray &data) { // Parse the JSON QJsonParseError error; QJsonDocument doc(QJsonDocument::fromJson(data, &error)); if(error.error != QJsonParseError::NoError) { emit loadFailed(QString("JSON Error: %1").arg(error.errorString())); return; } QJsonObject root(doc.object()); // Check the response int success = (int) root.value("success").toDouble(); if(success != 1) { emit loadFailed(QString("API Error %1").arg(success)); return; } // Parse the translation data translation = root.value("translation").toObject().toVariantMap(); isLoaded = true; emit loadFinished(); } QString KVTranslator::translate(const QString &line) const { if(!enabled) return line; QString realLine = unescape(line); QByteArray utf8 = realLine.toUtf8(); quint32 crc = crc32(0, utf8.constData(), utf8.size()); QString key = QString::number(crc); QVariant value = translation.value(key); if(value.isValid()) { //qDebug() << "TL:" << realLine << "->" << value.toString(); return value.toString(); } else { //qDebug() << "No TL:" << realLine; return line; } } QString KVTranslator::fixTime(const QString &time) const { QDateTime realTime = QDateTime::fromString(time, "yyyy-MM-dd hh:mm:ss"); if(!realTime.isValid()) return time; realTime.setTimeZone(JST); realTime = realTime.toLocalTime(); qDebug() << "fix time" << time << "to" << realTime.toString("yyyy-MM-dd hh:mm:ss"); return realTime.toString("yyyy-MM-dd hh:mm:ss"); } QString KVTranslator::translateJson(const QString &json) const { if(!enabled) return json; // Block until translation is loaded if(!isLoaded) { QEventLoop loop; loop.connect(this, SIGNAL(translationLoaded()), SLOT(quit())); loop.connect(this, SIGNAL(loadFailed()), SLOT(quit())); loop.exec(); } bool hasPrefix = json.startsWith("svdata="); QJsonDocument doc = QJsonDocument::fromJson(json.mid(hasPrefix ? 7 : 0).toUtf8()); QJsonValue val = this->_walk(QJsonValue(doc.object())); //qDebug() << val; doc = QJsonDocument(val.toObject()); #if QT_VERSION >= 0x050100 QString str = QString::fromUtf8(doc.toJson(QJsonDocument::Compact)); #else QString str = QString::fromUtf8(doc.toJson()); #endif return (hasPrefix ? "svdata=" + str : str); } QJsonValue KVTranslator::_walk(QJsonValue value, QString key) const { switch(value.type()) { case QJsonValue::Object: { QJsonObject obj = value.toObject(); for(QJsonObject::iterator it = obj.begin(); it != obj.end(); it++) *it = this->_walk(*it, it.key()); return obj; } case QJsonValue::Array: { QJsonArray arr = value.toArray(); for(QJsonArray::iterator it = arr.begin(); it != arr.end(); it++) *it = this->_walk(*it); return arr; } case QJsonValue::String: if(key == "api_complete_time_str") return this->fixTime(value.toString()); return this->translate(value.toString()); default: return value; } } <commit_msg>comment out fix time: debug statements<commit_after>#include "KVTranslator.h" #include <QMutex> #include <QUrl> #include <QStandardPaths> #include <QDir> #include <QByteArray> #include <QEventLoop> #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> #include <QJsonValue> #include <QDateTime> #include <QNetworkRequest> #include <QNetworkReply> #include <QDebug> #include "KVUtil.h" KVTranslator* KVTranslator::m_instance = 0; // -- Singleton Instance KVTranslator* KVTranslator::instance() { static QMutex mutex; if(!m_instance) { mutex.lock(); if(!m_instance) m_instance = new KVTranslator; mutex.unlock(); } return m_instance; } // -- KVTranslator::KVTranslator(QObject *parent): QObject(parent), isLoaded(false), JST(32400) { cacheFile.setFileName(QDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).filePath("translation.json")); } KVTranslator::~KVTranslator() { } bool KVTranslator::loaded() { return isLoaded; } void KVTranslator::loadTranslation(QString language) { if(cacheFile.exists()) { cacheFile.open(QIODevice::ReadOnly | QIODevice::Unbuffered); parseTranslationData(cacheFile.readAll()); cacheFile.close(); } QNetworkReply *reply = manager.get(QNetworkRequest(QString("http://api.comeonandsl.am/translation/%1/").arg(language))); connect(reply, SIGNAL(finished()), this, SLOT(translationRequestFinished())); } void KVTranslator::translationRequestFinished() { // Read the response body QNetworkReply *reply(qobject_cast<QNetworkReply*>(QObject::sender())); if(reply->error() != QNetworkReply::NoError) { emit loadFailed(QString("Network Error: %1").arg(reply->errorString())); return; } QByteArray body(reply->readAll()); parseTranslationData(body); qDebug() << "Network translation loaded!"; cacheFile.open(QIODevice::WriteOnly | QIODevice::Truncate); cacheFile.write(body); cacheFile.close(); } void KVTranslator::parseTranslationData(const QByteArray &data) { // Parse the JSON QJsonParseError error; QJsonDocument doc(QJsonDocument::fromJson(data, &error)); if(error.error != QJsonParseError::NoError) { emit loadFailed(QString("JSON Error: %1").arg(error.errorString())); return; } QJsonObject root(doc.object()); // Check the response int success = (int) root.value("success").toDouble(); if(success != 1) { emit loadFailed(QString("API Error %1").arg(success)); return; } // Parse the translation data translation = root.value("translation").toObject().toVariantMap(); isLoaded = true; emit loadFinished(); } QString KVTranslator::translate(const QString &line) const { if(!enabled) return line; QString realLine = unescape(line); QByteArray utf8 = realLine.toUtf8(); quint32 crc = crc32(0, utf8.constData(), utf8.size()); QString key = QString::number(crc); QVariant value = translation.value(key); if(value.isValid()) { //qDebug() << "TL:" << realLine << "->" << value.toString(); return value.toString(); } else { //qDebug() << "No TL:" << realLine; return line; } } QString KVTranslator::fixTime(const QString &time) const { QDateTime realTime = QDateTime::fromString(time, "yyyy-MM-dd hh:mm:ss"); if(!realTime.isValid()) return time; realTime.setTimeZone(JST); realTime = realTime.toLocalTime(); //qDebug() << "fix time" << time << "to" << realTime.toString("yyyy-MM-dd hh:mm:ss"); return realTime.toString("yyyy-MM-dd hh:mm:ss"); } QString KVTranslator::translateJson(const QString &json) const { if(!enabled) return json; // Block until translation is loaded if(!isLoaded) { QEventLoop loop; loop.connect(this, SIGNAL(translationLoaded()), SLOT(quit())); loop.connect(this, SIGNAL(loadFailed()), SLOT(quit())); loop.exec(); } bool hasPrefix = json.startsWith("svdata="); QJsonDocument doc = QJsonDocument::fromJson(json.mid(hasPrefix ? 7 : 0).toUtf8()); QJsonValue val = this->_walk(QJsonValue(doc.object())); //qDebug() << val; doc = QJsonDocument(val.toObject()); #if QT_VERSION >= 0x050100 QString str = QString::fromUtf8(doc.toJson(QJsonDocument::Compact)); #else QString str = QString::fromUtf8(doc.toJson()); #endif return (hasPrefix ? "svdata=" + str : str); } QJsonValue KVTranslator::_walk(QJsonValue value, QString key) const { switch(value.type()) { case QJsonValue::Object: { QJsonObject obj = value.toObject(); for(QJsonObject::iterator it = obj.begin(); it != obj.end(); it++) *it = this->_walk(*it, it.key()); return obj; } case QJsonValue::Array: { QJsonArray arr = value.toArray(); for(QJsonArray::iterator it = arr.begin(); it != arr.end(); it++) *it = this->_walk(*it); return arr; } case QJsonValue::String: if(key == "api_complete_time_str") return this->fixTime(value.toString()); return this->translate(value.toString()); default: return value; } } <|endoftext|>
<commit_before>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL. // // Simple example of use of Producer::RenderSurface + KeyboardMouseCallback + SceneView // example that provides the user with control over view position with basic picking. #include <Producer/RenderSurface> #include <Producer/KeyboardMouse> #include <Producer/Trackball> #include <osg/Timer> #include <osg/io_utils> #include <osgUtil/SceneView> #include <osgUtil/IntersectVisitor> #include <osgDB/ReadFile> #include <osgFX/Scribe> class MyKeyboardMouseCallback : public Producer::KeyboardMouseCallback { public: MyKeyboardMouseCallback(osgUtil::SceneView* sceneView) : Producer::KeyboardMouseCallback(), _mx(0.0f),_my(0.0f),_mbutton(0), _done(false), _trackBall(new Producer::Trackball), _sceneView(sceneView) { resetTrackball(); _mouseMovingOnPreviousRelease = false; } virtual void specialKeyPress( Producer::KeyCharacter key ) { if (key==Producer::KeyChar_Escape) shutdown(); } virtual void shutdown() { _done = true; } virtual void keyPress( Producer::KeyCharacter key) { if (key==' ') resetTrackball(); } virtual void mouseMotion( float mx, float my ) { _mx = mx; _my = my; } virtual void buttonPress( float mx, float my, unsigned int mbutton ) { _mx = mx; _my = my; _mbutton |= (1<<(mbutton-1)); _mx_buttonPress = _mx; _my_buttonPress = _my; } virtual void buttonRelease( float mx, float my, unsigned int mbutton ) { _mx = mx; _my = my; _mbutton &= ~(1<<(mbutton-1)); if (_mx==_mx_buttonPress && _my_buttonPress==_my) { if (!_mouseMovingOnPreviousRelease) { // button press and release without moving so assume this means // the users wants to pick. pick(_mx,_my); } _mouseMovingOnPreviousRelease = false; } else { _mouseMovingOnPreviousRelease = true; } } bool done() { return _done; } float mx() { return _mx; } float my() { return _my; } unsigned int mbutton() { return _mbutton; } void resetTrackball() { osg::Node* scene = _sceneView->getSceneData(); if (scene) { const osg::BoundingSphere& bs = scene->getBound(); if (bs.valid()) { _trackBall->reset(); _trackBall->setOrientation( Producer::Trackball::Z_UP ); _trackBall->setDistance(bs.radius()*2.0f); _trackBall->translate(-bs.center().x(),-bs.center().y(),-bs.center().z()); } } } osg::Matrixd getViewMatrix() { _trackBall->input( mx(), my(), mbutton() ); return osg::Matrixd(_trackBall->getMatrix().ptr()); } void pick(float x, float y) { osg::Node* scene = _sceneView->getSceneData(); if (scene) { std::cout<<"Picking "<<x<<"\t"<<y<<std::endl; int origX, origY, width, height; _sceneView->getViewport(origX,origY,width,height); // convert Produce's non dimensional x,y coords back into pixel coords. int winX = (int)((x+1.0f)*0.5f*(float)width); int winY = (int)((y+1.0f)*0.5f*(float)height); osg::Vec3 nearPoint, farPoint; _sceneView->projectWindowXYIntoObject(winX,winY,nearPoint,farPoint); std::cout<<"nearPoint "<<nearPoint<<" farPoint "<<farPoint<<std::endl; // make a line segment osg::ref_ptr<osg::LineSegment> lineSegment = new osg::LineSegment(nearPoint,farPoint); // create the IntersectVisitor to do the line intersection traversals. osgUtil::IntersectVisitor intersector; intersector.addLineSegment(lineSegment.get()); scene->accept(intersector); osgUtil::IntersectVisitor::HitList& hits=intersector.getHitList(lineSegment.get()); if (!hits.empty()) { std::cout<<"Got hits"<<std::endl; // just take the first hit - nearest the eye point. osgUtil::Hit& hit = hits.front(); osg::NodePath& nodePath = hit._nodePath; osg::Node* node = (nodePath.size()>=1)?nodePath[nodePath.size()-1]:0; osg::Group* parent = (nodePath.size()>=2)?dynamic_cast<osg::Group*>(nodePath[nodePath.size()-2]):0; if (parent && node) { std::cout<<"Hits "<<node->className()<<std::endl; std::cout<<" parent "<<parent->className()<<std::endl; osgFX::Scribe* parentAsScribe = dynamic_cast<osgFX::Scribe*>(parent); if (!parentAsScribe) { // node not already picked, so highlight it with an osgFX::Scribe osgFX::Scribe* scribe = new osgFX::Scribe(); scribe->addChild(node); parent->replaceChild(node,scribe); } else { // node already picked so we want to remove scribe to unpick it. osg::Node::ParentList parentList = parentAsScribe->getParents(); for(osg::Node::ParentList::iterator itr=parentList.begin(); itr!=parentList.end(); ++itr) { (*itr)->replaceChild(parentAsScribe,node); } } } } } } private: float _mx, _my; float _mx_buttonPress, _my_buttonPress; unsigned int _mbutton; bool _mouseMovingOnPreviousRelease; bool _done; osg::ref_ptr<Producer::Trackball> _trackBall; osg::ref_ptr<osgUtil::SceneView> _sceneView; }; int main( int argc, char **argv ) { if (argc<2) { std::cout << argv[0] <<": requires filename argument." << std::endl; return 1; } // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]); if (!loadedModel) { std::cout << argv[0] <<": No data loaded." << std::endl; return 1; } // create the window to draw to. osg::ref_ptr<Producer::RenderSurface> renderSurface = new Producer::RenderSurface; renderSurface->setWindowName("osgkeyboardmouse"); renderSurface->setWindowRectangle(100,100,800,600); renderSurface->useBorder(true); renderSurface->realize(); // create the view of the scene. osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView; sceneView->setDefaults(); sceneView->setSceneData(loadedModel.get()); // set up a KeyboardMouse to manage the events comming in from the RenderSurface osg::ref_ptr<Producer::KeyboardMouse> kbm = new Producer::KeyboardMouse(renderSurface.get()); // create a KeyboardMouseCallback to handle the mouse events within this applications osg::ref_ptr<MyKeyboardMouseCallback> kbmcb = new MyKeyboardMouseCallback(sceneView.get()); // record the timer tick at the start of rendering. osg::Timer_t start_tick = osg::Timer::instance()->tick(); unsigned int frameNum = 0; // main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.) while( renderSurface->isRealized() && !kbmcb->done()) { // set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly osg::FrameStamp* frameStamp = new osg::FrameStamp; frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(start_tick,osg::Timer::instance()->tick())); frameStamp->setFrameNumber(frameNum++); // pass frame stamp to the SceneView so that the update, cull and draw traversals all use the same FrameStamp sceneView->setFrameStamp(frameStamp); // pass any keyboard mouse events onto the local keyboard mouse callback. kbm->update( *kbmcb ); // set the view sceneView->setViewMatrix(kbmcb->getViewMatrix()); // update the viewport dimensions, incase the window has been resized. sceneView->setViewport(0,0,renderSurface->getWindowWidth(),renderSurface->getWindowHeight()); // do the update traversal the scene graph - such as updating animations sceneView->update(); // do the cull traversal, collect all objects in the view frustum into a sorted set of rendering bins sceneView->cull(); // draw the rendering bins. sceneView->draw(); // Swap Buffers renderSurface->swapBuffers(); } return 0; } <commit_msg>Ported picking across to using PickVisitor.<commit_after>// C++ source file - (C) 2003 Robert Osfield, released under the OSGPL. // // Simple example of use of Producer::RenderSurface + KeyboardMouseCallback + SceneView // example that provides the user with control over view position with basic picking. #include <Producer/RenderSurface> #include <Producer/KeyboardMouse> #include <Producer/Trackball> #include <osg/Timer> #include <osg/io_utils> #include <osgUtil/SceneView> #include <osgUtil/IntersectVisitor> #include <osgDB/ReadFile> #include <osgFX/Scribe> class MyKeyboardMouseCallback : public Producer::KeyboardMouseCallback { public: MyKeyboardMouseCallback(osgUtil::SceneView* sceneView) : Producer::KeyboardMouseCallback(), _mx(0.0f),_my(0.0f),_mbutton(0), _done(false), _trackBall(new Producer::Trackball), _sceneView(sceneView) { resetTrackball(); _mouseMovingOnPreviousRelease = false; } virtual void specialKeyPress( Producer::KeyCharacter key ) { if (key==Producer::KeyChar_Escape) shutdown(); } virtual void shutdown() { _done = true; } virtual void keyPress( Producer::KeyCharacter key) { if (key==' ') resetTrackball(); } virtual void mouseMotion( float mx, float my ) { _mx = mx; _my = my; } virtual void buttonPress( float mx, float my, unsigned int mbutton ) { _mx = mx; _my = my; _mbutton |= (1<<(mbutton-1)); _mx_buttonPress = _mx; _my_buttonPress = _my; } virtual void buttonRelease( float mx, float my, unsigned int mbutton ) { _mx = mx; _my = my; _mbutton &= ~(1<<(mbutton-1)); if (_mx==_mx_buttonPress && _my_buttonPress==_my) { if (!_mouseMovingOnPreviousRelease) { // button press and release without moving so assume this means // the users wants to pick. pick(_mx,_my); } _mouseMovingOnPreviousRelease = false; } else { _mouseMovingOnPreviousRelease = true; } } bool done() { return _done; } float mx() { return _mx; } float my() { return _my; } unsigned int mbutton() { return _mbutton; } void resetTrackball() { osg::Node* scene = _sceneView->getSceneData(); if (scene) { const osg::BoundingSphere& bs = scene->getBound(); if (bs.valid()) { _trackBall->reset(); _trackBall->setOrientation( Producer::Trackball::Z_UP ); _trackBall->setDistance(bs.radius()*2.0f); _trackBall->translate(-bs.center().x(),-bs.center().y(),-bs.center().z()); } } } osg::Matrixd getViewMatrix() { _trackBall->input( mx(), my(), mbutton() ); return osg::Matrixd(_trackBall->getMatrix().ptr()); } void pick(float x, float y) { osg::Node* scene = _sceneView->getSceneData(); if (scene) { std::cout<<"Picking "<<x<<"\t"<<y<<std::endl; int origX, origY, width, height; _sceneView->getViewport(origX,origY,width,height); // convert Producer's non dimensional x,y coords back into pixel coords. int pixel_x = (int)((x+1.0f)*0.5f*(float)width); int pixel_y = (int)((y+1.0f)*0.5f*(float)height); osgUtil::PickVisitor pick(_sceneView->getViewport(), _sceneView->getProjectionMatrix(), _sceneView->getViewMatrix(), pixel_x, pixel_y); scene->accept(pick); osgUtil::PickVisitor::LineSegmentHitListMap& segHitList = pick.getSegHitList(); if (!segHitList.empty() && !segHitList.begin()->second.empty()) { std::cout<<"Got hits"<<std::endl; // get the hits for the first segment osgUtil::PickVisitor::HitList& hits = segHitList.begin()->second; // just take the first hit - nearest the eye point. osgUtil::Hit& hit = hits.front(); osg::NodePath& nodePath = hit._nodePath; osg::Node* node = (nodePath.size()>=1)?nodePath[nodePath.size()-1]:0; osg::Group* parent = (nodePath.size()>=2)?dynamic_cast<osg::Group*>(nodePath[nodePath.size()-2]):0; if (node) std::cout<<" Hits "<<node->className()<<" nodePath size"<<nodePath.size()<<std::endl; // now we try to decorate the hit node by the osgFX::Scribe to show that its been "picked" if (parent && node) { std::cout<<" parent "<<parent->className()<<std::endl; osgFX::Scribe* parentAsScribe = dynamic_cast<osgFX::Scribe*>(parent); if (!parentAsScribe) { // node not already picked, so highlight it with an osgFX::Scribe osgFX::Scribe* scribe = new osgFX::Scribe(); scribe->addChild(node); parent->replaceChild(node,scribe); } else { // node already picked so we want to remove scribe to unpick it. osg::Node::ParentList parentList = parentAsScribe->getParents(); for(osg::Node::ParentList::iterator itr=parentList.begin(); itr!=parentList.end(); ++itr) { (*itr)->replaceChild(parentAsScribe,node); } } } } } } private: float _mx, _my; float _mx_buttonPress, _my_buttonPress; unsigned int _mbutton; bool _mouseMovingOnPreviousRelease; bool _done; osg::ref_ptr<Producer::Trackball> _trackBall; osg::ref_ptr<osgUtil::SceneView> _sceneView; }; int main( int argc, char **argv ) { if (argc<2) { std::cout << argv[0] <<": requires filename argument." << std::endl; return 1; } // load the scene. osg::ref_ptr<osg::Node> loadedModel = osgDB::readNodeFile(argv[1]); if (!loadedModel) { std::cout << argv[0] <<": No data loaded." << std::endl; return 1; } // create the window to draw to. osg::ref_ptr<Producer::RenderSurface> renderSurface = new Producer::RenderSurface; renderSurface->setWindowName("osgkeyboardmouse"); renderSurface->setWindowRectangle(100,100,800,600); renderSurface->useBorder(true); renderSurface->realize(); // create the view of the scene. osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView; sceneView->setDefaults(); sceneView->setSceneData(loadedModel.get()); // set up a KeyboardMouse to manage the events comming in from the RenderSurface osg::ref_ptr<Producer::KeyboardMouse> kbm = new Producer::KeyboardMouse(renderSurface.get()); // create a KeyboardMouseCallback to handle the mouse events within this applications osg::ref_ptr<MyKeyboardMouseCallback> kbmcb = new MyKeyboardMouseCallback(sceneView.get()); // record the timer tick at the start of rendering. osg::Timer_t start_tick = osg::Timer::instance()->tick(); unsigned int frameNum = 0; // main loop (note, window toolkits which take control over the main loop will require a window redraw callback containing the code below.) while( renderSurface->isRealized() && !kbmcb->done()) { // set up the frame stamp for current frame to record the current time and frame number so that animtion code can advance correctly osg::FrameStamp* frameStamp = new osg::FrameStamp; frameStamp->setReferenceTime(osg::Timer::instance()->delta_s(start_tick,osg::Timer::instance()->tick())); frameStamp->setFrameNumber(frameNum++); // pass frame stamp to the SceneView so that the update, cull and draw traversals all use the same FrameStamp sceneView->setFrameStamp(frameStamp); // pass any keyboard mouse events onto the local keyboard mouse callback. kbm->update( *kbmcb ); // set the view sceneView->setViewMatrix(kbmcb->getViewMatrix()); // update the viewport dimensions, incase the window has been resized. sceneView->setViewport(0,0,renderSurface->getWindowWidth(),renderSurface->getWindowHeight()); // do the update traversal the scene graph - such as updating animations sceneView->update(); // do the cull traversal, collect all objects in the view frustum into a sorted set of rendering bins sceneView->cull(); // draw the rendering bins. sceneView->draw(); // Swap Buffers renderSurface->swapBuffers(); } return 0; } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include "mylistmodel.h" #include <QList> #include <algorithm> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); classes.append(Class()); Class &c = classes.last(); c.name = "Example class"; { Student s; s.name = "mist"; s.present = Qt::Unchecked; c.students.append(s); } { Student s; s.name = "spank"; s.present = Qt::Unchecked; c.students.append(s); } { Student s; s.name = "bob"; s.present = Qt::Unchecked; c.students.append(s); } { Student s; s.name = "alice"; s.present = Qt::Unchecked; c.students.append(s); } { Student s; s.name = "malice"; s.present = Qt::Unchecked; c.students.append(s); } { Student s; s.name = "kill"; s.present = Qt::Unchecked; c.students.append(s); } { Student s; s.name = "dragon"; s.present = Qt::Unchecked; c.students.append(s); } lm = new MyListModel(&c.students, this); ui->students->setModel(lm); ui->attendants->setModel(lm); //ui->classes->setModel(lm); connect(lm,SIGNAL(dataChanged(QModelIndex,QModelIndex)),this,SLOT(on_attendants_itemChanged(QModelIndex,QModelIndex))); on_attendants_itemChanged(QModelIndex(), QModelIndex()); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_3_clicked() { QModelIndex i = lm->addEntry("New student"); ui->students->edit(i); ui->students->scrollTo(i); } void MainWindow::on_pushButton_4_clicked() { foreach (QModelIndex i, ui->students->selectionModel()->selectedRows()) { lm->removeRow(i.row()); } } void MainWindow::on_pushButton_5_clicked() { for(int i = 0; i < lm->rowCount(QModelIndex()); ++i) { lm->setData(lm->index(i, 0), QVariant(Qt::Checked), Qt::CheckStateRole); } } void MainWindow::on_pushButton_6_clicked() { for(int i = 0; i < lm->rowCount(QModelIndex()); ++i) { lm->setData(lm->index(i, 0), QVariant(Qt::Unchecked), Qt::CheckStateRole); } } void MainWindow::on_attendants_itemChanged(const QModelIndex &ib, const QModelIndex &ie) { (void)ib; (void)ie;// FIXME: ineffectinve O(n*n) update int present = 0; int absent = 0; for(int i = 0; i < lm->rowCount(QModelIndex()); ++i) { if ((Qt::CheckState)lm->data(lm->index(i, 0), Qt::CheckStateRole).toUInt() == Qt::Checked) { ++present; } else { ++absent; } } ui->absenseStats->setText(tr("%1 students present, %2 students absent").arg(present).arg(absent)); } QList<QString> MainWindow::getShuffledPresentStudents() { QList<QString> presentStudents; for(int i = 0; i < lm->rowCount(QModelIndex()); ++i) { if ((Qt::CheckState)lm->data(lm->index(i, 0), Qt::CheckStateRole).toUInt() == Qt::Checked) { presentStudents.append(lm->data(lm->index(i, 0), Qt::DisplayRole).toString()); } } std::random_shuffle(presentStudents.begin(), presentStudents.end()); return presentStudents; } void MainWindow::doGrouping(QList<QString> s, int groupCount) { int n = s.length(); ui->result->clear(); ui->result->setColumnCount(groupCount); ui->result->setRowCount(n/groupCount + 1); int x = 0; int currentColumn = 0; int currentRow = 0; foreach (QString i, s) { QTableWidgetItem *it = new QTableWidgetItem(i); ui->result->setItem(currentRow, currentColumn, it); ++currentRow; // n / groupCount; x+=groupCount; if (x >= n && currentColumn < groupCount-1) { currentRow = 0; currentColumn += 1; x -= n; } } } void MainWindow::on_pushButton_8_clicked() { QList<QString> s = getShuffledPresentStudents(); int groupCount = ui->desiredSGcount->text().toInt(); doGrouping(s, groupCount); } void MainWindow::on_pushButton_7_clicked() { QList<QString> s = getShuffledPresentStudents(); int n = s.length(); if (n == 0) return; int desiredGroupSize = ui->desiredSGsize->text().toInt(); int groupCountCandidate = n / desiredGroupSize; int groupCountRemainder = n % desiredGroupSize; if (groupCountRemainder != 0) { if (ui->radioPreferIncomplete->isChecked()) { ++groupCountCandidate; } else if (ui->radioBalanced->isChecked()) { if (groupCountRemainder - 1 < desiredGroupSize/2) { // prefer extended } else { // prefer incomplete ++groupCountCandidate; } } } if (groupCountCandidate == 0) ++groupCountCandidate; doGrouping(s, groupCountCandidate); } <commit_msg>Persistence<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include "mylistmodel.h" #include <QList> #include <algorithm> #include <QSettings> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); classes.append(Class()); Class &c = classes.last(); c.name = "Example class"; QSettings set("_Vi","studentchooser"); int n = set.value("preview/count", 0).toInt(); for(int i = 0; i < n; ++i) { Student s; s.name = set.value(QString("preview/%1/name" ).arg(i), "???").toString(); s.present = set.value(QString("preview/%1/present").arg(i), false).toBool() ? Qt::Checked : Qt::Unchecked; c.students.append(s); } lm = new MyListModel(&c.students, this); ui->students->setModel(lm); ui->attendants->setModel(lm); //ui->classes->setModel(lm); connect(lm,SIGNAL(dataChanged(QModelIndex,QModelIndex)),this,SLOT(on_attendants_itemChanged(QModelIndex,QModelIndex))); on_attendants_itemChanged(QModelIndex(), QModelIndex()); } MainWindow::~MainWindow() { delete ui; QSettings set("_Vi","studentchooser"); set.setValue("preview/count", lm->rowCount(QModelIndex())); for(int i = 0; i < lm->rowCount(QModelIndex()); ++i) { bool present = (Qt::CheckState)lm->data(lm->index(i, 0), Qt::CheckStateRole).toUInt() == Qt::Checked; QString name = lm->data(lm->index(i, 0), Qt::DisplayRole).toString(); set.setValue(QString("preview/%1/name" ).arg(i), name); set.setValue(QString("preview/%1/present").arg(i), present); } } void MainWindow::on_pushButton_3_clicked() { QModelIndex i = lm->addEntry("New student"); ui->students->edit(i); ui->students->scrollTo(i); } void MainWindow::on_pushButton_4_clicked() { foreach (QModelIndex i, ui->students->selectionModel()->selectedRows()) { lm->removeRow(i.row()); } } void MainWindow::on_pushButton_5_clicked() { for(int i = 0; i < lm->rowCount(QModelIndex()); ++i) { lm->setData(lm->index(i, 0), QVariant(Qt::Checked), Qt::CheckStateRole); } } void MainWindow::on_pushButton_6_clicked() { for(int i = 0; i < lm->rowCount(QModelIndex()); ++i) { lm->setData(lm->index(i, 0), QVariant(Qt::Unchecked), Qt::CheckStateRole); } } void MainWindow::on_attendants_itemChanged(const QModelIndex &ib, const QModelIndex &ie) { (void)ib; (void)ie;// FIXME: ineffectinve O(n*n) update int present = 0; int absent = 0; for(int i = 0; i < lm->rowCount(QModelIndex()); ++i) { if ((Qt::CheckState)lm->data(lm->index(i, 0), Qt::CheckStateRole).toUInt() == Qt::Checked) { ++present; } else { ++absent; } } ui->absenseStats->setText(tr("%1 students present, %2 students absent").arg(present).arg(absent)); } QList<QString> MainWindow::getShuffledPresentStudents() { QList<QString> presentStudents; for(int i = 0; i < lm->rowCount(QModelIndex()); ++i) { if ((Qt::CheckState)lm->data(lm->index(i, 0), Qt::CheckStateRole).toUInt() == Qt::Checked) { presentStudents.append(lm->data(lm->index(i, 0), Qt::DisplayRole).toString()); } } std::random_shuffle(presentStudents.begin(), presentStudents.end()); return presentStudents; } void MainWindow::doGrouping(QList<QString> s, int groupCount) { int n = s.length(); ui->result->clear(); ui->result->setColumnCount(groupCount); ui->result->setRowCount(n/groupCount + 1); int x = 0; int currentColumn = 0; int currentRow = 0; foreach (QString i, s) { QTableWidgetItem *it = new QTableWidgetItem(i); ui->result->setItem(currentRow, currentColumn, it); ++currentRow; // n / groupCount; x+=groupCount; if (x >= n && currentColumn < groupCount-1) { currentRow = 0; currentColumn += 1; x -= n; } } } void MainWindow::on_pushButton_8_clicked() { QList<QString> s = getShuffledPresentStudents(); int groupCount = ui->desiredSGcount->text().toInt(); doGrouping(s, groupCount); } void MainWindow::on_pushButton_7_clicked() { QList<QString> s = getShuffledPresentStudents(); int n = s.length(); if (n == 0) return; int desiredGroupSize = ui->desiredSGsize->text().toInt(); int groupCountCandidate = n / desiredGroupSize; int groupCountRemainder = n % desiredGroupSize; if (groupCountRemainder != 0) { if (ui->radioPreferIncomplete->isChecked()) { ++groupCountCandidate; } else if (ui->radioBalanced->isChecked()) { if (groupCountRemainder - 1 < desiredGroupSize/2) { // prefer extended } else { // prefer incomplete ++groupCountCandidate; } } } if (groupCountCandidate == 0) ++groupCountCandidate; doGrouping(s, groupCountCandidate); } <|endoftext|>
<commit_before>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QImage> #include <QtDebug> #include <QDir> #include <QMessageBox> #include <qmath.h> #include <math.h> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QString versionString; versionString.append(APP_VERSION); qDebug() << versionString; ui->labVersion->setText("Version: " + versionString); cursor = new QCursor(); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updatePos())); scene = new QGraphicsScene(ui->graphicsView); ui->graphicsView->setScene(scene); ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); calc = new QPixelCalculator(this); patientInfoString = "PatientInfo"; testInfoString = "TestInfo"; settings = new QSettings(this); picIndex = 1; diagonalCMDouble = 1; timer->start(5); } MainWindow::~MainWindow() { delete ui; } void MainWindow::updatePos() { static QPoint lastCursorPosition; QPointF mouse = cursor->pos(); if(lastCursorPosition != mouse) //make sure someone is touching the screen { ui->graphicsView->scene()->addEllipse(mouse.x() - ui->graphicsView->x(), mouse.y() - ui->graphicsView->y(), 3, 3, QPen(), QBrush(Qt::red)); lastCursorPosition = mouse.toPoint(); dataListRaw.append(QPoint(mouse.x() - ui->graphicsView->x(), mouse.y() - ui->graphicsView->y())); } } void MainWindow::calcPPCM() { calc->calculatePPCM(this->width(), this->height(), diagonalCMDouble); } void MainWindow::on_pbCalibrate_clicked() { calcPPCM(); loadSettings(); dataListRaw.clear(); if(ui->pbCalibrate->text() != "Reset") { ui->pbCalibrate->setText("Reset"); } } void MainWindow::drawDataFieldInformation() { scene->clear(); scene->setSceneRect(0,0,ui->graphicsView->width(), ui->graphicsView->height()); ui->graphicsView->resetTransform(); calcPPCM(); for(int i=0; i<ui->graphicsView->width();i = i + (int)calc->getPPCM()) { scene->addLine(i, 0, i, ui->graphicsView->height(), QPen(QBrush(Qt::gray), 1)); //vertical lines } for(int i=0; i<ui->graphicsView->height();i = i+ (int)calc->getPPCM()) { scene->addLine(0, i, ui->graphicsView->width(), i, QPen(QBrush(Qt::gray), 1)); //horizontal lines } //Add date to data field QDate date; QGraphicsSimpleTextItem * dateItem = new QGraphicsSimpleTextItem; dateItem->setText(date.currentDate().toString("MMM dd yyyy")); dateItem->setPos(0,0); scene->addItem(dateItem); //Add patient info to data field QGraphicsSimpleTextItem * patientInfo = new QGraphicsSimpleTextItem; patientInfo->setText(patientInfoString); patientInfo->setPos(dateItem->boundingRect().x() + dateItem->boundingRect().width() + 50, 0); scene->addItem(patientInfo); //Add test info to data field QGraphicsSimpleTextItem * testInfo = new QGraphicsSimpleTextItem; testInfo->setText(testInfoString); testInfo->setPos(dateItem->boundingRect().x() + dateItem->boundingRect().width() + 50 + patientInfo->boundingRect().width() + 50, 0); scene->addItem(testInfo); //Add trial (index) number QString trialString; trialString.append("Trial: "); trialString.append(QString::number(picIndex).rightJustified(2,'0')); QGraphicsSimpleTextItem * trialInfo = new QGraphicsSimpleTextItem; trialInfo->setText(trialString); trialInfo->setPos(dateItem->boundingRect().x() + dateItem->boundingRect().width() + 50 + patientInfo->boundingRect().width() + 50 + testInfo->boundingRect().width() + 50, 0); scene->addItem(trialInfo); QList<QGraphicsItem *> items = scene->items(); foreach(QGraphicsItem *i, items) { i->setFlag(QGraphicsItem::ItemIgnoresTransformations); } qDebug() << "Redrew data field static components"; } void MainWindow::on_pbSaveData_clicked() { timer->stop(); //pause the data-gathering ui->graphicsView->viewport()->update(); //update data field QDir photoDir("/mnt/sdcard/thumbdata"); if(!photoDir.exists()) { if(photoDir.mkdir("/mnt/sdcard/thumbdata") == false) //if couldn't make dir { errorDialog = new ErrorDialog(this); errorDialog->exec(); qDebug() << "Error: Could not find or create the folder to save the data in."; } } QString fileName = photoDir.absolutePath() + "/" + patientInfoString + "-" + testInfoString + QString::number(picIndex).rightJustified(2,'0') + ".png"; QPixmap pixMap = QPixmap::grabWidget(ui->graphicsView); if(pixMap.save(fileName)) { savedDialog = new SavedDialog(this); savedDialog->exec(); qDebug() << "Info: Picture saved as " + fileName; } else { errorDialog = new ErrorDialog(this); errorDialog->exec(); qDebug() << "Error: Couldn't save the pixmap"; } picIndex++; timer->start(); //resume the data-gathering } void MainWindow::loadSettings() { patientInfoString = settings->value("patientInfoString", "Patient Info").toString(); testInfoString = settings->value("testInfoString", "Test Info").toString(); diagonalCMDouble = settings->value("diagonalCM", 1).toDouble(); qDebug() << "Settings loaded in MainWindow"; drawDataFieldInformation(); //refresh the display to reflect updates } void MainWindow::on_pbSettings_clicked() { loadSettings(); //fix CTD bug? settingsDialog = new SettingsDialog(patientInfoString, testInfoString, diagonalCMDouble, this); connect(settingsDialog, SIGNAL(patientInfo(QString)), this, SLOT(patientInfo(QString))); connect(settingsDialog, SIGNAL(testInfo(QString)), this, SLOT(testInfo(QString))); connect(settingsDialog, SIGNAL(diagonalCM(double)), this, SLOT(diagonalCM(double))); connect(settingsDialog, SIGNAL(accepted()), this, SLOT(resetPicIndex())); connect(settingsDialog, SIGNAL(accepted()), timer, SLOT(start())); connect(settingsDialog, SIGNAL(rejected()), timer, SLOT(start())); timer->stop(); //pause the data-gathering settingsDialog->exec(); } void MainWindow::resetPicIndex() { picIndex = 1; //reset counter loadSettings(); //load the settings qDebug() << "Reset counter and called loadSettings()"; } void MainWindow::patientInfo(QString patient) { patientInfoString = patient; settings->setValue("patientInfoString", patientInfoString); settings->sync(); qDebug() << "Patient info copied from Settings dialog"; } void MainWindow::testInfo(QString test) { testInfoString = test; settings->setValue("testInfoString", testInfoString); settings->sync(); qDebug() << "Test info copied from Settings dialog"; } void MainWindow::diagonalCM(double cm) { diagonalCMDouble = cm; settings->setValue("diagonalCM", diagonalCMDouble); settings->sync(); qDebug() << "diagonalCMDouble copied from Settings dialog"; } QPointF MainWindow::calcCircle() { //Prep work first, including gathering of data points QPointF center; center.setX(-1); center.setY(-1); int sectionBreak = dataListRaw.count()/10; //break the datalist into 10 sections QList<QPointF> centerList; //find average center int numCenters = 0; for(int i= 0;i<20;i++) { int indexA = qrand() % (dataListRaw.count()); int indexB = qrand() % (dataListRaw.count()); int indexC = qrand() % (dataListRaw.count()); QPointF a = dataListRaw.at(indexA); QPointF b = dataListRaw.at(indexB); QPointF c = dataListRaw.at(indexC); if(a.x() != b.x() && b.x() != c.x() && a.x() != c.x() && a.y() != b.y() && b.y() != c.y() && a.y() != c.y()) { numCenters++; centerList.append(calcCenter(a,b,c)); } } double xTotal = 0; double yTotal = 0; foreach(QPointF p, centerList) { xTotal += p.x(); yTotal += p.y(); } center.setX((int)xTotal/numCenters); center.setY((int)yTotal/numCenters); //Draw information on screen QPointF testPoint = dataListRaw.at(sectionBreak*3); int radius = sqrt( ((center.x() - testPoint.x()) * (center.x() - testPoint.x())) + ((center.y() - testPoint.y()) * (center.y() - testPoint.y())) ); scene->addEllipse(center.x()-radius, center.y()-radius, 2 * radius, 2 * radius, QPen(Qt::black), QBrush(QColor(0,255,0,64))); rom.setRadius((double)radius); rom.setCenterPoint(center); qDebug() << "Radius (px): " << radius; qDebug() << "PPCM: " << calc->getPPCM(); return center; } QPointF MainWindow::calcCenter(QPointF a, QPointF b, QPointF c) { QPointF centerTemp; qDebug() << a << "; " << b << "; " << c; double yDelta0 = b.y() - a.y(); double xDelta0 = b.x() - a.x(); double yDelta1 = c.y() - b.y(); double xDelta1 = c.x() - b.x(); double slope0 = yDelta0/xDelta0; double slope1 = yDelta1/xDelta1; double xD = 0; double yD = 0; xD = ( (slope0 * slope1 * (a.y() - c.y())) + (slope1 * (a.x() + b.x())) - (slope0 * (b.x() + c.x())) ) / (2.0 *(slope1 - slope0)); yD = -1.0 * (xD - ((a.x() + b.x()) / 2 )) / slope0 + ((a.y() +b.y()) / 2); centerTemp.setX((int)xD); centerTemp.setY((int)yD); qDebug() << "Calculated center here: " << centerTemp; return centerTemp; } double MainWindow::calcROM() //calculate the Range of Motion { double romDegrees = -1; calcCircle(); QPointF furthestPoint = QPointF(-1, -1); QPoint lastPoint = QPoint(0,0); foreach(QPoint p, dataListRaw) //find the furthest point down { if(p.y() >= lastPoint.y()) { furthestPoint.setX(p.x()); furthestPoint.setY(p.y()); lastPoint = p; } else { } } scene->addLine(rom.getCenterPoint().x(), rom.getCenterPoint().y(), furthestPoint.x(), furthestPoint.y(), QPen(Qt::blue)); qDebug() << "Furthest Point: " << furthestPoint; QPointF verticalPoint = rom.getCenterPoint(); verticalPoint.setY(verticalPoint.y() - rom.getRadius()); scene->addLine(rom.getCenterPoint().x(), rom.getCenterPoint().y(), verticalPoint.x(), verticalPoint.y(), QPen(Qt::blue)); qDebug() << "Vertical Point: " << verticalPoint; double deltaX = verticalPoint.x() - furthestPoint.x(); double deltaY = verticalPoint.y() - furthestPoint.y(); double chordLength = sqrt( (deltaX * deltaX) + (deltaY * deltaY) ); double thetaR = qAcos( ( (chordLength * chordLength) - (2 * (rom.getRadius() * rom.getRadius())) ) / ( -2 * (rom.getRadius() * rom.getRadius())) ); double thetaD = 180.0 * thetaR / M_PI; romDegrees = thetaD; qDebug() << "Range of Motion degrees: " << romDegrees; return romDegrees; } void MainWindow::on_pbAnalyze_clicked() { calcROM(); } double MainWindow::calcDistance(QPointF a, QPointF b) { double deltaX = a.x() - b.x(); double deltaY = a.y() - b.y(); double d = sqrt( (deltaX * deltaX) + (deltaY * deltaY) ); return d; } double MainWindow::calcDistance(QPoint a, QPoint b) { double deltaX = (double)a.x() - (double)b.x(); double deltaY = (double)a.y() - (double)b.y(); double d = sqrt( (deltaX * deltaX) + (deltaY * deltaY) ); return d; } QPointF MainWindow::calcAveragePoint(QList<QPointF> l) { QPointF avgPnt = QPointF(0,0); foreach(QPointF p, l) { avgPnt.setX(avgPnt.x() + p.x()); avgPnt.setY(avgPnt.y() + p.y()); } avgPnt.setX(avgPnt.x() / (double)l.count()); avgPnt.setY(avgPnt.y() / (double)l.count()); return avgPnt; } <commit_msg>Rolling average for center points has been added<commit_after>#include "mainwindow.h" #include "ui_mainwindow.h" #include <QImage> #include <QtDebug> #include <QDir> #include <QMessageBox> #include <qmath.h> #include <math.h> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QString versionString; versionString.append(APP_VERSION); qDebug() << versionString; ui->labVersion->setText("Version: " + versionString); cursor = new QCursor(); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(updatePos())); scene = new QGraphicsScene(ui->graphicsView); ui->graphicsView->setScene(scene); ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); calc = new QPixelCalculator(this); patientInfoString = "PatientInfo"; testInfoString = "TestInfo"; settings = new QSettings(this); picIndex = 1; diagonalCMDouble = 1; timer->start(5); } MainWindow::~MainWindow() { delete ui; } void MainWindow::updatePos() { static QPoint lastCursorPosition; QPointF mouse = cursor->pos(); if(lastCursorPosition != mouse) //make sure someone is touching the screen { ui->graphicsView->scene()->addEllipse(mouse.x() - ui->graphicsView->x(), mouse.y() - ui->graphicsView->y(), 3, 3, QPen(), QBrush(Qt::red)); lastCursorPosition = mouse.toPoint(); dataListRaw.append(QPoint(mouse.x() - ui->graphicsView->x(), mouse.y() - ui->graphicsView->y())); } } void MainWindow::calcPPCM() { calc->calculatePPCM(this->width(), this->height(), diagonalCMDouble); } void MainWindow::on_pbCalibrate_clicked() { calcPPCM(); loadSettings(); dataListRaw.clear(); if(ui->pbCalibrate->text() != "Reset") { ui->pbCalibrate->setText("Reset"); } } void MainWindow::drawDataFieldInformation() { scene->clear(); scene->setSceneRect(0,0,ui->graphicsView->width(), ui->graphicsView->height()); ui->graphicsView->resetTransform(); calcPPCM(); for(int i=0; i<ui->graphicsView->width();i = i + (int)calc->getPPCM()) { scene->addLine(i, 0, i, ui->graphicsView->height(), QPen(QBrush(Qt::gray), 1)); //vertical lines } for(int i=0; i<ui->graphicsView->height();i = i+ (int)calc->getPPCM()) { scene->addLine(0, i, ui->graphicsView->width(), i, QPen(QBrush(Qt::gray), 1)); //horizontal lines } //Add date to data field QDate date; QGraphicsSimpleTextItem * dateItem = new QGraphicsSimpleTextItem; dateItem->setText(date.currentDate().toString("MMM dd yyyy")); dateItem->setPos(0,0); scene->addItem(dateItem); //Add patient info to data field QGraphicsSimpleTextItem * patientInfo = new QGraphicsSimpleTextItem; patientInfo->setText(patientInfoString); patientInfo->setPos(dateItem->boundingRect().x() + dateItem->boundingRect().width() + 50, 0); scene->addItem(patientInfo); //Add test info to data field QGraphicsSimpleTextItem * testInfo = new QGraphicsSimpleTextItem; testInfo->setText(testInfoString); testInfo->setPos(dateItem->boundingRect().x() + dateItem->boundingRect().width() + 50 + patientInfo->boundingRect().width() + 50, 0); scene->addItem(testInfo); //Add trial (index) number QString trialString; trialString.append("Trial: "); trialString.append(QString::number(picIndex).rightJustified(2,'0')); QGraphicsSimpleTextItem * trialInfo = new QGraphicsSimpleTextItem; trialInfo->setText(trialString); trialInfo->setPos(dateItem->boundingRect().x() + dateItem->boundingRect().width() + 50 + patientInfo->boundingRect().width() + 50 + testInfo->boundingRect().width() + 50, 0); scene->addItem(trialInfo); QList<QGraphicsItem *> items = scene->items(); foreach(QGraphicsItem *i, items) { i->setFlag(QGraphicsItem::ItemIgnoresTransformations); } qDebug() << "Redrew data field static components"; } void MainWindow::on_pbSaveData_clicked() { timer->stop(); //pause the data-gathering ui->graphicsView->viewport()->update(); //update data field QDir photoDir("/mnt/sdcard/thumbdata"); if(!photoDir.exists()) { if(photoDir.mkdir("/mnt/sdcard/thumbdata") == false) //if couldn't make dir { errorDialog = new ErrorDialog(this); errorDialog->exec(); qDebug() << "Error: Could not find or create the folder to save the data in."; } } QString fileName = photoDir.absolutePath() + "/" + patientInfoString + "-" + testInfoString + QString::number(picIndex).rightJustified(2,'0') + ".png"; QPixmap pixMap = QPixmap::grabWidget(ui->graphicsView); if(pixMap.save(fileName)) { savedDialog = new SavedDialog(this); savedDialog->exec(); qDebug() << "Info: Picture saved as " + fileName; } else { errorDialog = new ErrorDialog(this); errorDialog->exec(); qDebug() << "Error: Couldn't save the pixmap"; } picIndex++; timer->start(); //resume the data-gathering } void MainWindow::loadSettings() { patientInfoString = settings->value("patientInfoString", "Patient Info").toString(); testInfoString = settings->value("testInfoString", "Test Info").toString(); diagonalCMDouble = settings->value("diagonalCM", 1).toDouble(); qDebug() << "Settings loaded in MainWindow"; drawDataFieldInformation(); //refresh the display to reflect updates } void MainWindow::on_pbSettings_clicked() { loadSettings(); //fix CTD bug? settingsDialog = new SettingsDialog(patientInfoString, testInfoString, diagonalCMDouble, this); connect(settingsDialog, SIGNAL(patientInfo(QString)), this, SLOT(patientInfo(QString))); connect(settingsDialog, SIGNAL(testInfo(QString)), this, SLOT(testInfo(QString))); connect(settingsDialog, SIGNAL(diagonalCM(double)), this, SLOT(diagonalCM(double))); connect(settingsDialog, SIGNAL(accepted()), this, SLOT(resetPicIndex())); connect(settingsDialog, SIGNAL(accepted()), timer, SLOT(start())); connect(settingsDialog, SIGNAL(rejected()), timer, SLOT(start())); timer->stop(); //pause the data-gathering settingsDialog->exec(); } void MainWindow::resetPicIndex() { picIndex = 1; //reset counter loadSettings(); //load the settings qDebug() << "Reset counter and called loadSettings()"; } void MainWindow::patientInfo(QString patient) { patientInfoString = patient; settings->setValue("patientInfoString", patientInfoString); settings->sync(); qDebug() << "Patient info copied from Settings dialog"; } void MainWindow::testInfo(QString test) { testInfoString = test; settings->setValue("testInfoString", testInfoString); settings->sync(); qDebug() << "Test info copied from Settings dialog"; } void MainWindow::diagonalCM(double cm) { diagonalCMDouble = cm; settings->setValue("diagonalCM", diagonalCMDouble); settings->sync(); qDebug() << "diagonalCMDouble copied from Settings dialog"; } QPointF MainWindow::calcCircle() { //Prep work first, including gathering of data points QPointF center; center.setX(-1); center.setY(-1); int sectionBreak = dataListRaw.count()/10; //break the datalist into 10 sections QList<QPointF> centerList; //hold all calculated center points qDebug() << "---------- Starting to calculate center points ----------"; qDebug() << "dataListRaw count: " << dataListRaw.count(); for(int i= 0; i <dataListRaw.count() - 2;i++) { qDebug() << "Low: " << i << ", High: " << (i + 2); QPointF a = dataListRaw.at(i); QPointF b = dataListRaw.at(i+1); QPointF c = dataListRaw.at(i+2); if(a.x() != b.x() && b.x() != c.x() && a.x() != c.x() && a.y() != b.y() && b.y() != c.y() && a.y() != c.y()) { centerList.append(calcCenter(a,b,c)); } } qDebug() << "---------- Finished calculating center points ----------"; center = calcAveragePoint(centerList); //Calculate the average center point //Draw information on screen QPointF testPoint = dataListRaw.at(sectionBreak*3); int radius = sqrt( ((center.x() - testPoint.x()) * (center.x() - testPoint.x())) + ((center.y() - testPoint.y()) * (center.y() - testPoint.y())) ); scene->addEllipse(center.x()-radius, center.y()-radius, 2 * radius, 2 * radius, QPen(Qt::black), QBrush(QColor(0,255,0,64))); rom.setRadius((double)radius); rom.setCenterPoint(center); qDebug() << "Radius (px): " << radius; qDebug() << "PPCM: " << calc->getPPCM(); return center; } QPointF MainWindow::calcCenter(QPointF a, QPointF b, QPointF c) { QPointF centerTemp; qDebug() << a << "; " << b << "; " << c; double yDelta0 = b.y() - a.y(); double xDelta0 = b.x() - a.x(); double yDelta1 = c.y() - b.y(); double xDelta1 = c.x() - b.x(); double slope0 = yDelta0/xDelta0; double slope1 = yDelta1/xDelta1; double xD = 0; double yD = 0; xD = ( (slope0 * slope1 * (a.y() - c.y())) + (slope1 * (a.x() + b.x())) - (slope0 * (b.x() + c.x())) ) / (2.0 *(slope1 - slope0)); yD = -1.0 * (xD - ((a.x() + b.x()) / 2 )) / slope0 + ((a.y() +b.y()) / 2); centerTemp.setX((int)xD); centerTemp.setY((int)yD); qDebug() << "Calculated center here: " << centerTemp; return centerTemp; } double MainWindow::calcROM() //calculate the Range of Motion { double romDegrees = -1; calcCircle(); QPointF furthestPoint = QPointF(-1, -1); QPoint lastPoint = QPoint(0,0); foreach(QPoint p, dataListRaw) //find the furthest point down { if(p.y() >= lastPoint.y()) { furthestPoint.setX(p.x()); furthestPoint.setY(p.y()); lastPoint = p; } else { } } scene->addLine(rom.getCenterPoint().x(), rom.getCenterPoint().y(), furthestPoint.x(), furthestPoint.y(), QPen(Qt::blue)); qDebug() << "Furthest Point: " << furthestPoint; QPointF verticalPoint = rom.getCenterPoint(); verticalPoint.setY(verticalPoint.y() - rom.getRadius()); scene->addLine(rom.getCenterPoint().x(), rom.getCenterPoint().y(), verticalPoint.x(), verticalPoint.y(), QPen(Qt::blue)); qDebug() << "Vertical Point: " << verticalPoint; double deltaX = verticalPoint.x() - furthestPoint.x(); double deltaY = verticalPoint.y() - furthestPoint.y(); double chordLength = sqrt( (deltaX * deltaX) + (deltaY * deltaY) ); double thetaR = qAcos( ( (chordLength * chordLength) - (2 * (rom.getRadius() * rom.getRadius())) ) / ( -2 * (rom.getRadius() * rom.getRadius())) ); double thetaD = 180.0 * thetaR / M_PI; romDegrees = thetaD; qDebug() << "Range of Motion degrees: " << romDegrees; return romDegrees; } void MainWindow::on_pbAnalyze_clicked() { calcROM(); } double MainWindow::calcDistance(QPointF a, QPointF b) { double deltaX = a.x() - b.x(); double deltaY = a.y() - b.y(); double d = sqrt( (deltaX * deltaX) + (deltaY * deltaY) ); return d; } double MainWindow::calcDistance(QPoint a, QPoint b) { double deltaX = (double)a.x() - (double)b.x(); double deltaY = (double)a.y() - (double)b.y(); double d = sqrt( (deltaX * deltaX) + (deltaY * deltaY) ); return d; } QPointF MainWindow::calcAveragePoint(QList<QPointF> l) { qDebug() << "---------- Starting to calculate average center point ----------"; QPointF avgPnt = QPointF(0,0); foreach(QPointF p, l) { avgPnt.setX(avgPnt.x() + p.x()); avgPnt.setY(avgPnt.y() + p.y()); } avgPnt.setX(avgPnt.x() / (double)l.count()); avgPnt.setY(avgPnt.y() / (double)l.count()); qDebug() << "---------- Calculated average center point ----------"; return avgPnt; } <|endoftext|>
<commit_before>//===-- CommandObjectReproducer.cpp -----------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "CommandObjectReproducer.h" #include "lldb/Utility/Reproducer.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Interpreter/OptionArgParser.h" #include "lldb/Interpreter/OptionGroupBoolean.h" using namespace lldb; using namespace lldb_private; class CommandObjectReproducerGenerate : public CommandObjectParsed { public: CommandObjectReproducerGenerate(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "reproducer generate", "Generate reproducer on disk.", nullptr) {} ~CommandObjectReproducerGenerate() override = default; protected: bool DoExecute(Args &command, CommandReturnObject &result) override { if (!command.empty()) { result.AppendErrorWithFormat("'%s' takes no arguments", m_cmd_name.c_str()); return false; } auto &r = repro::Reproducer::Instance(); if (auto generator = r.GetGenerator()) { generator->Keep(); } else if (r.GetLoader()) { // Make this operation a NOP in replay mode. result.SetStatus(eReturnStatusSuccessFinishNoResult); return result.Succeeded(); } else { result.AppendErrorWithFormat("Unable to get the reproducer generator"); result.SetStatus(eReturnStatusFailed); return false; } result.GetOutputStream() << "Reproducer written to '" << r.GetReproducerPath() << "'\n"; result.SetStatus(eReturnStatusSuccessFinishResult); return result.Succeeded(); } }; class CommandObjectReproducerStatus : public CommandObjectParsed { public: CommandObjectReproducerStatus(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "reproducer status", "Show the current reproducer status.", nullptr) {} ~CommandObjectReproducerStatus() override = default; protected: bool DoExecute(Args &command, CommandReturnObject &result) override { if (!command.empty()) { result.AppendErrorWithFormat("'%s' takes no arguments", m_cmd_name.c_str()); return false; } auto &r = repro::Reproducer::Instance(); if (r.GetGenerator()) { result.GetOutputStream() << "Reproducer is in capture mode.\n"; } else if (r.GetLoader()) { result.GetOutputStream() << "Reproducer is in replay mode.\n"; } else { result.GetOutputStream() << "Reproducer is off.\n"; } result.SetStatus(eReturnStatusSuccessFinishResult); return result.Succeeded(); } }; CommandObjectReproducer::CommandObjectReproducer( CommandInterpreter &interpreter) : CommandObjectMultiword(interpreter, "reproducer", "Commands controlling LLDB reproducers.", "log <subcommand> [<command-options>]") { LoadSubCommand( "generate", CommandObjectSP(new CommandObjectReproducerGenerate(interpreter))); LoadSubCommand("status", CommandObjectSP( new CommandObjectReproducerStatus(interpreter))); } CommandObjectReproducer::~CommandObjectReproducer() = default; <commit_msg>[Reproducers] Improve reproducer help<commit_after>//===-- CommandObjectReproducer.cpp -----------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "CommandObjectReproducer.h" #include "lldb/Utility/Reproducer.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Interpreter/OptionArgParser.h" #include "lldb/Interpreter/OptionGroupBoolean.h" using namespace lldb; using namespace lldb_private; class CommandObjectReproducerGenerate : public CommandObjectParsed { public: CommandObjectReproducerGenerate(CommandInterpreter &interpreter) : CommandObjectParsed( interpreter, "reproducer generate", "Generate reproducer on disk. When the debugger is in capture " "mode, this command will output the reproducer to a directory on " "disk. In replay mode this command in a no-op.", nullptr) {} ~CommandObjectReproducerGenerate() override = default; protected: bool DoExecute(Args &command, CommandReturnObject &result) override { if (!command.empty()) { result.AppendErrorWithFormat("'%s' takes no arguments", m_cmd_name.c_str()); return false; } auto &r = repro::Reproducer::Instance(); if (auto generator = r.GetGenerator()) { generator->Keep(); } else if (r.GetLoader()) { // Make this operation a NOP in replay mode. result.SetStatus(eReturnStatusSuccessFinishNoResult); return result.Succeeded(); } else { result.AppendErrorWithFormat("Unable to get the reproducer generator"); result.SetStatus(eReturnStatusFailed); return false; } result.GetOutputStream() << "Reproducer written to '" << r.GetReproducerPath() << "'\n"; result.SetStatus(eReturnStatusSuccessFinishResult); return result.Succeeded(); } }; class CommandObjectReproducerStatus : public CommandObjectParsed { public: CommandObjectReproducerStatus(CommandInterpreter &interpreter) : CommandObjectParsed( interpreter, "reproducer status", "Show the current reproducer status. In capture mode the debugger " "is collecting all the information it needs to create a " "reproducer. In replay mode the reproducer is replaying a " "reproducer. When the reproducers are off, no data is collected " "and no reproducer can be generated.", nullptr) {} ~CommandObjectReproducerStatus() override = default; protected: bool DoExecute(Args &command, CommandReturnObject &result) override { if (!command.empty()) { result.AppendErrorWithFormat("'%s' takes no arguments", m_cmd_name.c_str()); return false; } auto &r = repro::Reproducer::Instance(); if (r.GetGenerator()) { result.GetOutputStream() << "Reproducer is in capture mode.\n"; } else if (r.GetLoader()) { result.GetOutputStream() << "Reproducer is in replay mode.\n"; } else { result.GetOutputStream() << "Reproducer is off.\n"; } result.SetStatus(eReturnStatusSuccessFinishResult); return result.Succeeded(); } }; CommandObjectReproducer::CommandObjectReproducer( CommandInterpreter &interpreter) : CommandObjectMultiword( interpreter, "reproducer", "Commands to inspect and manipulate the reproducer functionality.", "log <subcommand> [<command-options>]") { LoadSubCommand( "generate", CommandObjectSP(new CommandObjectReproducerGenerate(interpreter))); LoadSubCommand("status", CommandObjectSP( new CommandObjectReproducerStatus(interpreter))); } CommandObjectReproducer::~CommandObjectReproducer() = default; <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) 2015 University of Central Florida's Computer Software Engineering Scalable & Secure Systems (CSE - S3) Lab 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 <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <unistd.h> #include <string> #include <fstream> #include <iostream> #include "connection.h" #define MAXDATASIZE 100 /************************************************************************ * Temp struct holder for results ************************************************************************/ /** Used to hold result before parsing into objects **/ struct ResultHolder { char metaDataPacket[MESSAGE_SIZE]; char resultPacket[MESSAGE_SIZE]; }; /************************************************************************* * Private Helper Functions * *************************************************************************/ void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } /** * Builds a network packet with the passed in parameters. * This network packet is necessary to send data across sockets. * @param type The type of command being passed. * @param command The command being sent to the server * @return a CommandPacket containing the information to be sent across the socket. */ CommandPacket buildPacket(CommandType type, std::string command) { CommandPacket commandPacket; // command needs to be made into char[] strncpy(commandPacket.message, command.c_str(), sizeof(commandPacket.message)); commandPacket.message[sizeof(commandPacket.message) -1] = 0; commandPacket.commandType = type; commandPacket.terminator = THE_TERMINATOR; return commandPacket; } std::vector<libomdb::ResultRow> parseData(ResultPacket packet) { std::vector<libomdb::ResultRow> rows; // Each of the columns is 64bits, packet.resultSize is number of bytes // 8 bits to a byte, so 8 bytes per column, therefore number of columns // is packet.resultSize / 8 for (int i = 0; i < packet.resultSize; i += 8) { for (int j = 0; j < packet.rowLen; j++) { //TODO: Finish this. I'm going to bed } } return rows; } /** * Parses a ResultMetaDataPacket and builds a list of MetaDataColumns which is * the core of the ResultMetaData class. * @param packet * @return A vector<MetaDataColumn> describing a result set */ std::vector<libomdb::MetaDataColumn> parseMetaData(ResultMetaDataPacket packet) { std::vector<libomdb::MetaDataColumn> metaDataColumns; for (int i = 0; i < packet.numColumns; ++i) { libomdb::MetaDataColumn column; column.label = std::string(packet.columns[i].name); column.sqlType = packet.columns[i].type; } return metaDataColumns; } libomdb::Connection buildConnectionObj(int socket, char* buffer) { // TODO: Parse connection string and create new Connection object } libomdb::CommandResult parseCommandResult(ResultHolder result) { //TODO: build CommandResult requires parsing neils string } /** * TODO: Add error checking */ libomdb::Result parseQueryResult(ResultHolder holder) { ResultMetaDataPacket resultMetaDataPacket = DeserializeResultMetaDataPacket(holder.metaDataPacket); ResultPacket resultPacket = DeserializeResultPacket(holder.resultPacket); // Build result object; std::vector<libomdb::ResultRow> rows = parseData(resultPacket); std::vector<libomdb::MetaDataColumn> metaDataColumns = parseMetaData(resultMetaDataPacket); libomdb::ResultMetaData metaData = libomdb::ResultMetaData::buildResultMetaDataObject(metaDataColumns); return libomdb::Result::buildResultObject(rows, metaData); } /** * Sends message across the socket passed in * @param message The message to send to the server * @param socket The file descriptor of the listening socket */ ResultHolder sendMessage(CommandPacket packet, int socket) { // Need to convert message to c string in order to send it. char message[MESSAGE_SIZE]; memcpy(message, &packet, sizeof(packet)); std::cout << "Message being sent: " << message <<std::endl; // const char* c_message = message.c_str(); std::cout << "Attempting to send message to socket" << socket << std::endl; int bytes_sent = send(socket, message, sizeof message, 0); std::cout<< "Bytes sent: " << bytes_sent << std::endl; if (bytes_sent == -1) { perror("send"); ResultHolder emptyHolder; return emptyHolder; } // Wait for receipt of message; /* * Results will now come in this order: * 1.) ResultMetaDataPacket * 2.) ResultPacket * * Build a struct containing both and return it. */ ResultHolder holder; int bytes_recieved = recv(socket, holder.metaDataPacket, sizeof(holder.metaDataPacket), 0); std::cout << "Bytes relieved: " << bytes_recieved << std::endl; if (bytes_recieved == -1) { perror("recv"); ResultHolder emptyHolder; return emptyHolder; } // Now receive result packet bytes_recieved = recv(socket, holder.resultPacket, sizeof(holder.resultPacket), 0); if (bytes_recieved == -1) { perror("recv"); ResultHolder emptyHolder; return emptyHolder; } return holder; } /************************************************************************* * ConnectionMetaData Implementations * *************************************************************************/ libomdb::ConnectionMetaData::ConnectionMetaData(std::string dbName, bool isValid) :m_databaseName(dbName), m_isValid(isValid) {} std::string libomdb::ConnectionMetaData::getDbName() { return this->m_databaseName; } bool libomdb::ConnectionMetaData::isValid() { return this->m_isValid; } /************************************************************************* * Connection Implementations * *************************************************************************/ // TODO: Break up this monstrosity. libomdb::Connection libomdb::Connection::connect(std::string hostname, uint16_t port, std::string db) { int sockfd, numbytes; char buf[MAXDATASIZE]; struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; // Convert hostname to c string const char* connection_ip = hostname.c_str(); //Convert port to c string. const char* port_string = std::to_string(port).c_str(); memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(connection_ip, port_string, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %d\n", rv); fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return errorConnection(); } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } if (::connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("client: connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); return errorConnection(); } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); printf("client: connecting to %s\n", s); freeaddrinfo(servinfo); // all done with this structure if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) { perror("recv"); return errorConnection(); } buf[numbytes] = '\0'; printf("client: received '%s'\n",buf); std::string dbConnectString = "k:"+db; const char* dbString = dbConnectString.c_str(); // Sending the name of the database to the server. int bytesSent = send(sockfd, dbString, dbConnectString.length(), 0); if (bytesSent == -1) { perror("send"); return errorConnection(); } int bytesReceived = recv(sockfd, buf, MAXDATASIZE -1, 0); if (bytesReceived == -1) { perror("recv"); return errorConnection(); } buf[bytesReceived] = '\0'; printf("client received response from server: %s\n", buf); return buildConnectionObj(sockfd, buf); } void libomdb::Connection::disconnect() { close(this->m_socket_fd); } libomdb::CommandResult libomdb::Connection::executeCommand(std::string command) { CommandPacket packet = buildPacket(CommandType::DB_COMMAND, command); return parseCommandResult(sendMessage(packet, this->m_socket_fd)); } libomdb::Result libomdb::Connection::executeQuery(std::string query) { CommandPacket packet = buildPacket(CommandType::SQL_STATEMENT, query); return parseQueryResult(sendMessage(packet, this->m_socket_fd)); } libomdb::ConnectionMetaData libomdb::Connection::getMetaData() { return this->m_metaData; } void libomdb::Connection::setMetaData(libomdb::ConnectionMetaData data) { this->m_metaData = data; } libomdb::Connection::Connection(uint64_t socket_fd, ConnectionMetaData metaData) :m_metaData(metaData), m_socket_fd(socket_fd) {}<commit_msg>Added parseData implementation<commit_after>/* The MIT License (MIT) Copyright (c) 2015 University of Central Florida's Computer Software Engineering Scalable & Secure Systems (CSE - S3) Lab 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 <arpa/inet.h> #include <netdb.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <unistd.h> #include <string> #include <fstream> #include <iostream> #include "connection.h" #define MAXDATASIZE 100 /************************************************************************ * Temp struct holder for results ************************************************************************/ /** Used to hold result before parsing into objects **/ struct ResultHolder { char metaDataPacket[MESSAGE_SIZE]; char resultPacket[MESSAGE_SIZE]; }; /************************************************************************* * Private Helper Functions * *************************************************************************/ void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } /** * Builds a network packet with the passed in parameters. * This network packet is necessary to send data across sockets. * @param type The type of command being passed. * @param command The command being sent to the server * @return a CommandPacket containing the information to be sent across the socket. */ CommandPacket buildPacket(CommandType type, std::string command) { CommandPacket commandPacket; // command needs to be made into char[] strncpy(commandPacket.message, command.c_str(), sizeof(commandPacket.message)); commandPacket.message[sizeof(commandPacket.message) -1] = 0; commandPacket.commandType = type; commandPacket.terminator = THE_TERMINATOR; return commandPacket; } /** * Parses result packet and builds a vector of ResultRow s * @param packet The result packet to parse * @return a vector<ResultRow> containing the parsed data */ std::vector<libomdb::ResultRow> parseData(ResultPacket packet) { std::vector<libomdb::ResultRow> rows; // Each of the columns is 64bits, packet.resultSize is number of bytes // 8 bits to a byte, so 8 bytes per column, therefore number of columns // is packet.resultSize / 8 uint32_t rowSizeInBytes = packet.rowLen * 8; uint32_t numberOfRows = (packet.resultSize / rowSizeInBytes); uint64_t* dataPointer = &packet.data[0]; for (uint i = 0; i < numberOfRows; ++i) { libomdb::ResultRow row; for (uint j = 0; j < packet.rowLen; ++i) { int64_t* col; memcpy(col, dataPointer, 8); //Move the next 8 bytes into col row.push_back(*col); dataPointer += 2; // Move pointer up 8 bytes. dataPointer++ moves 4 bytes? } rows.push_back(row); } return rows; } /** * Parses a ResultMetaDataPacket and builds a list of MetaDataColumns which is * the core of the ResultMetaData class. * @param packet * @return A vector<MetaDataColumn> describing a result set */ std::vector<libomdb::MetaDataColumn> parseMetaData(ResultMetaDataPacket packet) { std::vector<libomdb::MetaDataColumn> metaDataColumns; for (uint i = 0; i < packet.numColumns; ++i) { libomdb::MetaDataColumn column; column.label = std::string(packet.columns[i].name); column.sqlType = packet.columns[i].type; } return metaDataColumns; } libomdb::Connection buildConnectionObj(int socket, char* buffer) { // TODO: Parse connection string and create new Connection object } libomdb::CommandResult parseCommandResult(ResultHolder result) { //TODO: build CommandResult requires parsing neils string } /** * TODO: Add error checking */ libomdb::Result parseQueryResult(ResultHolder holder) { ResultMetaDataPacket resultMetaDataPacket = DeserializeResultMetaDataPacket(holder.metaDataPacket); ResultPacket resultPacket = DeserializeResultPacket(holder.resultPacket); // Build result object; std::vector<libomdb::ResultRow> rows = parseData(resultPacket); std::vector<libomdb::MetaDataColumn> metaDataColumns = parseMetaData(resultMetaDataPacket); libomdb::ResultMetaData metaData = libomdb::ResultMetaData::buildResultMetaDataObject(metaDataColumns); return libomdb::Result::buildResultObject(rows, metaData); } /** * Sends message across the socket passed in * @param message The message to send to the server * @param socket The file descriptor of the listening socket */ ResultHolder sendMessage(CommandPacket packet, int socket) { // Need to convert message to c string in order to send it. char message[MESSAGE_SIZE]; memcpy(message, &packet, sizeof(packet)); std::cout << "Message being sent: " << message <<std::endl; // const char* c_message = message.c_str(); std::cout << "Attempting to send message to socket" << socket << std::endl; int bytes_sent = send(socket, message, sizeof message, 0); std::cout<< "Bytes sent: " << bytes_sent << std::endl; if (bytes_sent == -1) { perror("send"); ResultHolder emptyHolder; return emptyHolder; } // Wait for receipt of message; /* * Results will now come in this order: * 1.) ResultMetaDataPacket * 2.) ResultPacket * * Build a struct containing both and return it. */ ResultHolder holder; int bytes_recieved = recv(socket, holder.metaDataPacket, sizeof(holder.metaDataPacket), 0); std::cout << "Bytes relieved: " << bytes_recieved << std::endl; if (bytes_recieved == -1) { perror("recv"); ResultHolder emptyHolder; return emptyHolder; } // Now receive result packet bytes_recieved = recv(socket, holder.resultPacket, sizeof(holder.resultPacket), 0); if (bytes_recieved == -1) { perror("recv"); ResultHolder emptyHolder; return emptyHolder; } return holder; } /************************************************************************* * ConnectionMetaData Implementations * *************************************************************************/ libomdb::ConnectionMetaData::ConnectionMetaData(std::string dbName, bool isValid) :m_databaseName(dbName), m_isValid(isValid) {} std::string libomdb::ConnectionMetaData::getDbName() { return this->m_databaseName; } bool libomdb::ConnectionMetaData::isValid() { return this->m_isValid; } /************************************************************************* * Connection Implementations * *************************************************************************/ // TODO: Break up this monstrosity. libomdb::Connection libomdb::Connection::connect(std::string hostname, uint16_t port, std::string db) { int sockfd, numbytes; char buf[MAXDATASIZE]; struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; // Convert hostname to c string const char* connection_ip = hostname.c_str(); //Convert port to c string. const char* port_string = std::to_string(port).c_str(); memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(connection_ip, port_string, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %d\n", rv); fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return errorConnection(); } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } if (::connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("client: connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); return errorConnection(); } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); printf("client: connecting to %s\n", s); freeaddrinfo(servinfo); // all done with this structure if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) { perror("recv"); return errorConnection(); } buf[numbytes] = '\0'; printf("client: received '%s'\n",buf); std::string dbConnectString = "k:"+db; const char* dbString = dbConnectString.c_str(); // Sending the name of the database to the server. int bytesSent = send(sockfd, dbString, dbConnectString.length(), 0); if (bytesSent == -1) { perror("send"); return errorConnection(); } int bytesReceived = recv(sockfd, buf, MAXDATASIZE -1, 0); if (bytesReceived == -1) { perror("recv"); return errorConnection(); } buf[bytesReceived] = '\0'; printf("client received response from server: %s\n", buf); return buildConnectionObj(sockfd, buf); } void libomdb::Connection::disconnect() { close(this->m_socket_fd); } libomdb::CommandResult libomdb::Connection::executeCommand(std::string command) { CommandPacket packet = buildPacket(CommandType::DB_COMMAND, command); return parseCommandResult(sendMessage(packet, this->m_socket_fd)); } libomdb::Result libomdb::Connection::executeQuery(std::string query) { CommandPacket packet = buildPacket(CommandType::SQL_STATEMENT, query); return parseQueryResult(sendMessage(packet, this->m_socket_fd)); } libomdb::ConnectionMetaData libomdb::Connection::getMetaData() { return this->m_metaData; } void libomdb::Connection::setMetaData(libomdb::ConnectionMetaData data) { this->m_metaData = data; } libomdb::Connection::Connection(uint64_t socket_fd, ConnectionMetaData metaData) :m_metaData(metaData), m_socket_fd(socket_fd) {}<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: SdShapeTypes.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: af $ $Date: 2002-03-19 17:21:36 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "SdShapeTypes.hxx" #include "AccessiblePresentationShape.hxx" #include "AccessiblePresentationGraphicShape.hxx" #include "AccessiblePresentationOLEShape.hxx" #ifndef _RTL_USTRING_H_ #include <rtl/ustring.h> #endif namespace accessibility { AccessibleShape* CreateSdAccessibleShape (const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible>& rxParent, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape>& rxShape, AccessibleShapeTreeInfo& rShapeTreeInfo, ShapeTypeId nId) { OSL_TRACE ("creating new presentation shape for type id %d", nId); switch (nId) { case PRESENTATION_TITLE: case PRESENTATION_OUTLINER: case PRESENTATION_SUBTITLE: case PRESENTATION_PAGE: case PRESENTATION_NOTES: case PRESENTATION_HANDOUT: return new AccessiblePresentationShape (rxShape, rxParent, rShapeTreeInfo); case PRESENTATION_GRAPHIC_OBJECT: return new AccessiblePresentationGraphicShape (rxShape, rxParent, rShapeTreeInfo); case PRESENTATION_OLE: case PRESENTATION_CHART: case PRESENTATION_TABLE: return new AccessiblePresentationOLEShape (rxShape, rxParent, rShapeTreeInfo); default: return new AccessibleShape (rxShape, rxParent, rShapeTreeInfo); } } ShapeTypeDescriptor aSdShapeTypeList[] = { ShapeTypeDescriptor ( PRESENTATION_OUTLINER, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.OutlinerShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_SUBTITLE, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.SubtitleShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_GRAPHIC_OBJECT, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.GraphicObjectShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_PAGE, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.PageShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_OLE, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.OLE2Shape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_CHART, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.ChartShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_TABLE, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.TableShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_NOTES, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.NotesShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_TITLE, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.TitleTextShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_HANDOUT, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.HandoutShape"), CreateSdAccessibleShape ) }; void RegisterImpressShapeTypes (void) { ShapeTypeHandler::Instance().AddShapeTypeList ( PRESENTATION_HANDOUT - PRESENTATION_OUTLINER + 1, aSdShapeTypeList); } } // end of namespace accessibility <commit_msg>#95585# Removed trace message.<commit_after>/************************************************************************* * * $RCSfile: SdShapeTypes.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: af $ $Date: 2002-04-15 15:35:30 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "SdShapeTypes.hxx" #include "AccessiblePresentationShape.hxx" #include "AccessiblePresentationGraphicShape.hxx" #include "AccessiblePresentationOLEShape.hxx" #ifndef _RTL_USTRING_H_ #include <rtl/ustring.h> #endif namespace accessibility { AccessibleShape* CreateSdAccessibleShape (const ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible>& rxParent, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShape>& rxShape, AccessibleShapeTreeInfo& rShapeTreeInfo, ShapeTypeId nId) { switch (nId) { case PRESENTATION_TITLE: case PRESENTATION_OUTLINER: case PRESENTATION_SUBTITLE: case PRESENTATION_PAGE: case PRESENTATION_NOTES: case PRESENTATION_HANDOUT: return new AccessiblePresentationShape (rxShape, rxParent, rShapeTreeInfo); case PRESENTATION_GRAPHIC_OBJECT: return new AccessiblePresentationGraphicShape (rxShape, rxParent, rShapeTreeInfo); case PRESENTATION_OLE: case PRESENTATION_CHART: case PRESENTATION_TABLE: return new AccessiblePresentationOLEShape (rxShape, rxParent, rShapeTreeInfo); default: return new AccessibleShape (rxShape, rxParent, rShapeTreeInfo); } } ShapeTypeDescriptor aSdShapeTypeList[] = { ShapeTypeDescriptor ( PRESENTATION_OUTLINER, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.OutlinerShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_SUBTITLE, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.SubtitleShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_GRAPHIC_OBJECT, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.GraphicObjectShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_PAGE, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.PageShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_OLE, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.OLE2Shape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_CHART, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.ChartShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_TABLE, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.TableShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_NOTES, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.NotesShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_TITLE, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.TitleTextShape"), CreateSdAccessibleShape ), ShapeTypeDescriptor ( PRESENTATION_HANDOUT, ::rtl::OUString::createFromAscii ("com.sun.star.presentation.HandoutShape"), CreateSdAccessibleShape ) }; void RegisterImpressShapeTypes (void) { ShapeTypeHandler::Instance().AddShapeTypeList ( PRESENTATION_HANDOUT - PRESENTATION_OUTLINER + 1, aSdShapeTypeList); } } // end of namespace accessibility <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ScriptingContext.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-09 02:31:29 $ * * 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 _FRAMEWORK_SCRIPT_PROTOCOLHANDLER_SCRIPTING_CONTEXT_HXX_ #define _FRAMEWORK_SCRIPT_PROTOCOLHANDLER_SCRIPTING_CONTEXT_HXX_ #include <osl/mutex.hxx> #include <rtl/ustring> #include <cppuhelper/implbase1.hxx> #include <comphelper/uno3.hxx> #include <comphelper/propertycontainer.hxx> #include <comphelper/proparrhlp.hxx> #include <cppuhelper/implbase1.hxx> #include <cppuhelper/weak.hxx> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/uno/RuntimeException.hpp> #include <com/sun/star/uno/RuntimeException.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <comphelper/broadcasthelper.hxx> namespace func_provider { // for simplification #define css ::com::sun::star //Typedefs //============================================================================= //typedef ::cppu::WeakImplHelper1< css::beans::XPropertySet > ScriptingContextImpl_BASE; class ScriptingContext : public ::comphelper::OMutexAndBroadcastHelper, public ::comphelper::OPropertyContainer, public ::comphelper::OPropertyArrayUsageHelper< ScriptingContext >, public css::lang::XTypeProvider, public ::cppu::OWeakObject { public: ScriptingContext( const css::uno::Reference< css::uno::XComponentContext > & xContext ); ~ScriptingContext(); // XInterface css::uno::Any SAL_CALL queryInterface( const css::uno::Type& rType ) throw( css::uno::RuntimeException ) { css::uno::Any aRet( OPropertySetHelper::queryInterface( rType ) ); return (aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType )); } void SAL_CALL acquire() throw() { ::cppu::OWeakObject::acquire(); } void SAL_CALL release() throw() { ::cppu::OWeakObject::release(); } // XPropertySet virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw ( css::uno::RuntimeException ); //XTypeProvider DECLARE_XTYPEPROVIDER( ) protected: // OPropertySetHelper virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper( ); // OPropertyArrayUsageHelper virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const; private: css::uno::Reference< css::uno::XComponentContext > m_xContext; }; } // func_provider #endif //_FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_ <commit_msg>INTEGRATION: CWS warnings01 (1.6.14); FILE MERGED 2005/12/22 14:40:54 ab 1.6.14.1: #i53898# Removed warnings for unxlngi6, unxlngi6.pro<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ScriptingContext.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-06-19 10:22:05 $ * * 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 _FRAMEWORK_SCRIPT_PROTOCOLHANDLER_SCRIPTING_CONTEXT_HXX_ #define _FRAMEWORK_SCRIPT_PROTOCOLHANDLER_SCRIPTING_CONTEXT_HXX_ #include <osl/mutex.hxx> #include <rtl/ustring.hxx> #include <cppuhelper/implbase1.hxx> #include <comphelper/uno3.hxx> #include <comphelper/propertycontainer.hxx> #include <comphelper/proparrhlp.hxx> #include <cppuhelper/implbase1.hxx> #include <cppuhelper/weak.hxx> #include <com/sun/star/lang/XServiceInfo.hpp> #include <com/sun/star/uno/RuntimeException.hpp> #include <com/sun/star/uno/RuntimeException.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <comphelper/broadcasthelper.hxx> namespace func_provider { // for simplification #define css ::com::sun::star //Typedefs //============================================================================= //typedef ::cppu::WeakImplHelper1< css::beans::XPropertySet > ScriptingContextImpl_BASE; class ScriptingContext : public ::comphelper::OMutexAndBroadcastHelper, public ::comphelper::OPropertyContainer, public ::comphelper::OPropertyArrayUsageHelper< ScriptingContext >, public css::lang::XTypeProvider, public ::cppu::OWeakObject { public: ScriptingContext( const css::uno::Reference< css::uno::XComponentContext > & xContext ); ~ScriptingContext(); // XInterface css::uno::Any SAL_CALL queryInterface( const css::uno::Type& rType ) throw( css::uno::RuntimeException ) { css::uno::Any aRet( OPropertySetHelper::queryInterface( rType ) ); return (aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType )); } void SAL_CALL acquire() throw() { ::cppu::OWeakObject::acquire(); } void SAL_CALL release() throw() { ::cppu::OWeakObject::release(); } // XPropertySet virtual css::uno::Reference< css::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw ( css::uno::RuntimeException ); //XTypeProvider DECLARE_XTYPEPROVIDER( ) protected: // OPropertySetHelper virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper( ); // OPropertyArrayUsageHelper virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const; private: css::uno::Reference< css::uno::XComponentContext > m_xContext; }; } // func_provider #endif //_FRAMEWORK_SCRIPT_PROVIDER_XFUNCTIONPROVIDER_HXX_ <|endoftext|>
<commit_before>#include "Adafruit_MQTT.h" #include "Adafruit_MQTT_CC3000.h" #include <Adafruit_Watchdog.h> static void printBuffer(uint8_t *buffer, uint8_t len) { for (uint8_t i=0; i<len; i++) { if (isprint(buffer[i])) Serial.write(buffer[i]); else Serial.print(" "); Serial.print(F(" [0x")); if (buffer[i] < 0x10) Serial.print("0"); Serial.print(buffer[i],HEX); Serial.print("], "); if (i % 8 == 7) Serial.println(); } Serial.println(); } Adafruit_MQTT_CC3000::Adafruit_MQTT_CC3000(Adafruit_CC3000 *cc3k, const char *server, uint16_t port, const char *cid, const char *user, const char *pass) : Adafruit_MQTT(server, port, cid, user, pass), cc3000(cc3k) { // nothin doin } int8_t Adafruit_MQTT_CC3000::connect(void) { uint32_t ip = 0; Watchdog.reset(); // look up IP address if (serverip == 0) { // Try looking up the website's IP address using CC3K's built in getHostByName strcpy_P((char *)buffer, servername); Serial.print((char *)buffer); Serial.print(F(" -> ")); uint8_t dnsretries = 5; Watchdog.reset(); while (ip == 0) { if (! cc3000->getHostByName((char *)buffer, &ip)) { Serial.println(F("Couldn't resolve!")); dnsretries--; Watchdog.reset(); } //Serial.println("OK"); Serial.println(ip, HEX); if (!dnsretries) return -1; delay(500); } serverip = ip; cc3000->printIPdotsRev(serverip); Serial.println(); } Watchdog.reset(); // connect to server #ifdef DEBUG_MQTT_CONNECT Serial.println(F("Connecting to TCP")); #endif mqttclient = cc3000->connectTCP(serverip, portnum); uint8_t len = connectPacket(buffer); #ifdef DEBUG_MQTT_CONNECT Serial.println(F("MQTT connection packet:")); printBuffer(buffer, len); #endif if (mqttclient.connected()) { uint16_t ret = mqttclient.write(buffer, len); #ifdef DEBUG_MQTT_CONNECT Serial.print("returned: "); Serial.println(ret); #endif if (ret != len) return -1; } else { #ifdef DEBUG_MQTT_CONNECT Serial.println(F("Connection failed")); #endif return -1; } len = readPacket(buffer, 4, CONNECT_TIMEOUT_MS); if (len != 4) return -1; if ((buffer[0] != (MQTT_CTRL_CONNECTACK << 4)) || (buffer[1] != 2)) { return -1; } if (buffer[3] != 0) return buffer[3]; /**************** subscription time! */ for (uint8_t i=0; i<MAXSUBSCRIPTIONS; i++) { if (subscriptions[i] == 0) continue; #ifdef DEBUG_MQTT_CONNECT Serial.print(F("Subscribing...")); #endif uint8_t len = subscribePacket(buffer, subscriptions[i]->topic, subscriptions[i]->qos); #ifdef DEBUG_MQTT_CONNECT Serial.println(F("MQTT subscription packet:")); printBuffer(buffer, len); #endif if (mqttclient.connected()) { uint16_t ret = mqttclient.write(buffer, len); #ifdef DEBUG_MQTT_CONNECT Serial.print("returned: "); Serial.println(ret); #endif if (ret != len) return -1; } else { #ifdef DEBUG_MQTT_CONNECT Serial.println(F("Connection failed")); #endif return -1; } // Get SUBACK len = readPacket(buffer, 5, CONNECT_TIMEOUT_MS); #ifdef DEBUG_MQTT_CONNECT Serial.print(F("SUBACK:\t")); printBuffer(buffer, len); #endif if ((len != 5) || (buffer[0] != (MQTT_CTRL_SUBACK << 4))) { return 6; // failure to subscribe } } return 0; } uint16_t Adafruit_MQTT_CC3000::readPacket(uint8_t *buffer, uint8_t maxlen, int16_t timeout, boolean checkForValidPubPacket) { /* Read data until either the connection is closed, or the idle timeout is reached. */ uint16_t len = 0; int16_t t = timeout; while (mqttclient.connected() && (timeout >= 0)) { //Serial.print('.'); while (mqttclient.available()) { //Serial.print('!'); char c = mqttclient.read(); timeout = t; // reset the timeout buffer[len] = c; //Serial.print((uint8_t)c,HEX); len++; if (len == maxlen) { // we read all we want, bail #ifdef DEBUG_MQTT_PACKETREAD Serial.print(F("Read packet:\t")); printBuffer(buffer, len); #endif return len; } // special case where we just one one publication packet at a time if (checkForValidPubPacket) { if ((buffer[0] == (MQTT_CTRL_PUBLISH << 4)) && (buffer[1] == len-2)) { // oooh a valid publish packet! #ifdef DEBUG_MQTT_PACKETREAD Serial.print(F("PUBLISH packet:\t")); printBuffer(buffer, len); #endif return len; } } } Watchdog.reset(); timeout -= MQTT_CC3000_INTERAVAILDELAY; delay(MQTT_CC3000_INTERAVAILDELAY); } return len; } boolean Adafruit_MQTT_CC3000::ping(uint8_t times) { while (times) { uint8_t len = pingPacket(buffer); Serial.print(F("Sending:\t")); printBuffer(buffer, len); if (mqttclient.connected()) { uint16_t ret = mqttclient.write(buffer, len); //Serial.print("returned: "); Serial.println(ret); if (ret != len) return false; } else { Serial.println(F("Connection failed")); return false; } // process ping reply len = readPacket(buffer, 2, PING_TIMEOUT_MS); if (buffer[0] == (MQTT_CTRL_PINGRESP << 4)) return true; } return false; } int32_t Adafruit_MQTT_CC3000::close(void) { return mqttclient.close(); } boolean Adafruit_MQTT_CC3000::publish(const char *topic, char *data, uint8_t qos) { uint8_t len = publishPacket(buffer, topic, data, qos); #ifdef DEBUG_MQTT_PUBLISH Serial.println(F("MQTT publish packet:")); printBuffer(buffer, len); #endif if (mqttclient.connected()) { uint16_t ret = mqttclient.write(buffer, len); #ifdef DEBUG_MQTT_PUBLISH Serial.print("returned: "); Serial.println(ret); #endif if (ret != len) return false; } else { #ifdef DEBUG_MQTT_PUBLISH Serial.println(F("Connection failed")); #endif return false; } if (qos > 0) { len = readPacket(buffer, 4, PUBLISH_TIMEOUT_MS); #ifdef DEBUG_MQTT_PUBLISH Serial.print(F("Reply:\t")); printBuffer(buffer, len); #endif return true; } else { return true; } } boolean Adafruit_MQTT_CC3000::subscribe(Adafruit_MQTT_Subscribe *sub) { uint8_t i; // see if we are already subscribed for (i=0; i<MAXSUBSCRIPTIONS; i++) { if (subscriptions[i] == sub) { #ifdef DEBUG_MQTT_SUBSCRIBE Serial.println(F("Already subscribed")); #endif break; } } if (i==MAXSUBSCRIPTIONS) { // add to subscriptionlist for (i=0; i<MAXSUBSCRIPTIONS; i++) { if (subscriptions[i] == 0) { #ifdef DEBUG_MQTT_SUBSCRIBE Serial.print(F("Added sub ")); Serial.println(i); #endif subscriptions[i] = sub; break; } } } if (i==MAXSUBSCRIPTIONS) { #ifdef DEBUG_MQTT_SUBSCRIBE Serial.println(F("no more space :(")); #endif return false; } } Adafruit_MQTT_Subscribe *Adafruit_MQTT_CC3000::readSubscription(int16_t timeout) { uint8_t i, topiclen, datalen; #ifdef DEBUG_MQTT_READSUB Serial.println(F("reading...")); #endif uint16_t len = readPacket(buffer, MAXBUFFERSIZE, timeout, true); // return one full packet #ifdef DEBUG_MQTT_READSUB printBuffer(buffer, len); #endif if (!len) return NULL; topiclen = buffer[3]; #ifdef DEBUG_MQTT_READSUB Serial.print(F("Looking for subscription len ")); Serial.println(topiclen); #endif // figure out what subscription this is! for (i=0; i<MAXSUBSCRIPTIONS; i++) { if (subscriptions[i]) { //Serial.print(i); boolean flag = true; // TODO: REPLACE WITH MEMCMP? for (uint8_t k=0; k<topiclen; k++) { if ( buffer[4+k] != pgm_read_byte(subscriptions[i]->topic+k) ) flag = false; } if (flag) { #ifdef DEBUG_MQTT_READSUB Serial.println((char *)buffer+4); Serial.print(F("Found sub #")); Serial.println(i); #endif break; } } } if (i==MAXSUBSCRIPTIONS) return NULL; // matching sub not found ??? // zero out the old data memset(subscriptions[i]->lastread, 0, SUBSCRIPTIONDATALEN); datalen = len - topiclen - 4; if (datalen > SUBSCRIPTIONDATALEN) { datalen = SUBSCRIPTIONDATALEN-1; // cut it off } // extract out just the data, into the subscription object itself memcpy(subscriptions[i]->lastread, buffer+4+topiclen, datalen); #ifdef DEBUG_MQTT_READSUB Serial.print(F("Data len: ")); Serial.println(datalen); Serial.print("Data: "); Serial.println((char *)subscriptions[i]->lastread); #endif // return the valid matching subscription return subscriptions[i]; } <commit_msg>fix for new sleepydog include<commit_after>#include "Adafruit_MQTT.h" #include "Adafruit_MQTT_CC3000.h" #include <Adafruit_SleepyDog.h> static void printBuffer(uint8_t *buffer, uint8_t len) { for (uint8_t i=0; i<len; i++) { if (isprint(buffer[i])) Serial.write(buffer[i]); else Serial.print(" "); Serial.print(F(" [0x")); if (buffer[i] < 0x10) Serial.print("0"); Serial.print(buffer[i],HEX); Serial.print("], "); if (i % 8 == 7) Serial.println(); } Serial.println(); } Adafruit_MQTT_CC3000::Adafruit_MQTT_CC3000(Adafruit_CC3000 *cc3k, const char *server, uint16_t port, const char *cid, const char *user, const char *pass) : Adafruit_MQTT(server, port, cid, user, pass), cc3000(cc3k) { // nothin doin } int8_t Adafruit_MQTT_CC3000::connect(void) { uint32_t ip = 0; Watchdog.reset(); // look up IP address if (serverip == 0) { // Try looking up the website's IP address using CC3K's built in getHostByName strcpy_P((char *)buffer, servername); Serial.print((char *)buffer); Serial.print(F(" -> ")); uint8_t dnsretries = 5; Watchdog.reset(); while (ip == 0) { if (! cc3000->getHostByName((char *)buffer, &ip)) { Serial.println(F("Couldn't resolve!")); dnsretries--; Watchdog.reset(); } //Serial.println("OK"); Serial.println(ip, HEX); if (!dnsretries) return -1; delay(500); } serverip = ip; cc3000->printIPdotsRev(serverip); Serial.println(); } Watchdog.reset(); // connect to server #ifdef DEBUG_MQTT_CONNECT Serial.println(F("Connecting to TCP")); #endif mqttclient = cc3000->connectTCP(serverip, portnum); uint8_t len = connectPacket(buffer); #ifdef DEBUG_MQTT_CONNECT Serial.println(F("MQTT connection packet:")); printBuffer(buffer, len); #endif if (mqttclient.connected()) { uint16_t ret = mqttclient.write(buffer, len); #ifdef DEBUG_MQTT_CONNECT Serial.print("returned: "); Serial.println(ret); #endif if (ret != len) return -1; } else { #ifdef DEBUG_MQTT_CONNECT Serial.println(F("Connection failed")); #endif return -1; } len = readPacket(buffer, 4, CONNECT_TIMEOUT_MS); if (len != 4) return -1; if ((buffer[0] != (MQTT_CTRL_CONNECTACK << 4)) || (buffer[1] != 2)) { return -1; } if (buffer[3] != 0) return buffer[3]; /**************** subscription time! */ for (uint8_t i=0; i<MAXSUBSCRIPTIONS; i++) { if (subscriptions[i] == 0) continue; #ifdef DEBUG_MQTT_CONNECT Serial.print(F("Subscribing...")); #endif uint8_t len = subscribePacket(buffer, subscriptions[i]->topic, subscriptions[i]->qos); #ifdef DEBUG_MQTT_CONNECT Serial.println(F("MQTT subscription packet:")); printBuffer(buffer, len); #endif if (mqttclient.connected()) { uint16_t ret = mqttclient.write(buffer, len); #ifdef DEBUG_MQTT_CONNECT Serial.print("returned: "); Serial.println(ret); #endif if (ret != len) return -1; } else { #ifdef DEBUG_MQTT_CONNECT Serial.println(F("Connection failed")); #endif return -1; } // Get SUBACK len = readPacket(buffer, 5, CONNECT_TIMEOUT_MS); #ifdef DEBUG_MQTT_CONNECT Serial.print(F("SUBACK:\t")); printBuffer(buffer, len); #endif if ((len != 5) || (buffer[0] != (MQTT_CTRL_SUBACK << 4))) { return 6; // failure to subscribe } } return 0; } uint16_t Adafruit_MQTT_CC3000::readPacket(uint8_t *buffer, uint8_t maxlen, int16_t timeout, boolean checkForValidPubPacket) { /* Read data until either the connection is closed, or the idle timeout is reached. */ uint16_t len = 0; int16_t t = timeout; while (mqttclient.connected() && (timeout >= 0)) { //Serial.print('.'); while (mqttclient.available()) { //Serial.print('!'); char c = mqttclient.read(); timeout = t; // reset the timeout buffer[len] = c; //Serial.print((uint8_t)c,HEX); len++; if (len == maxlen) { // we read all we want, bail #ifdef DEBUG_MQTT_PACKETREAD Serial.print(F("Read packet:\t")); printBuffer(buffer, len); #endif return len; } // special case where we just one one publication packet at a time if (checkForValidPubPacket) { if ((buffer[0] == (MQTT_CTRL_PUBLISH << 4)) && (buffer[1] == len-2)) { // oooh a valid publish packet! #ifdef DEBUG_MQTT_PACKETREAD Serial.print(F("PUBLISH packet:\t")); printBuffer(buffer, len); #endif return len; } } } Watchdog.reset(); timeout -= MQTT_CC3000_INTERAVAILDELAY; delay(MQTT_CC3000_INTERAVAILDELAY); } return len; } boolean Adafruit_MQTT_CC3000::ping(uint8_t times) { while (times) { uint8_t len = pingPacket(buffer); Serial.print(F("Sending:\t")); printBuffer(buffer, len); if (mqttclient.connected()) { uint16_t ret = mqttclient.write(buffer, len); //Serial.print("returned: "); Serial.println(ret); if (ret != len) return false; } else { Serial.println(F("Connection failed")); return false; } // process ping reply len = readPacket(buffer, 2, PING_TIMEOUT_MS); if (buffer[0] == (MQTT_CTRL_PINGRESP << 4)) return true; } return false; } int32_t Adafruit_MQTT_CC3000::close(void) { return mqttclient.close(); } boolean Adafruit_MQTT_CC3000::publish(const char *topic, char *data, uint8_t qos) { uint8_t len = publishPacket(buffer, topic, data, qos); #ifdef DEBUG_MQTT_PUBLISH Serial.println(F("MQTT publish packet:")); printBuffer(buffer, len); #endif if (mqttclient.connected()) { uint16_t ret = mqttclient.write(buffer, len); #ifdef DEBUG_MQTT_PUBLISH Serial.print("returned: "); Serial.println(ret); #endif if (ret != len) return false; } else { #ifdef DEBUG_MQTT_PUBLISH Serial.println(F("Connection failed")); #endif return false; } if (qos > 0) { len = readPacket(buffer, 4, PUBLISH_TIMEOUT_MS); #ifdef DEBUG_MQTT_PUBLISH Serial.print(F("Reply:\t")); printBuffer(buffer, len); #endif return true; } else { return true; } } boolean Adafruit_MQTT_CC3000::subscribe(Adafruit_MQTT_Subscribe *sub) { uint8_t i; // see if we are already subscribed for (i=0; i<MAXSUBSCRIPTIONS; i++) { if (subscriptions[i] == sub) { #ifdef DEBUG_MQTT_SUBSCRIBE Serial.println(F("Already subscribed")); #endif break; } } if (i==MAXSUBSCRIPTIONS) { // add to subscriptionlist for (i=0; i<MAXSUBSCRIPTIONS; i++) { if (subscriptions[i] == 0) { #ifdef DEBUG_MQTT_SUBSCRIBE Serial.print(F("Added sub ")); Serial.println(i); #endif subscriptions[i] = sub; break; } } } if (i==MAXSUBSCRIPTIONS) { #ifdef DEBUG_MQTT_SUBSCRIBE Serial.println(F("no more space :(")); #endif return false; } } Adafruit_MQTT_Subscribe *Adafruit_MQTT_CC3000::readSubscription(int16_t timeout) { uint8_t i, topiclen, datalen; #ifdef DEBUG_MQTT_READSUB Serial.println(F("reading...")); #endif uint16_t len = readPacket(buffer, MAXBUFFERSIZE, timeout, true); // return one full packet #ifdef DEBUG_MQTT_READSUB printBuffer(buffer, len); #endif if (!len) return NULL; topiclen = buffer[3]; #ifdef DEBUG_MQTT_READSUB Serial.print(F("Looking for subscription len ")); Serial.println(topiclen); #endif // figure out what subscription this is! for (i=0; i<MAXSUBSCRIPTIONS; i++) { if (subscriptions[i]) { //Serial.print(i); boolean flag = true; // TODO: REPLACE WITH MEMCMP? for (uint8_t k=0; k<topiclen; k++) { if ( buffer[4+k] != pgm_read_byte(subscriptions[i]->topic+k) ) flag = false; } if (flag) { #ifdef DEBUG_MQTT_READSUB Serial.println((char *)buffer+4); Serial.print(F("Found sub #")); Serial.println(i); #endif break; } } } if (i==MAXSUBSCRIPTIONS) return NULL; // matching sub not found ??? // zero out the old data memset(subscriptions[i]->lastread, 0, SUBSCRIPTIONDATALEN); datalen = len - topiclen - 4; if (datalen > SUBSCRIPTIONDATALEN) { datalen = SUBSCRIPTIONDATALEN-1; // cut it off } // extract out just the data, into the subscription object itself memcpy(subscriptions[i]->lastread, buffer+4+topiclen, datalen); #ifdef DEBUG_MQTT_READSUB Serial.print(F("Data len: ")); Serial.println(datalen); Serial.print("Data: "); Serial.println((char *)subscriptions[i]->lastread); #endif // return the valid matching subscription return subscriptions[i]; } <|endoftext|>
<commit_before>/* * opencog/atoms/execution/ExecutionOutputLink.cc * * Copyright (C) 2009, 2013, 2015 Linas Vepstas * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <dlfcn.h> #include <stdlib.h> #include <opencog/atoms/base/atom_types.h> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atoms/core/DefineLink.h> #include <opencog/cython/PythonEval.h> #include <opencog/guile/SchemeEval.h> #include "ExecutionOutputLink.h" #include "Force.h" using namespace opencog; class LibraryManager { private: static std::unordered_map<std::string, void*> _librarys; static std::unordered_map<std::string, void*> _functions; public: static void* getFunc(std::string libName,std::string funcName); }; void ExecutionOutputLink::check_schema(const Handle& schema) const { if (not classserver().isA(schema->get_type(), SCHEMA_NODE) and LAMBDA_LINK != schema->get_type()) { throw SyntaxException(TRACE_INFO, "ExecutionOutputLink must have schema! Got %s", schema->to_string().c_str()); } } ExecutionOutputLink::ExecutionOutputLink(const HandleSeq& oset, Type t) : FunctionLink(oset, t) { if (EXECUTION_OUTPUT_LINK != t) throw SyntaxException(TRACE_INFO, "Expection an ExecutionOutputLink!"); if (2 != oset.size()) throw SyntaxException(TRACE_INFO, "ExecutionOutputLink must have schema and args! Got arity=%d", oset.size()); check_schema(oset[0]); } ExecutionOutputLink::ExecutionOutputLink(const Handle& schema, const Handle& args) : FunctionLink(EXECUTION_OUTPUT_LINK, schema, args) { check_schema(schema); } ExecutionOutputLink::ExecutionOutputLink(const Link& l) : FunctionLink(l) { Type tscope = l.get_type(); if (EXECUTION_OUTPUT_LINK != tscope) throw SyntaxException(TRACE_INFO, "Expection an ExecutionOutputLink!"); } /// execute -- execute the function defined in an ExecutionOutputLink /// /// Each ExecutionOutputLink should have the form: /// /// ExecutionOutputLink /// GroundedSchemaNode "lang: func_name" /// ListLink /// SomeAtom /// OtherAtom /// /// The "lang:" should be either "scm:" for scheme, or "py:" for python. /// This method will then invoke "func_name" on the provided ListLink /// of arguments to the function. /// Handle ExecutionOutputLink::execute(AtomSpace* as, bool silent) const { if (_outgoing[0]->get_type() != GROUNDED_SCHEMA_NODE) { LAZY_LOG_FINE << "Not a grounded schema. Do not execute it"; return get_handle(); } return do_execute(as, _outgoing[0], _outgoing[1], silent); } /// do_execute -- execute the SchemaNode of the ExecutionOutputLink /// /// Expects "gsn" to be a GroundedSchemaNode or a DefinedSchemaNode /// Expects "cargs" to be a ListLink unless there is only one argument /// Executes the GroundedSchemaNode, supplying cargs as arguments /// Handle ExecutionOutputLink::do_execute(AtomSpace* as, const Handle& gsn, const Handle& cargs, bool silent) { LAZY_LOG_FINE << "Execute gsn: " << gsn->to_short_string() << "with arguments: " << cargs->to_short_string(); // Force execution of the arguments. We have to do this, because // the user-defined functions are black-boxes, and cannot be trusted // to do lazy execution correctly. Right now, forcing is the policy. // We could add "scm-lazy:" and "py-lazy:" URI's for user-defined // functions smart enough to do lazy evaluation. Handle args = force_execute(as, cargs, silent); // Get the schema name. const std::string& schema = gsn->get_name(); // Extract the language, library and function std::string lang, lib, fun; lang_lib_fun(schema, lang, lib, fun); Handle result; // At this point, we only run scheme, python schemas and functions from // libraries loaded at runtime. if (lang == "scm") { #ifdef HAVE_GUILE SchemeEval* applier = SchemeEval::get_evaluator(as); result = applier->apply(fun, args); // Exceptions were already caught, before leaving guile mode, // so we can't rethrow. Just throw a new exception. if (applier->eval_error()) throw RuntimeException(TRACE_INFO, "Failed evaluation; see logfile for stack trace."); #else throw RuntimeException(TRACE_INFO, "Cannot evaluate scheme GroundedSchemaNode!"); #endif /* HAVE_GUILE */ } else if (lang == "py") { #ifdef HAVE_CYTHON // Get a reference to the python evaluator. // Be sure to specify the atomspace in which the // evaluation is to be performed. PythonEval &applier = PythonEval::instance(); result = applier.apply(as, fun, args); #else throw RuntimeException(TRACE_INFO, "Cannot evaluate python GroundedSchemaNode!"); #endif /* HAVE_CYTHON */ } // Used by the Haskel bindings else if (lang == "lib") { #define BROKEN_CODE #ifdef BROKEN_CODE void* sym = LibraryManager::getFunc(lib,fun); // Convert the void* pointer to the correct function type. Handle* (*func)(AtomSpace*, Handle*); func = reinterpret_cast<Handle* (*)(AtomSpace *, Handle*)>(sym); // Execute the function result = *func(as, &args); #endif } else { // Unkown proceedure type throw RuntimeException(TRACE_INFO, "Cannot evaluate unknown Schema %s", gsn->to_string().c_str()); } // Check for a not-uncommon user-error. If the user-defined // code returns nothing, then a null-pointer-dereference is // likely, a bit later down the line, leading to a crash. // So head this off at the pass. if (nullptr == result) { // If silent is true, return a simpler and non-logged // exception, which may, in some contexts, be considerably // faster than the one below. if (silent) throw NotEvaluatableException(); throw RuntimeException(TRACE_INFO, "Invalid return value from schema %s\nArgs: %s", gsn->to_string().c_str(), cargs->to_string().c_str()); } LAZY_LOG_FINE << "Result: " << oc_to_string(result); return result; } void ExecutionOutputLink::lang_lib_fun(const std::string& schema, std::string& lang, std::string& lib, std::string& fun) { std::string::size_type pos = schema.find(":"); if (pos == std::string::npos) return; lang = schema.substr(0, pos); // Move past the colon and strip leading white-space do { pos++; } while (' ' == schema[pos]); if (lang == "lib") { // Get the name of the Library and Function. They should be // sperated by "\\". std::size_t seppos = schema.find("\\"); if (seppos == std::string::npos) { throw RuntimeException(TRACE_INFO, "Library name and function name must be separated by '\\'"); } lib = schema.substr(pos, seppos - pos); fun = schema.substr(seppos + 1); } else fun = schema.substr(pos); } DEFINE_LINK_FACTORY(ExecutionOutputLink, EXECUTION_OUTPUT_LINK) std::unordered_map<std::string, void*> LibraryManager::_librarys; std::unordered_map<std::string, void*> LibraryManager::_functions; void* LibraryManager::getFunc(std::string libName,std::string funcName) { void* libHandle; if (_librarys.count(libName) == 0) { // Try and load the library and function. libHandle = dlopen(libName.c_str(), RTLD_LAZY); if (nullptr == libHandle) throw RuntimeException(TRACE_INFO, "Cannot open library: %s - %s", libName.c_str(), dlerror()); _librarys[libName] = libHandle; } else { libHandle = _librarys[libName]; } std::string funcID = libName + "\\" + funcName; void* sym; if (_functions.count(funcID) == 0){ sym = dlsym(libHandle, funcName.c_str()); if (nullptr == sym) throw RuntimeException(TRACE_INFO, "Cannot find symbol %s in library: %s - %s", funcName.c_str(), libName.c_str(), dlerror()); _functions[funcID] = sym; } else { sym = _functions[funcID]; } return sym; } <commit_msg>Add missing schema check in ExecutionOutputLink ctor<commit_after>/* * opencog/atoms/execution/ExecutionOutputLink.cc * * Copyright (C) 2009, 2013, 2015 Linas Vepstas * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <dlfcn.h> #include <stdlib.h> #include <opencog/atoms/base/atom_types.h> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atoms/core/DefineLink.h> #include <opencog/cython/PythonEval.h> #include <opencog/guile/SchemeEval.h> #include "ExecutionOutputLink.h" #include "Force.h" using namespace opencog; class LibraryManager { private: static std::unordered_map<std::string, void*> _librarys; static std::unordered_map<std::string, void*> _functions; public: static void* getFunc(std::string libName,std::string funcName); }; void ExecutionOutputLink::check_schema(const Handle& schema) const { if (not classserver().isA(schema->get_type(), SCHEMA_NODE) and LAMBDA_LINK != schema->get_type()) { throw SyntaxException(TRACE_INFO, "ExecutionOutputLink must have schema! Got %s", schema->to_string().c_str()); } } ExecutionOutputLink::ExecutionOutputLink(const HandleSeq& oset, Type t) : FunctionLink(oset, t) { if (EXECUTION_OUTPUT_LINK != t) throw SyntaxException(TRACE_INFO, "Expection an ExecutionOutputLink!"); if (2 != oset.size()) throw SyntaxException(TRACE_INFO, "ExecutionOutputLink must have schema and args! Got arity=%d", oset.size()); check_schema(oset[0]); } ExecutionOutputLink::ExecutionOutputLink(const Handle& schema, const Handle& args) : FunctionLink(EXECUTION_OUTPUT_LINK, schema, args) { check_schema(schema); } ExecutionOutputLink::ExecutionOutputLink(const Link& l) : FunctionLink(l) { Type tscope = l.get_type(); if (EXECUTION_OUTPUT_LINK != tscope) throw SyntaxException(TRACE_INFO, "Expection an ExecutionOutputLink!"); check_schema(l.getOutgoingAtom(0)); } /// execute -- execute the function defined in an ExecutionOutputLink /// /// Each ExecutionOutputLink should have the form: /// /// ExecutionOutputLink /// GroundedSchemaNode "lang: func_name" /// ListLink /// SomeAtom /// OtherAtom /// /// The "lang:" should be either "scm:" for scheme, or "py:" for python. /// This method will then invoke "func_name" on the provided ListLink /// of arguments to the function. /// Handle ExecutionOutputLink::execute(AtomSpace* as, bool silent) const { if (_outgoing[0]->get_type() != GROUNDED_SCHEMA_NODE) { LAZY_LOG_FINE << "Not a grounded schema. Do not execute it"; return get_handle(); } return do_execute(as, _outgoing[0], _outgoing[1], silent); } /// do_execute -- execute the SchemaNode of the ExecutionOutputLink /// /// Expects "gsn" to be a GroundedSchemaNode or a DefinedSchemaNode /// Expects "cargs" to be a ListLink unless there is only one argument /// Executes the GroundedSchemaNode, supplying cargs as arguments /// Handle ExecutionOutputLink::do_execute(AtomSpace* as, const Handle& gsn, const Handle& cargs, bool silent) { LAZY_LOG_FINE << "Execute gsn: " << gsn->to_short_string() << "with arguments: " << cargs->to_short_string(); // Force execution of the arguments. We have to do this, because // the user-defined functions are black-boxes, and cannot be trusted // to do lazy execution correctly. Right now, forcing is the policy. // We could add "scm-lazy:" and "py-lazy:" URI's for user-defined // functions smart enough to do lazy evaluation. Handle args = force_execute(as, cargs, silent); // Get the schema name. const std::string& schema = gsn->get_name(); // Extract the language, library and function std::string lang, lib, fun; lang_lib_fun(schema, lang, lib, fun); Handle result; // At this point, we only run scheme, python schemas and functions from // libraries loaded at runtime. if (lang == "scm") { #ifdef HAVE_GUILE SchemeEval* applier = SchemeEval::get_evaluator(as); result = applier->apply(fun, args); // Exceptions were already caught, before leaving guile mode, // so we can't rethrow. Just throw a new exception. if (applier->eval_error()) throw RuntimeException(TRACE_INFO, "Failed evaluation; see logfile for stack trace."); #else throw RuntimeException(TRACE_INFO, "Cannot evaluate scheme GroundedSchemaNode!"); #endif /* HAVE_GUILE */ } else if (lang == "py") { #ifdef HAVE_CYTHON // Get a reference to the python evaluator. // Be sure to specify the atomspace in which the // evaluation is to be performed. PythonEval &applier = PythonEval::instance(); result = applier.apply(as, fun, args); #else throw RuntimeException(TRACE_INFO, "Cannot evaluate python GroundedSchemaNode!"); #endif /* HAVE_CYTHON */ } // Used by the Haskel bindings else if (lang == "lib") { #define BROKEN_CODE #ifdef BROKEN_CODE void* sym = LibraryManager::getFunc(lib,fun); // Convert the void* pointer to the correct function type. Handle* (*func)(AtomSpace*, Handle*); func = reinterpret_cast<Handle* (*)(AtomSpace *, Handle*)>(sym); // Execute the function result = *func(as, &args); #endif } else { // Unkown proceedure type throw RuntimeException(TRACE_INFO, "Cannot evaluate unknown Schema %s", gsn->to_string().c_str()); } // Check for a not-uncommon user-error. If the user-defined // code returns nothing, then a null-pointer-dereference is // likely, a bit later down the line, leading to a crash. // So head this off at the pass. if (nullptr == result) { // If silent is true, return a simpler and non-logged // exception, which may, in some contexts, be considerably // faster than the one below. if (silent) throw NotEvaluatableException(); throw RuntimeException(TRACE_INFO, "Invalid return value from schema %s\nArgs: %s", gsn->to_string().c_str(), cargs->to_string().c_str()); } LAZY_LOG_FINE << "Result: " << oc_to_string(result); return result; } void ExecutionOutputLink::lang_lib_fun(const std::string& schema, std::string& lang, std::string& lib, std::string& fun) { std::string::size_type pos = schema.find(":"); if (pos == std::string::npos) return; lang = schema.substr(0, pos); // Move past the colon and strip leading white-space do { pos++; } while (' ' == schema[pos]); if (lang == "lib") { // Get the name of the Library and Function. They should be // sperated by "\\". std::size_t seppos = schema.find("\\"); if (seppos == std::string::npos) { throw RuntimeException(TRACE_INFO, "Library name and function name must be separated by '\\'"); } lib = schema.substr(pos, seppos - pos); fun = schema.substr(seppos + 1); } else fun = schema.substr(pos); } DEFINE_LINK_FACTORY(ExecutionOutputLink, EXECUTION_OUTPUT_LINK) std::unordered_map<std::string, void*> LibraryManager::_librarys; std::unordered_map<std::string, void*> LibraryManager::_functions; void* LibraryManager::getFunc(std::string libName,std::string funcName) { void* libHandle; if (_librarys.count(libName) == 0) { // Try and load the library and function. libHandle = dlopen(libName.c_str(), RTLD_LAZY); if (nullptr == libHandle) throw RuntimeException(TRACE_INFO, "Cannot open library: %s - %s", libName.c_str(), dlerror()); _librarys[libName] = libHandle; } else { libHandle = _librarys[libName]; } std::string funcID = libName + "\\" + funcName; void* sym; if (_functions.count(funcID) == 0){ sym = dlsym(libHandle, funcName.c_str()); if (nullptr == sym) throw RuntimeException(TRACE_INFO, "Cannot find symbol %s in library: %s - %s", funcName.c_str(), libName.c_str(), dlerror()); _functions[funcID] = sym; } else { sym = _functions[funcID]; } return sym; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: browserlistbox.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2004-03-19 12:00:33 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _EXTENSIONS_PROPCTRLR_BROWSERLISTBOX_HXX_ #define _EXTENSIONS_PROPCTRLR_BROWSERLISTBOX_HXX_ #ifndef _SV_SCRBAR_HXX #include <vcl/scrbar.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #ifndef _LINK_HXX #include <tools/link.hxx> #endif #ifndef _EXTENSIONS_PROPCTRLR_BRWCONTROLLISTENER_HXX_ #include "brwcontrollistener.hxx" #endif #ifndef _EXTENSIONS_PROPCTRLR_BROWSERLINE_HXX_ #include "browserline.hxx" #endif #ifndef _EXTENSIONS_PROPCTRLR_MODULEPRC_HXX_ #include "modulepcr.hxx" #endif //............................................................................ namespace pcr { //............................................................................ class IPropertyLineListener; struct OLineDescriptor; //======================================================================== //= OBrowserListBox //======================================================================== class OBrowserListBox :public Control ,public IBrowserControlListener ,public OModuleResourceClient { protected: Window m_aPlayGround; ScrollBar m_aVScroll; OBrowserLinesArray m_aLines; ::rtl::OUString m_aStandard; IPropertyLineListener* m_pLineListener; long m_nYOffset; sal_uInt16 m_nSelectedLine; sal_uInt16 m_nTheNameSize; sal_uInt16 m_nRowHeight; sal_Bool m_bIsActive : 1; sal_Bool m_bUpdate : 1; protected: void ShowLine(sal_uInt16 i); void UpdatePosNSize(); void UpdatePlayGround(); void UpdateVScroll(); void ShowEntry(sal_uInt16 nPos); void MoveThumbTo(long nNewThumbPos); void Resize(); public: OBrowserListBox( Window* pParent, WinBits nWinStyle = WB_DIALOGCONTROL ); ~OBrowserListBox(); void UpdateAll(); virtual void Activate(sal_Bool _bActive = sal_True); virtual sal_uInt16 CalcVisibleLines(); virtual void EnableUpdate(); virtual void DisableUpdate(); virtual long Notify( NotifyEvent& _rNEvt ); virtual void setListener(IPropertyLineListener* _pPLL); virtual void Clear(); virtual sal_uInt16 InsertEntry(const OLineDescriptor&, sal_uInt16 nPos = EDITOR_LIST_APPEND); virtual void ChangeEntry( const OLineDescriptor&, sal_uInt16 nPos); virtual void SetPropertyValue( const ::rtl::OUString & rEntryName, const ::rtl::OUString & rValue ); virtual ::rtl::OUString GetPropertyValue( const ::rtl::OUString & rEntryName ) const; virtual sal_uInt16 GetPropertyPos( const ::rtl::OUString& rEntryName ) const; virtual void SetPropertyData( const ::rtl::OUString& rEntryName, void* pData ); virtual IBrowserControl* GetPropertyControl( const ::rtl::OUString& rEntryName ); virtual IBrowserControl* GetCurrentPropertyControl(); void EnablePropertyLine( const ::rtl::OUString& _rEntryName, bool _bEnable ); void EnablePropertyInput( const ::rtl::OUString& _rEntryName, bool _bEnableInput, bool _bEnableBrowseButton ); virtual void SetFirstVisibleEntry(sal_uInt16 nPos); virtual sal_uInt16 GetFirstVisibleEntry(); virtual void SetSelectedEntry(sal_uInt16 nPos); virtual sal_uInt16 GetSelectedEntry(); // #95343# -------------------------- sal_Int32 GetMinimumWidth(); sal_Bool IsModified( ) const; void CommitModified( ); protected: DECL_LINK( ScrollHdl, ScrollBar* ); DECL_LINK( ClickHdl, PushButton* ); // IBrowserControlListener virtual void Modified (IBrowserControl* _pControl); virtual void GetFocus (IBrowserControl* _pControl); virtual void Commit (IBrowserControl* _pControl); virtual void KeyInput (IBrowserControl* _pControl, const KeyCode& _rKey); virtual void TravelLine (IBrowserControl* _pControl); }; //............................................................................ } // namespace pcr //............................................................................ #endif // _EXTENSIONS_PROPCTRLR_BROWSERLISTBOX_HXX_ <commit_msg>INTEGRATION: CWS eforms2 (1.5.24); FILE MERGED 2004/04/26 11:24:31 fs 1.5.24.1: some cleanup/consolidation / (optionally) allow for a second button per line<commit_after>/************************************************************************* * * $RCSfile: browserlistbox.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2004-11-16 12:01:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _EXTENSIONS_PROPCTRLR_BROWSERLISTBOX_HXX_ #define _EXTENSIONS_PROPCTRLR_BROWSERLISTBOX_HXX_ #ifndef _SV_SCRBAR_HXX #include <vcl/scrbar.hxx> #endif #ifndef _SV_LSTBOX_HXX #include <vcl/lstbox.hxx> #endif #ifndef _SV_BUTTON_HXX #include <vcl/button.hxx> #endif #ifndef _LINK_HXX #include <tools/link.hxx> #endif #ifndef _EXTENSIONS_PROPCTRLR_BRWCONTROLLISTENER_HXX_ #include "brwcontrollistener.hxx" #endif #ifndef _EXTENSIONS_PROPCTRLR_BROWSERLINE_HXX_ #include "browserline.hxx" #endif #ifndef _EXTENSIONS_PROPCTRLR_MODULEPRC_HXX_ #include "modulepcr.hxx" #endif #include <set> //............................................................................ namespace pcr { //............................................................................ class IPropertyLineListener; struct OLineDescriptor; //======================================================================== //= OBrowserListBox //======================================================================== class OBrowserListBox :public Control ,public IBrowserControlListener ,public IButtonClickListener ,public OModuleResourceClient { protected: Window m_aPlayGround; ScrollBar m_aVScroll; OBrowserLinesArray m_aLines; ::rtl::OUString m_aStandard; IPropertyLineListener* m_pLineListener; long m_nYOffset; sal_uInt16 m_nSelectedLine; sal_uInt16 m_nTheNameSize; sal_uInt16 m_nRowHeight; ::std::set< sal_uInt16 > m_aOutOfDateLines; sal_Bool m_bIsActive : 1; sal_Bool m_bUpdate : 1; protected: void PositionLine( sal_uInt16 _nIndex ); void UpdatePosNSize(); void UpdatePlayGround(); void UpdateVScroll(); void ShowEntry(sal_uInt16 nPos); void MoveThumbTo(long nNewThumbPos); void Resize(); public: OBrowserListBox( Window* pParent, WinBits nWinStyle = WB_DIALOGCONTROL ); ~OBrowserListBox(); void UpdateAll(); void Activate(sal_Bool _bActive = sal_True); sal_uInt16 CalcVisibleLines(); void EnableUpdate(); void DisableUpdate(); long Notify( NotifyEvent& _rNEvt ); void setListener(IPropertyLineListener* _pPLL); void Clear(); sal_uInt16 InsertEntry( const OLineDescriptor&, sal_uInt16 nPos = EDITOR_LIST_APPEND ); sal_Bool RemoveEntry( const ::rtl::OUString& _rName ); void ChangeEntry( const OLineDescriptor&, sal_uInt16 nPos ); void SetPropertyValue( const ::rtl::OUString & rEntryName, const ::rtl::OUString & rValue ); ::rtl::OUString GetPropertyValue( const ::rtl::OUString & rEntryName ) const; sal_uInt16 GetPropertyPos( const ::rtl::OUString& rEntryName ) const; IBrowserControl* GetPropertyControl( const ::rtl::OUString& rEntryName ); IBrowserControl* GetCurrentPropertyControl(); void EnablePropertyControls( const ::rtl::OUString& _rEntryName, bool _bEnableInput, bool _bEnablePrimaryButton, bool _bEnableSecondaryButton = false ); void EnablePropertyLine( const ::rtl::OUString& _rEntryName, bool _bEnable ); sal_Bool IsPropertyInputEnabled( const ::rtl::OUString& _rEntryName ) const; void SetFirstVisibleEntry(sal_uInt16 nPos); sal_uInt16 GetFirstVisibleEntry(); void SetSelectedEntry(sal_uInt16 nPos); sal_uInt16 GetSelectedEntry(); // #95343# -------------------------- sal_Int32 GetMinimumWidth(); sal_Bool IsModified( ) const; void CommitModified( ); protected: DECL_LINK( ScrollHdl, ScrollBar* ); // IBrowserControlListener void Modified (IBrowserControl* _pControl); void GetFocus (IBrowserControl* _pControl); void Commit (IBrowserControl* _pControl); void KeyInput (IBrowserControl* _pControl, const KeyCode& _rKey); void TravelLine (IBrowserControl* _pControl); // IButtonClickListener void buttonClicked( OBrowserLine* _pLine, bool _bPrimary ); }; //............................................................................ } // namespace pcr //............................................................................ #endif // _EXTENSIONS_PROPCTRLR_BROWSERLISTBOX_HXX_ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: linedescriptor.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2003-03-25 16:03:54 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _EXTENSIONS_PROPCTRLR_LINEDESCRIPTOR_HXX_ #define _EXTENSIONS_PROPCTRLR_LINEDESCRIPTOR_HXX_ #ifndef _EXTENSIONS_PROPCTRLR_BRWCONTROL_HXX_ #include "brwcontrol.hxx" #endif //............................................................................ namespace pcr { //............................................................................ class IBrowserControl; //======================================================================== //= OLineDescriptor //======================================================================== struct OLineDescriptor { String sName; String sTitle; String sValue; ::std::vector< String> aListValues; void* pDataPtr; IBrowserControl* pControl; BrowserControlType eControlType; sal_uInt32 nHelpId; sal_uInt32 nUniqueButtonId; sal_uInt16 nDigits; // for numeric fields sal_Int32 nMinValue; // for numeric fields only sal_Int32 nMaxValue; // for numeric fields only sal_Bool bUnknownValue :1; sal_Bool bHasDefaultValue:1; sal_Bool bHasBrowseButton:1; sal_Bool bIsHyperlink :1; sal_Bool bIsLocked :1; sal_Bool bHaveMinMax :1; OLineDescriptor() :eControlType(BCT_UNDEFINED) ,nHelpId(0) ,bUnknownValue(sal_False) ,bHasDefaultValue(sal_False) ,bHasBrowseButton(sal_False) ,bIsHyperlink(sal_False) ,bIsLocked(sal_False) ,pDataPtr(NULL) ,pControl(NULL) ,nDigits(0) ,nUniqueButtonId(0) ,nMinValue(0) ,nMaxValue(-1) ,bHaveMinMax(sal_False) { } // does not copy theValues // TODO: (fs) why? OLineDescriptor(const OLineDescriptor& rData) :eControlType(rData.eControlType) ,sValue(rData.sValue) ,sTitle(rData.sTitle) ,sName(rData.sName) ,nHelpId(rData.nHelpId) ,bUnknownValue(rData.bUnknownValue) ,bHasDefaultValue(rData.bHasDefaultValue) ,bHasBrowseButton(rData.bHasBrowseButton) ,bIsHyperlink(rData.bIsHyperlink) ,bIsLocked(rData.bIsLocked) ,pDataPtr(rData.pDataPtr) ,pControl(rData.pControl) ,nDigits(rData.nDigits) ,nUniqueButtonId(rData.nUniqueButtonId) ,nMinValue(rData.nMinValue) ,nMaxValue(rData.nMaxValue) ,bHaveMinMax(rData.bHaveMinMax) { } }; //............................................................................ } // namespace pcr //............................................................................ #endif _EXTENSIONS_PROPCTRLR_LINEDESCRIPTOR_HXX_ <commit_msg>INTEGRATION: CWS rt02 (1.2.96); FILE MERGED 2003/10/01 11:36:39 rt 1.2.96.1: #i19697# Fixed comment after preprocessor directive<commit_after>/************************************************************************* * * $RCSfile: linedescriptor.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2003-10-06 15:50:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _EXTENSIONS_PROPCTRLR_LINEDESCRIPTOR_HXX_ #define _EXTENSIONS_PROPCTRLR_LINEDESCRIPTOR_HXX_ #ifndef _EXTENSIONS_PROPCTRLR_BRWCONTROL_HXX_ #include "brwcontrol.hxx" #endif //............................................................................ namespace pcr { //............................................................................ class IBrowserControl; //======================================================================== //= OLineDescriptor //======================================================================== struct OLineDescriptor { String sName; String sTitle; String sValue; ::std::vector< String> aListValues; void* pDataPtr; IBrowserControl* pControl; BrowserControlType eControlType; sal_uInt32 nHelpId; sal_uInt32 nUniqueButtonId; sal_uInt16 nDigits; // for numeric fields sal_Int32 nMinValue; // for numeric fields only sal_Int32 nMaxValue; // for numeric fields only sal_Bool bUnknownValue :1; sal_Bool bHasDefaultValue:1; sal_Bool bHasBrowseButton:1; sal_Bool bIsHyperlink :1; sal_Bool bIsLocked :1; sal_Bool bHaveMinMax :1; OLineDescriptor() :eControlType(BCT_UNDEFINED) ,nHelpId(0) ,bUnknownValue(sal_False) ,bHasDefaultValue(sal_False) ,bHasBrowseButton(sal_False) ,bIsHyperlink(sal_False) ,bIsLocked(sal_False) ,pDataPtr(NULL) ,pControl(NULL) ,nDigits(0) ,nUniqueButtonId(0) ,nMinValue(0) ,nMaxValue(-1) ,bHaveMinMax(sal_False) { } // does not copy theValues // TODO: (fs) why? OLineDescriptor(const OLineDescriptor& rData) :eControlType(rData.eControlType) ,sValue(rData.sValue) ,sTitle(rData.sTitle) ,sName(rData.sName) ,nHelpId(rData.nHelpId) ,bUnknownValue(rData.bUnknownValue) ,bHasDefaultValue(rData.bHasDefaultValue) ,bHasBrowseButton(rData.bHasBrowseButton) ,bIsHyperlink(rData.bIsHyperlink) ,bIsLocked(rData.bIsLocked) ,pDataPtr(rData.pDataPtr) ,pControl(rData.pControl) ,nDigits(rData.nDigits) ,nUniqueButtonId(rData.nUniqueButtonId) ,nMinValue(rData.nMinValue) ,nMaxValue(rData.nMaxValue) ,bHaveMinMax(rData.bHaveMinMax) { } }; //............................................................................ } // namespace pcr //............................................................................ #endif // _EXTENSIONS_PROPCTRLR_LINEDESCRIPTOR_HXX_ <|endoftext|>
<commit_before>/* * blinkyBlocksSimulator.cpp * * Created on: 23 mars 2013 * Author: dom */ #include <iostream> #include "blinkyBlocksSimulator.h" #include <string.h> #include "trace.h" using namespace std; namespace BlinkyBlocks { BlinkyBlocksBlockCode*(* BlinkyBlocksSimulator::buildNewBlockCode)(BlinkyBlocksBlock*)=NULL; BlinkyBlocksSimulator::BlinkyBlocksSimulator(int argc, char *argv[], BlinkyBlocksBlockCode *(*blinkyBlocksBlockCodeBuildingFunction)(BlinkyBlocksBlock*)) : BaseSimulator::Simulator(argc, argv) { OUTPUT << "\033[1;34m" << "BlinkyBlocksSimulator constructor" << "\033[0m" << endl; int currentID = 1; BlinkyBlocksWorld *world = NULL; buildNewBlockCode = blinkyBlocksBlockCodeBuildingFunction; // PThy: Reading the command line may be needed at this time to enable debugging. TiXmlNode *node = xmlDoc->FirstChild("world"); if (node) { TiXmlElement* worldElement = node->ToElement(); const char *attr= worldElement->Attribute("gridSize"); int lx = 0; int ly = 0; int lz = 0; if (attr) { string str=attr; int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); lx = atoi(str.substr(0,pos1).c_str()); ly = atoi(str.substr(pos1+1,pos2-pos1-1).c_str()); lz = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str()); OUTPUT << "grid size : " << lx << " x " << ly << " x " << lz << endl; } else { OUTPUT << "WARNING No grid size in XML file" << endl; } attr=worldElement->Attribute("windowSize"); if (attr) { string str=attr; int pos = str.find_first_of(','); GlutContext::initialScreenWidth = atoi(str.substr(0,pos).c_str()); GlutContext::initialScreenHeight = atoi(str.substr(pos+1,str.length()-pos-1).c_str()); GlutContext::screenWidth = GlutContext::initialScreenWidth; GlutContext::screenHeight = GlutContext::initialScreenHeight; } createWorld(lx, ly, lz, argc, argv); world = getWorld(); world->loadTextures("../../simulatorCore/blinkyBlocksTextures"); } else { ERRPUT << "ERROR : NO world in XML file" << endl; exit(1); } createScheduler(); // Pthy: Not sure if we should be keeping that debugging part, perhaps it has to be located somewhere else now that MeldInterpreter has been embedded into VSim // if(debugging) { // createDebugger(); // } // loading the camera parameters TiXmlNode *nodeConfig = node->FirstChild("camera"); if (nodeConfig) { TiXmlElement* cameraElement = nodeConfig->ToElement(); const char *attr=cameraElement->Attribute("target"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); Vecteur target; target.pt[0] = atof(str.substr(0,pos1).c_str()); target.pt[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str()); target.pt[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str()); world->getCamera()->setTarget(target); } attr=cameraElement->Attribute("directionSpherical"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); float az,ele,dist; az = -90.0+atof(str.substr(0,pos1).c_str()); ele = atof(str.substr(pos1+1,pos2-pos1-1).c_str()); dist = atof(str.substr(pos2+1,str.length()-pos1-1).c_str()); world->getCamera()->setDirection(az,ele); world->getCamera()->setDistance(dist); } attr=cameraElement->Attribute("angle"); if (attr) { float angle = atof(attr); world->getCamera()->setAngle(angle); } double def_near=1,def_far=1500; attr=cameraElement->Attribute("near"); if (attr) { def_near = atof(attr); } attr=cameraElement->Attribute("far"); if (attr) { def_far = atof(attr); } world->getCamera()->setNearFar(def_near,def_far); } // loading the spotlight parameters nodeConfig = node->FirstChild("spotlight"); if (nodeConfig) { Vecteur target; float az=0,ele=60,dist=1000,angle=50; TiXmlElement* lightElement = nodeConfig->ToElement(); const char *attr=lightElement->Attribute("target"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); target.pt[0] = atof(str.substr(0,pos1).c_str()); target.pt[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str()); target.pt[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str()); } attr=lightElement->Attribute("directionSpherical"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); az = -90.0+atof(str.substr(0,pos1).c_str()); ele = atof(str.substr(pos1+1,pos2-pos1-1).c_str()); dist = atof(str.substr(pos2+1,str.length()-pos1-1).c_str()); } attr=lightElement->Attribute("angle"); if (attr) { angle = atof(attr); } float farplane=2.0*dist*tan(angle*M_PI/180.0); world->getCamera()->setLightParameters(target,az,ele,dist,angle,10.0,farplane); } // loading the blocks TiXmlNode *nodeBlock = node->FirstChild("blockList"); if (nodeBlock) { Color defaultColor = DARKGREY; TiXmlElement* element = nodeBlock->ToElement(); const char *attr= element->Attribute("color"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); defaultColor.rgba[0] = atof(str.substr(0,pos1).c_str())/255.0; defaultColor.rgba[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str())/255.0; defaultColor.rgba[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str())/255.0; } attr= element->Attribute("blocksize"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); float siz[3]; siz[0] = atof(str.substr(0,pos1).c_str()); siz[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str()); siz[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str()); OUTPUT << "blocksize =" << siz[0] <<"," << siz[1] <<"," << siz[2]<< endl; world->setBlocksSize(siz); } /* Reading a blinkyblock */ OUTPUT << "default color :" << defaultColor << endl; nodeBlock = nodeBlock->FirstChild("block"); Vecteur position; Color color; while (nodeBlock) { element = nodeBlock->ToElement(); color=defaultColor; attr = element->Attribute("color"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); color.set(atof(str.substr(0,pos1).c_str())/255.0, atof(str.substr(pos1+1,pos2-pos1-1).c_str())/255.0, atof(str.substr(pos2+1,str.length()-pos1-1).c_str())/255.0); OUTPUT << "color :" << color << endl; } attr = element->Attribute("position"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); position.pt[0] = atoi(str.substr(0,pos1).c_str()); position.pt[1] = atoi(str.substr(pos1+1,pos2-pos1-1).c_str()); position.pt[2] = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str()); OUTPUT << "position : " << position << endl; } world->addBlock(currentID++, BlinkyBlocksSimulator::buildNewBlockCode, position, color); nodeBlock = nodeBlock->NextSibling("block"); } // end while (nodeBlock) } else { // end if(nodeBlock) ERRPUT << "no Block List" << endl; } // loading the scenario TiXmlNode *nodeScenario = node->FirstChild("scenario"); if (nodeScenario) { bool autostart=false; TiXmlElement* element = nodeScenario->ToElement(); const char *attr= element->Attribute("autostart"); if (attr) { string str(attr); autostart=(str=="True" || str=="true"); } OUTPUT << "SCENARIO: Autostart=" << autostart << endl; /* Reading an event */ nodeScenario = nodeScenario->FirstChild("event"); float eventTime =0.0; int eventBlockId=-1; while (nodeScenario) { element = nodeScenario->ToElement(); attr = element->Attribute("time"); if (attr) { eventTime = atof(attr); } attr = element->Attribute("type"); if (attr) { string strAttr(attr); if (strAttr=="tap") { attr = element->Attribute("id"); eventBlockId=-1; if (attr) { eventBlockId=atoi(attr); } if (eventBlockId==-1) { ERRPUT << "SCENARIO:No id for tap event" << endl; } else { OUTPUT << "SCENARIO: tap(" << eventTime << "," << eventBlockId << ")" << endl; world->addScenarioEvent(new ScenarioTapEvent(eventTime,eventBlockId)); } } else if (strAttr=="debug") { attr = element->Attribute("id"); bool open=true; if (attr) { string str(attr); open = (str=="true" || str=="True"); } OUTPUT << "SCENARIO: debug(" << eventTime << "," << open << ")" << endl; world->addScenarioEvent(new ScenarioDebugEvent(eventTime,open)); } else if (strAttr=="selectBlock") { attr = element->Attribute("id"); eventBlockId=-1; if (attr) { eventBlockId=atoi(attr); } OUTPUT << "SCENARIO: selectBlock(" << eventTime << "," << eventBlockId << ")" << endl; world->addScenarioEvent(new ScenarioSelectBlockEvent(eventTime,eventBlockId)); } else if (strAttr=="addBlock") { attr = element->Attribute("position"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); Vecteur position; position.pt[0] = atoi(str.substr(0,pos1).c_str()); position.pt[1] = atoi(str.substr(pos1+1,pos2-pos1-1).c_str()); position.pt[2] = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str()); OUTPUT << "SCENARIO: addBlock(" << eventTime << "," << position << ")" << endl; world->addScenarioEvent(new ScenarioAddBlockEvent(eventTime,position)); } else { ERRPUT << "SCENARIO: No position for addBlock event" << endl; } } else { ERRPUT << "SCENARIO: event '" << attr << "': unknown !" << endl; } } else { ERRPUT << "SCENARIO: no Event type " << endl; } nodeScenario = nodeScenario->NextSibling("event"); } // while(nodeScenario) } world->linkBlocks(); //getScheduler()->sem_schedulerStart->post(); getScheduler()->setState(Scheduler::NOTSTARTED); GlutContext::mainLoop(); } BlinkyBlocksSimulator::~BlinkyBlocksSimulator() { OUTPUT << "\033[1;34m" << "BlinkyBlocksSimulator destructor" << "\033[0m" <<endl; } void BlinkyBlocksSimulator::createSimulator(int argc, char *argv[], BlinkyBlocksBlockCode *(*blinkyBlocksBlockCodeBuildingFunction)(BlinkyBlocksBlock*)) { simulator = new BlinkyBlocksSimulator(argc, argv, blinkyBlocksBlockCodeBuildingFunction); } void BlinkyBlocksSimulator::deleteSimulator() { delete((BlinkyBlocksSimulator*)simulator); } } // BlinkyBlocks namespace <commit_msg>attribute blocksize -> blockSize in BB config file parsing<commit_after>/* * blinkyBlocksSimulator.cpp * * Created on: 23 mars 2013 * Author: dom */ #include <iostream> #include "blinkyBlocksSimulator.h" #include <string.h> #include "trace.h" using namespace std; namespace BlinkyBlocks { BlinkyBlocksBlockCode*(* BlinkyBlocksSimulator::buildNewBlockCode)(BlinkyBlocksBlock*)=NULL; BlinkyBlocksSimulator::BlinkyBlocksSimulator(int argc, char *argv[], BlinkyBlocksBlockCode *(*blinkyBlocksBlockCodeBuildingFunction)(BlinkyBlocksBlock*)) : BaseSimulator::Simulator(argc, argv) { OUTPUT << "\033[1;34m" << "BlinkyBlocksSimulator constructor" << "\033[0m" << endl; int currentID = 1; BlinkyBlocksWorld *world = NULL; buildNewBlockCode = blinkyBlocksBlockCodeBuildingFunction; // PThy: Reading the command line may be needed at this time to enable debugging. TiXmlNode *node = xmlDoc->FirstChild("world"); if (node) { TiXmlElement* worldElement = node->ToElement(); const char *attr= worldElement->Attribute("gridSize"); int lx = 0; int ly = 0; int lz = 0; if (attr) { string str=attr; int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); lx = atoi(str.substr(0,pos1).c_str()); ly = atoi(str.substr(pos1+1,pos2-pos1-1).c_str()); lz = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str()); OUTPUT << "grid size : " << lx << " x " << ly << " x " << lz << endl; } else { OUTPUT << "WARNING No grid size in XML file" << endl; } attr=worldElement->Attribute("windowSize"); if (attr) { string str=attr; int pos = str.find_first_of(','); GlutContext::initialScreenWidth = atoi(str.substr(0,pos).c_str()); GlutContext::initialScreenHeight = atoi(str.substr(pos+1,str.length()-pos-1).c_str()); GlutContext::screenWidth = GlutContext::initialScreenWidth; GlutContext::screenHeight = GlutContext::initialScreenHeight; } createWorld(lx, ly, lz, argc, argv); world = getWorld(); world->loadTextures("../../simulatorCore/blinkyBlocksTextures"); } else { ERRPUT << "ERROR : NO world in XML file" << endl; exit(1); } createScheduler(); // Pthy: Not sure if we should be keeping that debugging part, perhaps it has to be located somewhere else now that MeldInterpreter has been embedded into VSim // if(debugging) { // createDebugger(); // } // loading the camera parameters TiXmlNode *nodeConfig = node->FirstChild("camera"); if (nodeConfig) { TiXmlElement* cameraElement = nodeConfig->ToElement(); const char *attr=cameraElement->Attribute("target"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); Vecteur target; target.pt[0] = atof(str.substr(0,pos1).c_str()); target.pt[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str()); target.pt[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str()); world->getCamera()->setTarget(target); } attr=cameraElement->Attribute("directionSpherical"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); float az,ele,dist; az = -90.0+atof(str.substr(0,pos1).c_str()); ele = atof(str.substr(pos1+1,pos2-pos1-1).c_str()); dist = atof(str.substr(pos2+1,str.length()-pos1-1).c_str()); world->getCamera()->setDirection(az,ele); world->getCamera()->setDistance(dist); } attr=cameraElement->Attribute("angle"); if (attr) { float angle = atof(attr); world->getCamera()->setAngle(angle); } double def_near=1,def_far=1500; attr=cameraElement->Attribute("near"); if (attr) { def_near = atof(attr); } attr=cameraElement->Attribute("far"); if (attr) { def_far = atof(attr); } world->getCamera()->setNearFar(def_near,def_far); } // loading the spotlight parameters nodeConfig = node->FirstChild("spotlight"); if (nodeConfig) { Vecteur target; float az=0,ele=60,dist=1000,angle=50; TiXmlElement* lightElement = nodeConfig->ToElement(); const char *attr=lightElement->Attribute("target"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); target.pt[0] = atof(str.substr(0,pos1).c_str()); target.pt[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str()); target.pt[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str()); } attr=lightElement->Attribute("directionSpherical"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); az = -90.0+atof(str.substr(0,pos1).c_str()); ele = atof(str.substr(pos1+1,pos2-pos1-1).c_str()); dist = atof(str.substr(pos2+1,str.length()-pos1-1).c_str()); } attr=lightElement->Attribute("angle"); if (attr) { angle = atof(attr); } float farplane=2.0*dist*tan(angle*M_PI/180.0); world->getCamera()->setLightParameters(target,az,ele,dist,angle,10.0,farplane); } // loading the blocks TiXmlNode *nodeBlock = node->FirstChild("blockList"); if (nodeBlock) { Color defaultColor = DARKGREY; TiXmlElement* element = nodeBlock->ToElement(); const char *attr= element->Attribute("color"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); defaultColor.rgba[0] = atof(str.substr(0,pos1).c_str())/255.0; defaultColor.rgba[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str())/255.0; defaultColor.rgba[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str())/255.0; } attr= element->Attribute("blockSize"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); float siz[3]; siz[0] = atof(str.substr(0,pos1).c_str()); siz[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str()); siz[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str()); OUTPUT << "blockSize =" << siz[0] <<"," << siz[1] <<"," << siz[2]<< endl; world->setBlocksSize(siz); } /* Reading a blinkyblock */ OUTPUT << "default color :" << defaultColor << endl; nodeBlock = nodeBlock->FirstChild("block"); Vecteur position; Color color; while (nodeBlock) { element = nodeBlock->ToElement(); color=defaultColor; attr = element->Attribute("color"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); color.set(atof(str.substr(0,pos1).c_str())/255.0, atof(str.substr(pos1+1,pos2-pos1-1).c_str())/255.0, atof(str.substr(pos2+1,str.length()-pos1-1).c_str())/255.0); OUTPUT << "color :" << color << endl; } attr = element->Attribute("position"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); position.pt[0] = atoi(str.substr(0,pos1).c_str()); position.pt[1] = atoi(str.substr(pos1+1,pos2-pos1-1).c_str()); position.pt[2] = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str()); OUTPUT << "position : " << position << endl; } world->addBlock(currentID++, BlinkyBlocksSimulator::buildNewBlockCode, position, color); nodeBlock = nodeBlock->NextSibling("block"); } // end while (nodeBlock) } else { // end if(nodeBlock) ERRPUT << "no Block List" << endl; } // loading the scenario TiXmlNode *nodeScenario = node->FirstChild("scenario"); if (nodeScenario) { bool autostart=false; TiXmlElement* element = nodeScenario->ToElement(); const char *attr= element->Attribute("autostart"); if (attr) { string str(attr); autostart=(str=="True" || str=="true"); } OUTPUT << "SCENARIO: Autostart=" << autostart << endl; /* Reading an event */ nodeScenario = nodeScenario->FirstChild("event"); float eventTime =0.0; int eventBlockId=-1; while (nodeScenario) { element = nodeScenario->ToElement(); attr = element->Attribute("time"); if (attr) { eventTime = atof(attr); } attr = element->Attribute("type"); if (attr) { string strAttr(attr); if (strAttr=="tap") { attr = element->Attribute("id"); eventBlockId=-1; if (attr) { eventBlockId=atoi(attr); } if (eventBlockId==-1) { ERRPUT << "SCENARIO:No id for tap event" << endl; } else { OUTPUT << "SCENARIO: tap(" << eventTime << "," << eventBlockId << ")" << endl; world->addScenarioEvent(new ScenarioTapEvent(eventTime,eventBlockId)); } } else if (strAttr=="debug") { attr = element->Attribute("id"); bool open=true; if (attr) { string str(attr); open = (str=="true" || str=="True"); } OUTPUT << "SCENARIO: debug(" << eventTime << "," << open << ")" << endl; world->addScenarioEvent(new ScenarioDebugEvent(eventTime,open)); } else if (strAttr=="selectBlock") { attr = element->Attribute("id"); eventBlockId=-1; if (attr) { eventBlockId=atoi(attr); } OUTPUT << "SCENARIO: selectBlock(" << eventTime << "," << eventBlockId << ")" << endl; world->addScenarioEvent(new ScenarioSelectBlockEvent(eventTime,eventBlockId)); } else if (strAttr=="addBlock") { attr = element->Attribute("position"); if (attr) { string str(attr); int pos1 = str.find_first_of(','), pos2 = str.find_last_of(','); Vecteur position; position.pt[0] = atoi(str.substr(0,pos1).c_str()); position.pt[1] = atoi(str.substr(pos1+1,pos2-pos1-1).c_str()); position.pt[2] = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str()); OUTPUT << "SCENARIO: addBlock(" << eventTime << "," << position << ")" << endl; world->addScenarioEvent(new ScenarioAddBlockEvent(eventTime,position)); } else { ERRPUT << "SCENARIO: No position for addBlock event" << endl; } } else { ERRPUT << "SCENARIO: event '" << attr << "': unknown !" << endl; } } else { ERRPUT << "SCENARIO: no Event type " << endl; } nodeScenario = nodeScenario->NextSibling("event"); } // while(nodeScenario) } world->linkBlocks(); //getScheduler()->sem_schedulerStart->post(); getScheduler()->setState(Scheduler::NOTSTARTED); GlutContext::mainLoop(); } BlinkyBlocksSimulator::~BlinkyBlocksSimulator() { OUTPUT << "\033[1;34m" << "BlinkyBlocksSimulator destructor" << "\033[0m" <<endl; } void BlinkyBlocksSimulator::createSimulator(int argc, char *argv[], BlinkyBlocksBlockCode *(*blinkyBlocksBlockCodeBuildingFunction)(BlinkyBlocksBlock*)) { simulator = new BlinkyBlocksSimulator(argc, argv, blinkyBlocksBlockCodeBuildingFunction); } void BlinkyBlocksSimulator::deleteSimulator() { delete((BlinkyBlocksSimulator*)simulator); } } // BlinkyBlocks namespace <|endoftext|>
<commit_before>// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie <dpetrie AT SIPez DOT com> // SYSTEM INCLUDES #include <assert.h> // APPLICATION INCLUDES #include <mp/MpBuf.h> #include <mp/MprAudioFrameBuffer.h> // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MprAudioFrameBuffer::MprAudioFrameBuffer(const UtlString& rName, int samplesPerFrame, int samplesPerSec, int numFramesOfHistory) : MpAudioResource(rName, 0, 1, 0, 1, samplesPerFrame, samplesPerSec), mFrameCount(0), mNumBufferFrames(numFramesOfHistory), mpBufferedFrameArray(NULL) { mpBufferedFrameArray = new MpBufPtr[mNumBufferFrames]; } // Destructor MprAudioFrameBuffer::~MprAudioFrameBuffer() { } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ UtlBoolean MprAudioFrameBuffer::doProcessFrame(MpBufPtr inBufs[], MpBufPtr outBufs[], int inBufsSize, int outBufsSize, UtlBoolean isEnabled, int samplesPerFrame, int samplesPerSecond) { mFrameCount++; if (!isEnabled) { } else { if(inBufs[0].isValid()) { // Valid buffer, keep a reference mpBufferedFrameArray[mFrameCount % mNumBufferFrames] = inBufs[0]; } else { // invalid buffer, clear the reference mpBufferedFrameArray[mFrameCount % mNumBufferFrames].release(); } } if(inBufs[0].isValid()) { outBufs[0] = inBufs[0]; } return TRUE; } OsStatus MprAudioFrameBuffer::getFrame(int pastFramesIndex, MpBufPtr& frameBuffer) { OsStatus status; assert(pastFramesIndex >= 0); assert(pastFramesIndex < mNumBufferFrames); if(pastFramesIndex >= 0 && pastFramesIndex < mNumBufferFrames) { frameBuffer = mpBufferedFrameArray[(mFrameCount + pastFramesIndex) % mNumBufferFrames]; status = OS_SUCCESS; } else { status = OS_NOT_FOUND; } return(status); } /* ============================ FUNCTIONS ================================= */ <commit_msg>Fixed stupid memory leak. Thanks Alex.<commit_after>// // Copyright (C) 2007 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // $$ /////////////////////////////////////////////////////////////////////////////// // Author: Dan Petrie <dpetrie AT SIPez DOT com> // SYSTEM INCLUDES #include <assert.h> // APPLICATION INCLUDES #include <mp/MpBuf.h> #include <mp/MprAudioFrameBuffer.h> // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MprAudioFrameBuffer::MprAudioFrameBuffer(const UtlString& rName, int samplesPerFrame, int samplesPerSec, int numFramesOfHistory) : MpAudioResource(rName, 0, 1, 0, 1, samplesPerFrame, samplesPerSec), mFrameCount(0), mNumBufferFrames(numFramesOfHistory), mpBufferedFrameArray(NULL) { mpBufferedFrameArray = new MpBufPtr[mNumBufferFrames]; } // Destructor MprAudioFrameBuffer::~MprAudioFrameBuffer() { if(mpBufferedFrameArray) { delete mpBufferedFrameArray; mpBufferedFrameArray = NULL; } } /* ============================ MANIPULATORS ============================== */ /* ============================ ACCESSORS ================================= */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ UtlBoolean MprAudioFrameBuffer::doProcessFrame(MpBufPtr inBufs[], MpBufPtr outBufs[], int inBufsSize, int outBufsSize, UtlBoolean isEnabled, int samplesPerFrame, int samplesPerSecond) { mFrameCount++; if (!isEnabled) { } else { if(inBufs[0].isValid()) { // Valid buffer, keep a reference mpBufferedFrameArray[mFrameCount % mNumBufferFrames] = inBufs[0]; } else { // invalid buffer, clear the reference mpBufferedFrameArray[mFrameCount % mNumBufferFrames].release(); } } if(inBufs[0].isValid()) { outBufs[0] = inBufs[0]; } return TRUE; } OsStatus MprAudioFrameBuffer::getFrame(int pastFramesIndex, MpBufPtr& frameBuffer) { OsStatus status; assert(pastFramesIndex >= 0); assert(pastFramesIndex < mNumBufferFrames); if(pastFramesIndex >= 0 && pastFramesIndex < mNumBufferFrames) { frameBuffer = mpBufferedFrameArray[(mFrameCount + pastFramesIndex) % mNumBufferFrames]; status = OS_SUCCESS; } else { status = OS_NOT_FOUND; } return(status); } /* ============================ FUNCTIONS ================================= */ <|endoftext|>
<commit_before>#include <ctime> #include <iostream> #include <vector> #include "boost/variant.hpp" #include "type_switchN-patterns-xtl.hpp" #include "adapt_boost_variant.hpp" #include "patterns/all.hpp" struct P { int i; }; struct Q { int i; }; struct R { int i; }; struct M { int i; }; struct N { int i; }; typedef boost::variant<P, Q, R> VP; typedef boost::variant<M, N> VM; int g_pm = 0; int g_qm = 0; int g_rm = 0; int g_pn = 0; int g_qn = 0; int g_rn = 0; void count_with_mach7(VP const& vp, VM const& vm) { using mch::C; Match(vp, vm) { Case(C<P>(), C<M>()) ++g_pm; break; Case(C<Q>(), C<M>()) ++g_qm; break; Case(C<R>(), C<M>()) ++g_rm; break; Case(C<P>(), C<N>()) ++g_pn; break; Case(C<Q>(), C<N>()) ++g_qn; break; Case(C<R>(), C<N>()) ++g_rn; break; } EndMatch } void count_with_visitor(VP const& vp, VM const& vm) { struct increment : boost::static_visitor<> { void operator()(const P&, const M&) const { ++g_pm; } void operator()(const Q&, const M&) const { ++g_qm; } void operator()(const R&, const M&) const { ++g_rm; } void operator()(const P&, const N&) const { ++g_pn; } void operator()(const Q&, const N&) const { ++g_qn; } void operator()(const R&, const N&) const { ++g_rn; } }; apply_visitor(increment{}, vp, vm); } struct result { clock_t mach7; clock_t visit; }; result measure(const std::vector<VP>& vecp, const std::vector<VM>& vecm, const bool mach7_first) { result ans{}; if (mach7_first) { clock_t t0 = clock(); for (const VP& vp : vecp) for (const VM& vm : vecm) count_with_mach7(vp, vm); clock_t t1 = clock(); ans.mach7 = (t1 - t0); } { clock_t t0 = clock(); for (const VP& vp : vecp) for (const VM& vm : vecm) count_with_visitor(vp, vm); clock_t t1 = clock(); ans.visit = (t1 - t0); } if (!mach7_first) { clock_t t0 = clock(); for (const VP& vp : vecp) for (const VM& vm : vecm) count_with_mach7(vp, vm); clock_t t1 = clock(); ans.mach7 = (t1 - t0); } return ans; } void populate_data(std::vector<VP>& vec_vp, std::vector<VM>& vec_vm, const int SIZE) { vec_vm.reserve(SIZE); vec_vp.reserve(SIZE); for(int i = 0; i != SIZE; ++i) { if (i % 3 == 0) vec_vp.push_back(P{0}); else if (i % 3 == 1) vec_vp.push_back(Q{0}); else vec_vp.push_back(R{0}); if (i % 2 == 0) vec_vm.push_back(M{0}); else vec_vm.push_back(N{0}); } } const int DATA_SIZE = 7000; const int TEST_NUM = 6; int main() { std::vector<VP> vec_vp; std::vector<VM> vec_vm; populate_data(vec_vp, vec_vm, DATA_SIZE); std::vector<result> results; for (int i = 0; i < TEST_NUM; i += 2) { results.push_back(measure(vec_vp, vec_vm, true)); results.push_back(measure(vec_vp, vec_vm, false)); } std::cout << "mach7" "\t" "visit" << std::endl; for (const result& r : results) std::cout << r.mach7 << "\t" << r.visit << std::endl; } <commit_msg>Manually inlined the timed calls to make sure both get inlined (or none). This was scewing results before with regular visitors. The performance regression still exists. Issue #15<commit_after>#include <ctime> #include <iostream> #include <vector> #include "boost/variant.hpp" #include "type_switchN-patterns-xtl.hpp" #include "adapt_boost_variant.hpp" #include "patterns/all.hpp" struct P { int i; }; struct Q { int i; }; struct R { int i; }; struct M { int i; }; struct N { int i; }; typedef boost::variant<P, Q, R> VP; typedef boost::variant<M, N> VM; int g_pm = 0; int g_qm = 0; int g_rm = 0; int g_pn = 0; int g_qn = 0; int g_rn = 0; struct result { clock_t mach7; clock_t visit; }; result measure(const std::vector<VP>& vecp, const std::vector<VM>& vecm, const bool mach7_first) { result ans{}; if (mach7_first) { clock_t t0 = clock(); for (const VP& vp : vecp) for (const VM& vm : vecm) { using mch::C; Match(vp, vm) { Case(C<P>(), C<M>()) ++g_pm; break; Case(C<Q>(), C<M>()) ++g_qm; break; Case(C<R>(), C<M>()) ++g_rm; break; Case(C<P>(), C<N>()) ++g_pn; break; Case(C<Q>(), C<N>()) ++g_qn; break; Case(C<R>(), C<N>()) ++g_rn; break; } EndMatch } clock_t t1 = clock(); ans.mach7 = (t1 - t0); } { clock_t t0 = clock(); for (const VP& vp : vecp) for (const VM& vm : vecm) { struct increment : boost::static_visitor<> { void operator()(const P&, const M&) const { ++g_pm; } void operator()(const Q&, const M&) const { ++g_qm; } void operator()(const R&, const M&) const { ++g_rm; } void operator()(const P&, const N&) const { ++g_pn; } void operator()(const Q&, const N&) const { ++g_qn; } void operator()(const R&, const N&) const { ++g_rn; } }; apply_visitor(increment{}, vp, vm); } clock_t t1 = clock(); ans.visit = (t1 - t0); } if (!mach7_first) { clock_t t0 = clock(); for (const VP& vp : vecp) for (const VM& vm : vecm) { using mch::C; Match(vp, vm) { Case(C<P>(), C<M>()) ++g_pm; break; Case(C<Q>(), C<M>()) ++g_qm; break; Case(C<R>(), C<M>()) ++g_rm; break; Case(C<P>(), C<N>()) ++g_pn; break; Case(C<Q>(), C<N>()) ++g_qn; break; Case(C<R>(), C<N>()) ++g_rn; break; } EndMatch } clock_t t1 = clock(); ans.mach7 = (t1 - t0); } return ans; } void populate_data(std::vector<VP>& vec_vp, std::vector<VM>& vec_vm, const int SIZE) { vec_vm.reserve(SIZE); vec_vp.reserve(SIZE); for(int i = 0; i != SIZE; ++i) { if (i % 3 == 0) vec_vp.push_back(P{0}); else if (i % 3 == 1) vec_vp.push_back(Q{0}); else vec_vp.push_back(R{0}); if (i % 2 == 0) vec_vm.push_back(M{0}); else vec_vm.push_back(N{0}); } } const int DATA_SIZE = 7000; const int TEST_NUM = 6; int main() { std::vector<VP> vec_vp; std::vector<VM> vec_vm; populate_data(vec_vp, vec_vm, DATA_SIZE); std::vector<result> results; for (int i = 0; i < TEST_NUM; i += 2) { results.push_back(measure(vec_vp, vec_vm, true)); results.push_back(measure(vec_vp, vec_vm, false)); } std::cout << "mach7" "\t" "visit" << std::endl; for (const result& r : results) std::cout << r.mach7 << "\t" << r.visit << std::endl; } <|endoftext|>
<commit_before>#include <ftl/ProcessFactory.hpp> #include <ftl/Dir.hpp> #include <ftl/Path.hpp> #include <ftl/Format.hpp> #include <ftl/PrintDebug.hpp> // debug #include "Supervisor.hpp" #include "HaxeMessageSyntax.hpp" #include "InterpositionServer.hpp" #include "HaxeCodetips.hpp" namespace codetips { CODETIPS_REGISTRATION_IMPL(HaxeCodetips) HaxeCodetips::HaxeCodetips() : processFactory_(new ProcessFactory), messageSyntax_(new HaxeMessageSyntax) { Path haxe = Path::lookup(Process::env("PATH").split(":"), "haxe", File::Exists|File::Execute); processFactory_->setExecPath(haxe); processFactory_->setIoPolicy(Process::ForwardOutput|Process::ErrorToOutput); InterpositionServer::injectClient(processFactory_->envMap()); setResource("haxe", haxe); update(); } void HaxeCodetips::update() { Path haxe = resource("haxe"); printTo(log(), "HaxeCodetips::update(): haxe = %%\n", haxe); if (haxe != "") { if (File(haxe).access(File::Read|File::Execute)) printTo(log(), "Found 'haxe' binary at \"%%\".\n", haxe); else printTo(log(), "Insufficiant permissions to 'haxe' binary.\n"); } else { printTo(log(), "Can't find the 'haxe' binary.\n"); printTo(log(), "Please provide the path to the 'haxe' binary.\n"); } } String HaxeCodetips::language() const { return "haxe"; } String HaxeCodetips::name() const { return "codetips"; } String HaxeCodetips::displayName() const { return "haXe Code Tips"; } String HaxeCodetips::description() const { return "Provides code tips for haxe. Press <Tab> key after \".\" for invocation."; } Ref<Tip, Owner> HaxeCodetips::assist(Ref<Context> context, int modifiers, uchar_t key) { if ( (key != '\t') || ((modifiers != Shift) && (modifiers != 0)) || (processFactory_->execPath() == "") ) return 0; if (modifiers == 0) { String line = context->line(); if (context->cursorColumn() == 0) return 0; char ch = line.get(line.first() + context->cursorColumn() - 1); if ((ch != '.') && (ch != '(')) return 0; } String className = Path(context->path()).fileNameSansExtension(); String projectFile = ""; String searchPath = context->path(); while (searchPath != "/") { searchPath = Path(searchPath).reduce(); Dir dir(searchPath); while (dir.hasNext()) { Ref<DirEntry, Owner> entry = dir.next(); Ref<StringList, Owner> parts = entry->name().split("."); if (parts->at(parts->last()) == "hxml") { projectFile = Format("%%/%%") << searchPath << entry->name(); break; } } } if (projectFile == "") return 0; processFactory_->setWorkingDirectory(Path(projectFile).reduce()); // debug("HaxeCodetips::assist(): processFactory_->execPath() = \"%%\"\n", processFactory_->execPath()); String options = Format("%% %% --display %%@%%") << projectFile << className << context->path() << context->cursorByte(); // debug("HaxeCodetips::assist(): options = \"%%\"\n", options); processFactory_->setOptions(options.split(" ")); Ref<Process, Owner> process = processFactory_->produce(); String message = process->rawOutput()->readAll(); // debug("HaxeCodetips::assist(): message = \"%%\"\n", message); Ref<Tip, Owner> tip = messageSyntax_->parse(message); if ((!tip) && (message != "")) tip = new TypeTip(new Type(message)); return tip; } } // namespace codetips <commit_msg>Minor fix.<commit_after>#include <ftl/ProcessFactory.hpp> #include <ftl/Dir.hpp> #include <ftl/Path.hpp> #include <ftl/Format.hpp> #include <ftl/PrintDebug.hpp> // debug #include "Supervisor.hpp" #include "HaxeMessageSyntax.hpp" #include "InterpositionServer.hpp" #include "HaxeCodetips.hpp" namespace codetips { CODETIPS_REGISTRATION_IMPL(HaxeCodetips) HaxeCodetips::HaxeCodetips() : processFactory_(new ProcessFactory), messageSyntax_(new HaxeMessageSyntax) { Path haxe = Path::lookup(Process::env("PATH").split(":"), "haxe", File::Exists|File::Execute); processFactory_->setExecPath(haxe); processFactory_->setIoPolicy(Process::ForwardOutput|Process::ErrorToOutput); InterpositionServer::injectClient(processFactory_->envMap()); setResource("haxe", haxe); update(); } void HaxeCodetips::update() { Path haxe = resource("haxe"); printTo(log(), "HaxeCodetips::update(): haxe = %%\n", haxe); if (haxe != "") { if (File(haxe).access(File::Read|File::Execute)) printTo(log(), "Found 'haxe' binary at \"%%\".\n", haxe); else printTo(log(), "Insufficiant permissions to 'haxe' binary.\n"); } else { printTo(log(), "Can't find the 'haxe' binary.\n"); printTo(log(), "Please provide the path to the 'haxe' binary.\n"); } } String HaxeCodetips::language() const { return "haxe"; } String HaxeCodetips::name() const { return "codetips"; } String HaxeCodetips::displayName() const { return "haXe Code Tips"; } String HaxeCodetips::description() const { return "Provides code tips for haxe. Press TAB key after \".\" or \"(\" for invocation."; } Ref<Tip, Owner> HaxeCodetips::assist(Ref<Context> context, int modifiers, uchar_t key) { if ( (key != '\t') || ((modifiers != Shift) && (modifiers != 0)) || (processFactory_->execPath() == "") ) return 0; if (modifiers == 0) { String line = context->line(); if (context->cursorColumn() == 0) return 0; char ch = line.get(line.first() + context->cursorColumn() - 1); if ((ch != '.') && (ch != '(')) return 0; } String className = Path(context->path()).fileNameSansExtension(); String projectFile = ""; String searchPath = context->path(); while (searchPath != "/") { searchPath = Path(searchPath).reduce(); Dir dir(searchPath); while (dir.hasNext()) { Ref<DirEntry, Owner> entry = dir.next(); Ref<StringList, Owner> parts = entry->name().split("."); if (parts->at(parts->last()) == "hxml") { projectFile = Format("%%/%%") << searchPath << entry->name(); break; } } } if (projectFile == "") return 0; processFactory_->setWorkingDirectory(Path(projectFile).reduce()); // debug("HaxeCodetips::assist(): processFactory_->execPath() = \"%%\"\n", processFactory_->execPath()); String options = Format("%% %% --display %%@%%") << projectFile << className << context->path() << context->cursorByte(); // debug("HaxeCodetips::assist(): options = \"%%\"\n", options); processFactory_->setOptions(options.split(" ")); Ref<Process, Owner> process = processFactory_->produce(); String message = process->rawOutput()->readAll(); // debug("HaxeCodetips::assist(): message = \"%%\"\n", message); Ref<Tip, Owner> tip = messageSyntax_->parse(message); if ((!tip) && (message != "")) tip = new TypeTip(new Type(message)); return tip; } } // namespace codetips <|endoftext|>
<commit_before>#ifndef SpMVAcceleratorDriver_H #define SpMVAcceleratorDriver_H #include <assert.h> class SpMVAcceleratorBufferAllDriver { public: static unsigned int expSignature() {return 0xccd68766;}; SpMVAcceleratorDriver(volatile unsigned int * baseAddr) { m_baseAddr = baseAddr; assert(signature() == expSignature());}; // read+write register: startInit index: 10 void startInit(unsigned int v) {m_baseAddr[10] = v;}; unsigned int startInit() {return m_baseAddr[10];}; // read+write register: startRegular index: 11 void startRegular(unsigned int v) {m_baseAddr[11] = v;}; unsigned int startRegular() {return m_baseAddr[11];}; // read+write register: startWrite index: 12 void startWrite(unsigned int v) {m_baseAddr[12] = v;}; unsigned int startWrite() {return m_baseAddr[12];}; // read+write register: numRows index: 13 void numRows(unsigned int v) {m_baseAddr[13] = v;}; unsigned int numRows() {return m_baseAddr[13];}; // read+write register: numCols index: 14 void numCols(unsigned int v) {m_baseAddr[14] = v;}; unsigned int numCols() {return m_baseAddr[14];}; // read+write register: numNZ index: 15 void numNZ(unsigned int v) {m_baseAddr[15] = v;}; unsigned int numNZ() {return m_baseAddr[15];}; // read+write register: baseColPtr index: 16 void baseColPtr(unsigned int v) {m_baseAddr[16] = v;}; unsigned int baseColPtr() {return m_baseAddr[16];}; // read+write register: baseRowInd index: 17 void baseRowInd(unsigned int v) {m_baseAddr[17] = v;}; unsigned int baseRowInd() {return m_baseAddr[17];}; // read+write register: baseNZData index: 18 void baseNZData(unsigned int v) {m_baseAddr[18] = v;}; unsigned int baseNZData() {return m_baseAddr[18];}; // read+write register: baseInputVec index: 19 void baseInputVec(unsigned int v) {m_baseAddr[19] = v;}; unsigned int baseInputVec() {return m_baseAddr[19];}; // read+write register: baseOutputVec index: 20 void baseOutputVec(unsigned int v) {m_baseAddr[20] = v;}; unsigned int baseOutputVec() {return m_baseAddr[20];}; // read+write register: thresColPtr index: 21 void thresColPtr(unsigned int v) {m_baseAddr[21] = v;}; unsigned int thresColPtr() {return m_baseAddr[21];}; // read+write register: thresRowInd index: 22 void thresRowInd(unsigned int v) {m_baseAddr[22] = v;}; unsigned int thresRowInd() {return m_baseAddr[22];}; // read+write register: thresNZData index: 23 void thresNZData(unsigned int v) {m_baseAddr[23] = v;}; unsigned int thresNZData() {return m_baseAddr[23];}; // read+write register: thresInputVec index: 24 void thresInputVec(unsigned int v) {m_baseAddr[24] = v;}; unsigned int thresInputVec() {return m_baseAddr[24];}; // read+write register: statBackend index: 1 void statBackend(unsigned int v) {m_baseAddr[1] = v;}; unsigned int statBackend() {return m_baseAddr[1];}; // read+write register: statFrontend index: 2 void statFrontend(unsigned int v) {m_baseAddr[2] = v;}; unsigned int statFrontend() {return m_baseAddr[2];}; // read+write register: hazardStalls index: 3 void hazardStalls(unsigned int v) {m_baseAddr[3] = v;}; unsigned int hazardStalls() {return m_baseAddr[3];}; // read+write register: bwMon_totalCycles index: 4 void bwMon_totalCycles(unsigned int v) {m_baseAddr[4] = v;}; unsigned int bwMon_totalCycles() {return m_baseAddr[4];}; // read+write register: bwMon_activeCycles index: 5 void bwMon_activeCycles(unsigned int v) {m_baseAddr[5] = v;}; unsigned int bwMon_activeCycles() {return m_baseAddr[5];}; // read+write register: ocmWords index: 6 void ocmWords(unsigned int v) {m_baseAddr[6] = v;}; unsigned int ocmWords() {return m_baseAddr[6];}; // read+write register: fifoCountsCPRI index: 7 void fifoCountsCPRI(unsigned int v) {m_baseAddr[7] = v;}; unsigned int fifoCountsCPRI() {return m_baseAddr[7];}; // read+write register: fifoCountsNZIV index: 8 void fifoCountsNZIV(unsigned int v) {m_baseAddr[8] = v;}; unsigned int fifoCountsNZIV() {return m_baseAddr[8];}; // read+write register: debug index: 9 void debug(unsigned int v) {m_baseAddr[9] = v;}; unsigned int debug() {return m_baseAddr[9];}; // read+write register: signature index: 0 void signature(unsigned int v) {m_baseAddr[0] = v;}; unsigned int signature() {return m_baseAddr[0];}; protected: volatile unsigned int * m_baseAddr; }; #endif <commit_msg>typo fix<commit_after>#ifndef SpMVAcceleratorDriver_H #define SpMVAcceleratorDriver_H #include <assert.h> class SpMVAcceleratorBufferAllDriver { public: static unsigned int expSignature() {return 0xccd68766;}; SpMVAcceleratorBufferAllDriver(volatile unsigned int * baseAddr) { m_baseAddr = baseAddr; assert(signature() == expSignature());}; // read+write register: startInit index: 10 void startInit(unsigned int v) {m_baseAddr[10] = v;}; unsigned int startInit() {return m_baseAddr[10];}; // read+write register: startRegular index: 11 void startRegular(unsigned int v) {m_baseAddr[11] = v;}; unsigned int startRegular() {return m_baseAddr[11];}; // read+write register: startWrite index: 12 void startWrite(unsigned int v) {m_baseAddr[12] = v;}; unsigned int startWrite() {return m_baseAddr[12];}; // read+write register: numRows index: 13 void numRows(unsigned int v) {m_baseAddr[13] = v;}; unsigned int numRows() {return m_baseAddr[13];}; // read+write register: numCols index: 14 void numCols(unsigned int v) {m_baseAddr[14] = v;}; unsigned int numCols() {return m_baseAddr[14];}; // read+write register: numNZ index: 15 void numNZ(unsigned int v) {m_baseAddr[15] = v;}; unsigned int numNZ() {return m_baseAddr[15];}; // read+write register: baseColPtr index: 16 void baseColPtr(unsigned int v) {m_baseAddr[16] = v;}; unsigned int baseColPtr() {return m_baseAddr[16];}; // read+write register: baseRowInd index: 17 void baseRowInd(unsigned int v) {m_baseAddr[17] = v;}; unsigned int baseRowInd() {return m_baseAddr[17];}; // read+write register: baseNZData index: 18 void baseNZData(unsigned int v) {m_baseAddr[18] = v;}; unsigned int baseNZData() {return m_baseAddr[18];}; // read+write register: baseInputVec index: 19 void baseInputVec(unsigned int v) {m_baseAddr[19] = v;}; unsigned int baseInputVec() {return m_baseAddr[19];}; // read+write register: baseOutputVec index: 20 void baseOutputVec(unsigned int v) {m_baseAddr[20] = v;}; unsigned int baseOutputVec() {return m_baseAddr[20];}; // read+write register: thresColPtr index: 21 void thresColPtr(unsigned int v) {m_baseAddr[21] = v;}; unsigned int thresColPtr() {return m_baseAddr[21];}; // read+write register: thresRowInd index: 22 void thresRowInd(unsigned int v) {m_baseAddr[22] = v;}; unsigned int thresRowInd() {return m_baseAddr[22];}; // read+write register: thresNZData index: 23 void thresNZData(unsigned int v) {m_baseAddr[23] = v;}; unsigned int thresNZData() {return m_baseAddr[23];}; // read+write register: thresInputVec index: 24 void thresInputVec(unsigned int v) {m_baseAddr[24] = v;}; unsigned int thresInputVec() {return m_baseAddr[24];}; // read+write register: statBackend index: 1 void statBackend(unsigned int v) {m_baseAddr[1] = v;}; unsigned int statBackend() {return m_baseAddr[1];}; // read+write register: statFrontend index: 2 void statFrontend(unsigned int v) {m_baseAddr[2] = v;}; unsigned int statFrontend() {return m_baseAddr[2];}; // read+write register: hazardStalls index: 3 void hazardStalls(unsigned int v) {m_baseAddr[3] = v;}; unsigned int hazardStalls() {return m_baseAddr[3];}; // read+write register: bwMon_totalCycles index: 4 void bwMon_totalCycles(unsigned int v) {m_baseAddr[4] = v;}; unsigned int bwMon_totalCycles() {return m_baseAddr[4];}; // read+write register: bwMon_activeCycles index: 5 void bwMon_activeCycles(unsigned int v) {m_baseAddr[5] = v;}; unsigned int bwMon_activeCycles() {return m_baseAddr[5];}; // read+write register: ocmWords index: 6 void ocmWords(unsigned int v) {m_baseAddr[6] = v;}; unsigned int ocmWords() {return m_baseAddr[6];}; // read+write register: fifoCountsCPRI index: 7 void fifoCountsCPRI(unsigned int v) {m_baseAddr[7] = v;}; unsigned int fifoCountsCPRI() {return m_baseAddr[7];}; // read+write register: fifoCountsNZIV index: 8 void fifoCountsNZIV(unsigned int v) {m_baseAddr[8] = v;}; unsigned int fifoCountsNZIV() {return m_baseAddr[8];}; // read+write register: debug index: 9 void debug(unsigned int v) {m_baseAddr[9] = v;}; unsigned int debug() {return m_baseAddr[9];}; // read+write register: signature index: 0 void signature(unsigned int v) {m_baseAddr[0] = v;}; unsigned int signature() {return m_baseAddr[0];}; protected: volatile unsigned int * m_baseAddr; }; #endif <|endoftext|>
<commit_before>#include "accent/selectionaccentpainter.h" #include <QPainter> #include <QPen> #include <QDebug> SelectionAccentPainter::SelectionAccentPainter(const QColor& rectColor, const QColor& shadeColor) : _cinemaScopePainter(shadeColor, 100) , _rectangleSelectedPainter(QPen(rectColor, 1, Qt::SolidLine)) , _rectangleHighlightedPainter(QPen(rectColor, 1, Qt::DashLine)) { } void SelectionAccentPainter::paint(QPainter *painter, const RegionContext* context) { Q_ASSERT(painter != NULL); Q_ASSERT(context != NULL); const QRect& selectedRegion = context->selectedRegion(); paint(painter, context->scopeRegion(), selectedRegion); const QRect& highlightedRegion = context->highlightedRegion(); if (selectedRegion.contains(highlightedRegion, false) || selectedRegion.intersects(highlightedRegion) ) { QRect intersectedRegion = (selectedRegion.intersects(highlightedRegion)) ? selectedRegion.intersected(highlightedRegion) : highlightedRegion; QRect innerRegion = intersectedRegion.adjusted(0,0,-1,-1); _rectangleHighlightedPainter.paint(painter, selectedRegion, innerRegion); } } void SelectionAccentPainter::paint(QPainter *painter, const QRect& scope, const QRect& region) { Q_ASSERT(painter != NULL); QRect outerRegion = region.adjusted(0,0,-1,-1); _cinemaScopePainter.paint(painter, scope, outerRegion); _rectangleSelectedPainter.paint(painter, scope, outerRegion); drawSizeBanner(painter, region, Qt::red); } void SelectionAccentPainter::drawSizeBanner(QPainter *painter, const QRect &rect, QColor baseColor) { int rw = rect.width(); int rh = rect.height(); if (rw > 1 || rh > 1) { QString text = QString("%1x%2").arg(rw).arg(rh); QRect bannerRect(rect.bottomRight() - QPoint(80, 0), rect.bottomRight() + QPoint(0, 20)); baseColor.setAlpha(50); QBrush bannerBrush(baseColor); painter->fillRect(bannerRect, bannerBrush); QPen textPen(Qt::black); painter->setPen(textPen); painter->drawText(bannerRect, text, Qt::AlignHCenter | Qt::AlignVCenter); } } <commit_msg>bug fixing (reset full shader after crop)<commit_after>#include "accent/selectionaccentpainter.h" #include <QPainter> #include <QPen> #include <QDebug> SelectionAccentPainter::SelectionAccentPainter(const QColor& rectColor, const QColor& shadeColor) : _cinemaScopePainter(shadeColor, 100) , _rectangleSelectedPainter(QPen(rectColor, 1, Qt::SolidLine)) , _rectangleHighlightedPainter(QPen(rectColor, 1, Qt::DashLine)) { } void SelectionAccentPainter::paint(QPainter *painter, const RegionContext* context) { Q_ASSERT(painter != NULL); Q_ASSERT(context != NULL); const QRect& selectedRegion = context->selectedRegion(); if (!context->fullWidgetMode()) { if (!RegionContext::isValidRegion(selectedRegion)){ return; } } paint(painter, context->scopeRegion(), selectedRegion); const QRect& highlightedRegion = context->highlightedRegion(); if (selectedRegion.contains(highlightedRegion, false) || selectedRegion.intersects(highlightedRegion) ) { QRect intersectedRegion = (selectedRegion.intersects(highlightedRegion)) ? selectedRegion.intersected(highlightedRegion) : highlightedRegion; QRect innerRegion = intersectedRegion.adjusted(0,0,-1,-1); _rectangleHighlightedPainter.paint(painter, selectedRegion, innerRegion); } } void SelectionAccentPainter::paint(QPainter *painter, const QRect& scope, const QRect& region) { Q_ASSERT(painter != NULL); QRect outerRegion = region.adjusted(0,0,-1,-1); _cinemaScopePainter.paint(painter, scope, outerRegion); _rectangleSelectedPainter.paint(painter, scope, outerRegion); drawSizeBanner(painter, region, Qt::red); } void SelectionAccentPainter::drawSizeBanner(QPainter *painter, const QRect &rect, QColor baseColor) { int rw = rect.width(); int rh = rect.height(); if (rw > 1 || rh > 1) { QString text = QString("%1x%2").arg(rw).arg(rh); QRect bannerRect(rect.bottomRight() - QPoint(80, 0), rect.bottomRight() + QPoint(0, 20)); baseColor.setAlpha(50); QBrush bannerBrush(baseColor); painter->fillRect(bannerRect, bannerBrush); QPen textPen(Qt::black); painter->setPen(textPen); painter->drawText(bannerRect, text, Qt::AlignHCenter | Qt::AlignVCenter); } } <|endoftext|>
<commit_before>// // Created by Vadim N. on 04/04/2015. // //#include <omp.h> //#include <stdio.h> // //int main() { //#pragma omp parallel // printf("Hello from thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads()); //} #include <ostream> #include "Model" using namespace ymir; /** * \brief Main function of a script for computing generation probabitilies. It has * a strict order of input arguments in console: * argv[0] - name of the script (default); * argv[1] - path to an input file; * argv[2] - path to a model; * argv[3] - path to an output file; * argv[4] - 0 if model should use stored gene usage; 1 if model should recompute gene usage from the input file. * argv[5] - 'n' for nucleotide sequences, 'a' for amino acid sequences. */ int main(int argc, char* argv[]) { std::string in_file_path(argv[1]), model_path(argv[2]), out_file_path(argv[3]); bool recompute_genes = std::stoi(argv[4]); std::cout << "Input file:\t" << in_file_path << std::endl; std::cout << "Model path:\t" << model_path << std::endl; std::cout << "Output file:\t" << out_file_path << std::endl; std::cout << std::endl; ProbabilisticAssemblingModel model(model_path); std::cout << std::endl; if (model.status()) { // // Nucleotide // // if (argv[5] == "n") { ParserNuc parser(new NaiveCDR3NucleotideAligner(model.gene_segments(), VDJAlignerParameters(3))); ClonesetNuc cloneset; auto alignment_column_options = AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED, AlignmentColumnOptions::OVERWRITE, AlignmentColumnOptions::REALIGN_PROVIDED); auto vdj_aligner_parameters_nuc = VDJAlignerParameters(3, VDJAlignmentEventScore(AlignmentEventScore(1, -1, 1), AlignmentEventScore(1, -1, 1), AlignmentEventScore(1, -1, 1)), VDJAlignmentScoreThreshold(3, 3, 3)); auto vdj_aligner_parameters_aa = VDJAlignerParameters(3, VDJAlignmentEventScore(AlignmentEventScore(1, -1, 1), AlignmentEventScore(1, -1, 1), AlignmentEventScore(1, -1, 1)), VDJAlignmentScoreThreshold(1, 1, 1)); if (parser.openAndParse(in_file_path, &cloneset, model.gene_segments(), model.recombination(), alignment_column_options, vdj_aligner_parameters_nuc)) { if (recompute_genes) { std::cout << std::endl; std::cout << "Recomputing gene usage on " << (size_t) cloneset.noncoding().size() << " clonotypes." << std::endl; model.updateGeneUsage(cloneset); } std::cout << std::endl; std::vector<prob_t> prob_vec; std::vector<size_t> noncoding_indices; std::vector<prob_t> coding_probs; if (argv[5][0] == 'n') { prob_vec = model.computeFullProbabilities(cloneset, NO_ERRORS); } else { ClonesetAA cloneset_aa; std::cout << "Converting nucleotide clonotypes to amino acid clonotypes..." << std::endl; noncoding_indices = CDR3AminoAcidAligner(model.gene_segments(), vdj_aligner_parameters_aa).toAminoAcid(cloneset, &cloneset_aa, true); std::cout << "Done." << std::endl << std::endl; coding_probs = model.computeFullProbabilities(cloneset_aa); // model.buildGraphs(cloneset_aa); } std::ofstream ofs; ofs.open(out_file_path); std::cout << std::endl; std::cout << "Generation probabilities statistics:" << std::endl; prob_summary(prob_vec); if (ofs.is_open()) { // Write nucleotide probabilities. if (prob_vec.size()) { for (auto i = 0; i < prob_vec.size(); ++i) { ofs << prob_vec[i] << std::endl; } } // Write amino acid probabilities. else { size_t k = 0, j = 0; for (auto i = 0; i < cloneset.size(); ++i) { if (k != noncoding_indices.size() && i == noncoding_indices[k]) { ofs << "-1" << std::endl; ++k; } else { ofs << coding_probs[j] << std::endl; ++j; } } } } else { std::cout << "Problems with the output stream. Terminating..." << std::endl; } ofs.close(); } else { std::cout << "Problems in parsing the input file. Terminating..." << std::endl; } // } // // Amino acid // // else { // ParserAA parser; // ClonesetAA cloneset; // // if (parser.openAndParse(in_file_path, // &cloneset, // model.gene_segments(), // model.recombination(), // AlignmentColumnOptions(AlignmentColumnOptions::USE_PROVIDED, // AlignmentColumnOptions::USE_PROVIDED, // AlignmentColumnOptions::OVERWRITE))) { //// if (recompute_genes) { //// std::cout << std::endl; //// std::cout << "Recomputing gene usage on " << (size_t) cloneset.noncoding().size() << " clonotypes." << std::endl; //// model.updateGeneUsage(cloneset); //// } // // std::cout << std::endl; // auto prob_vec = model.computeFullProbabilities(cloneset); // // std::ofstream ofs; // ofs.open(out_file_path); // // std::cout << std::endl; // std::cout << "Generation probabilities statistics:" << std::endl; // prob_summary(prob_vec); // // if (ofs.is_open()) { // for (auto i = 0; i < prob_vec.size(); ++i) { // ofs << prob_vec[i] << std::endl; // } // } else { // std::cout << "Problems with the output stream. Terminating..." << std::endl; // } // ofs.close(); // } else { // std::cout << "Problems in parsing the input file. Terminating..." << std::endl; // } // } } else { std::cout << "Problems with the model. Terminating..." << std::endl; } return 0; }<commit_msg>build graphs<commit_after>// // Created by Vadim N. on 04/04/2015. // //#include <omp.h> //#include <stdio.h> // //int main() { //#pragma omp parallel // printf("Hello from thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads()); //} #include <ostream> #include "Model" using namespace ymir; /** * \brief Main function of a script for computing generation probabitilies. It has * a strict order of input arguments in console: * argv[0] - name of the script (default); * argv[1] - path to an input file; * argv[2] - path to a model; * argv[3] - path to an output file; * argv[4] - 0 if model should use stored gene usage; 1 if model should recompute gene usage from the input file. * argv[5] - 'n' for nucleotide sequences, 'a' for amino acid sequences. */ int main(int argc, char* argv[]) { std::string in_file_path(argv[1]), model_path(argv[2]), out_file_path(argv[3]); bool recompute_genes = std::stoi(argv[4]); std::cout << "Input file:\t" << in_file_path << std::endl; std::cout << "Model path:\t" << model_path << std::endl; std::cout << "Output file:\t" << out_file_path << std::endl; std::cout << std::endl; ProbabilisticAssemblingModel model(model_path); std::cout << std::endl; if (model.status()) { // // Nucleotide // // if (argv[5] == "n") { ParserNuc parser(new NaiveCDR3NucleotideAligner(model.gene_segments(), VDJAlignerParameters(3))); ClonesetNuc cloneset; auto alignment_column_options = AlignmentColumnOptions(AlignmentColumnOptions::REALIGN_PROVIDED, AlignmentColumnOptions::OVERWRITE, AlignmentColumnOptions::REALIGN_PROVIDED); auto vdj_aligner_parameters_nuc = VDJAlignerParameters(3, VDJAlignmentEventScore(AlignmentEventScore(1, -1, 1), AlignmentEventScore(1, -1, 1), AlignmentEventScore(1, -1, 1)), VDJAlignmentScoreThreshold(3, 3, 3)); auto vdj_aligner_parameters_aa = VDJAlignerParameters(3, VDJAlignmentEventScore(AlignmentEventScore(1, -1, 1), AlignmentEventScore(1, -1, 1), AlignmentEventScore(1, -1, 1)), VDJAlignmentScoreThreshold(1, 1, 1)); if (parser.openAndParse(in_file_path, &cloneset, model.gene_segments(), model.recombination(), alignment_column_options, vdj_aligner_parameters_nuc)) { if (recompute_genes) { std::cout << std::endl; std::cout << "Recomputing gene usage on " << (size_t) cloneset.noncoding().size() << " clonotypes." << std::endl; model.updateGeneUsage(cloneset); } std::cout << std::endl; std::vector<prob_t> prob_vec; std::vector<size_t> noncoding_indices; std::vector<prob_t> coding_probs; if (argv[5][0] == 'n') { prob_vec = model.computeFullProbabilities(cloneset, NO_ERRORS); } else { ClonesetAA cloneset_aa; std::cout << "Converting nucleotide clonotypes to amino acid clonotypes..." << std::endl; noncoding_indices = CDR3AminoAcidAligner(model.gene_segments(), vdj_aligner_parameters_aa).toAminoAcid(cloneset, &cloneset_aa, true); std::cout << "Done." << std::endl << std::endl; // coding_probs = model.computeFullProbabilities(cloneset_aa); auto vec3 = model.buildGraphs(cloneset_aa); } std::ofstream ofs; ofs.open(out_file_path); std::cout << std::endl; std::cout << "Generation probabilities statistics:" << std::endl; prob_summary(prob_vec); if (ofs.is_open()) { // Write nucleotide probabilities. if (prob_vec.size()) { for (auto i = 0; i < prob_vec.size(); ++i) { ofs << prob_vec[i] << std::endl; } } // Write amino acid probabilities. else { size_t k = 0, j = 0; for (auto i = 0; i < cloneset.size(); ++i) { if (k != noncoding_indices.size() && i == noncoding_indices[k]) { ofs << "-1" << std::endl; ++k; } else { ofs << coding_probs[j] << std::endl; ++j; } } } } else { std::cout << "Problems with the output stream. Terminating..." << std::endl; } ofs.close(); } else { std::cout << "Problems in parsing the input file. Terminating..." << std::endl; } // } // // Amino acid // // else { // ParserAA parser; // ClonesetAA cloneset; // // if (parser.openAndParse(in_file_path, // &cloneset, // model.gene_segments(), // model.recombination(), // AlignmentColumnOptions(AlignmentColumnOptions::USE_PROVIDED, // AlignmentColumnOptions::USE_PROVIDED, // AlignmentColumnOptions::OVERWRITE))) { //// if (recompute_genes) { //// std::cout << std::endl; //// std::cout << "Recomputing gene usage on " << (size_t) cloneset.noncoding().size() << " clonotypes." << std::endl; //// model.updateGeneUsage(cloneset); //// } // // std::cout << std::endl; // auto prob_vec = model.computeFullProbabilities(cloneset); // // std::ofstream ofs; // ofs.open(out_file_path); // // std::cout << std::endl; // std::cout << "Generation probabilities statistics:" << std::endl; // prob_summary(prob_vec); // // if (ofs.is_open()) { // for (auto i = 0; i < prob_vec.size(); ++i) { // ofs << prob_vec[i] << std::endl; // } // } else { // std::cout << "Problems with the output stream. Terminating..." << std::endl; // } // ofs.close(); // } else { // std::cout << "Problems in parsing the input file. Terminating..." << std::endl; // } // } } else { std::cout << "Problems with the model. Terminating..." << std::endl; } return 0; }<|endoftext|>
<commit_before>#include "mswin.h" #include "kdtree.h" #include "partition.h" #include "memory.h" #include "aligned-arrays.h" #include "config.h" #include "model.h" #include "vector.h" #include "compiler.h" #include <cstdint> #include <limits> namespace { inline unsigned nodes_required (unsigned point_count) { // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 unsigned m = 2; unsigned t = point_count - 1; while (t >>= 1) m <<= 1; // Now m is 2^{ceil(log_2(count))}. return m - 1; } inline unsigned node_dimension (unsigned i) { // http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious unsigned m = 0; unsigned t = i + 1; while (t >>= 1) ++ m; // Now m is floor(log_2(i + 1)). return m % 3; } inline v4f dim_mask (unsigned dim) { static const union { std::uint32_t u32 [4]; float f32 [4]; } masks [3] ALIGNED16 = { { { 0xffffffff, 0, 0, 0, }, }, { { 0, 0xffffffff, 0, 0, }, }, { { 0, 0, 0xffffffff, 0, }, }, }; return load4f (masks [dim].f32); } inline void bounce (object_t * objects, const float (* r), const float (* x) [4], float (* v) [4], float (* w) [4], unsigned ix, unsigned iy) { const object_t & A = objects [ix]; const object_t & B = objects [iy]; v4f s = { r [ix] + r [iy], 0.0f, 0.0f, 0.0f, }; v4f ssq = s * s; v4f dx = load4f (x [iy]) - load4f (x [ix]); v4f dxsq = dot (dx, dx); if (_mm_comilt_ss (dxsq, ssq)) { // Spheres interpenetrate? v4f dv = load4f (v [iy]) - load4f (v [ix]); v4f dxdv = dot (dx, dv); v4f zero = _mm_setzero_ps (); if (_mm_comilt_ss (dxdv, zero)) { // Spheres approach? v4f dxlen = _mm_sqrt_ps (dxsq); v4f dxn = dx / dxlen; v4f rw = _mm_set1_ps (r [ix]) * load4f (w [ix]) + _mm_set1_ps (r [iy]) * load4f (w [iy]); v4f unn = dx * dxdv / dxsq; v4f rub = cross (rw, dxn) + unn - dv; v4f kf = _mm_set1_ps (usr::balls_friction); v4f u = kf * rub - unn; // Now take the nonzero multiplier lambda such that the // impulse lambda*u is consistent with conservation of // energy and momentum. // (Lambda is implicit now. See "problem.tex".) v4f dxu = cross (dxn, u); v4f km2 = { -2.0f, -2.0f, -2.0f, -2.0f, }; v4f top = km2 * (dot (u, dv) - dot (dxu, rw)); v4f uu = dot (u, u); v4f R = { 1.0f, 1.0f, r [ix], r [iy], }; v4f rdxu = (R * R) * dot (dxu, dxu); v4f urdxu = _mm_movehl_ps (rdxu, uu); v4f divisors = { A.m, B.m, A.l, B.l, }; v4f quotients = urdxu / divisors; v4f ha = _mm_hadd_ps (quotients, quotients); v4f hh = _mm_hadd_ps (ha, ha); v4f munu = (top * R) / (hh * divisors); v4f muA, muB, nuA, nuB; UNPACK4 (munu, muA, muB, nuA, nuB); store4f (v [ix], load4f (v [ix]) - muA * u); store4f (v [iy], load4f (v [iy]) + muB * u); store4f (w [ix], load4f (w [ix]) - nuA * dxu); store4f (w [iy], load4f (w [iy]) - nuB * dxu); // sic } } } inline void bounce (object_t * objects, const float (* r), const float (* x) [4], float (* v) [4], float (* w) [4], float (* walls) [2] [4], unsigned iw, unsigned ix) { object_t & A = objects [ix]; v4f anchor = load4f (walls [iw] [0]); v4f normal = load4f (walls [iw] [1]); v4f s = dot (load4f (x [ix]) - anchor, normal); v4f R = _mm_set1_ps (r [ix]); if (_mm_comilt_ss (s, R)) { // Sphere penetrates plane? v4f vn = dot (load4f (v [ix]), normal); v4f zero = _mm_setzero_ps (); if (_mm_comilt_ss (vn, zero)) { // Sphere approaches plane? // vN is the normal component of v. (The normal is a unit vector). // vF is the tangential contact velocity, composed of glide and spin. v4f vN = vn * normal; v4f rn = R * normal; v4f vF = load4f (v [ix]) - vN - cross (load4f (w [ix]), rn); v4f kf = _mm_set1_ps (usr::walls_friction); v4f uneg = vN + kf * vF; v4f vN_sq = vn * vn; v4f vF_sq = dot (vF, vF); v4f kvF_sq = kf * (kf * vF_sq); v4f ml = { A.m, A.l, A.m, A.l, }; v4f wtf = _mm_unpacklo_ps (vN_sq + kvF_sq, (R * R) * kvF_sq) / ml; v4f munu = (vN_sq + kf * vF_sq) / (ml * _mm_hadd_ps (wtf, wtf)); munu += munu; munu = _mm_unpacklo_ps (munu, munu); v4f mu = _mm_movelh_ps (munu, munu); v4f nu = _mm_movehl_ps (munu, munu); store4f (v [ix], load4f (v [ix]) - mu * uneg); store4f (w [ix], load4f (w [ix]) + nu * cross (rn, uneg)); } } } } kdtree_t::~kdtree_t () { deallocate (memory); } #define SETNODE(_i, _lo, _hi, _begin, _end) \ do { \ store4f (node_lohi [_i] [0], _lo); \ store4f (node_lohi [_i] [1], _hi); \ node_begin [_i] = _begin; \ node_end [_i] = _end; \ } while (false) void kdtree_t::compute (unsigned * new_index, const float (* new_x) [4], unsigned count) { index = new_index; x = new_x; unsigned new_node_count = nodes_required (count); reallocate_aligned_arrays (memory, node_count, new_node_count, & node_lohi, & node_begin, & node_end); static const float inf = std::numeric_limits <float>::infinity (); __m128 klo = { -inf, -inf, -inf, 0.0f, }; __m128 khi = { +inf, +inf, +inf, 0.0f, }; SETNODE (0, klo, khi, 0, count); unsigned stack [50]; // Big enough. unsigned sp = 0; stack [sp ++] = 0; while (sp) { unsigned i = stack [-- sp]; unsigned begin = node_begin [i]; unsigned end = node_end [i]; if (end - begin > 2) { unsigned middle = (begin + end) / 2; unsigned dim = node_dimension (i); partition (index, x, begin, middle, end, dim); v4f lo = load4f (node_lohi [i] [0]); v4f hi = load4f (node_lohi [i] [1]); v4f mid = load4f (x [index [middle]]); v4f dm = dim_mask (dim); v4f md = _mm_and_ps (dm, mid); v4f mid_lo = _mm_or_ps (md, _mm_andnot_ps (dm, lo)); v4f mid_hi = _mm_or_ps (md, _mm_andnot_ps (dm, hi)); SETNODE (2 * i + 1, lo, mid_hi, begin, middle); SETNODE (2 * i + 2, mid_lo, hi, middle, end); stack [sp ++] = 2 * i + 2; stack [sp ++] = 2 * i + 1; } } } void kdtree_t::bounce (unsigned count, float R, object_t * objects, const float (* r), float (* v) [4], float (* w) [4], float (* walls) [2] [4]) { // For each ball, find nearby balls and test for collisions. v4f rsq = _mm_set1_ps (R * R); for (unsigned k = 0; k != count; ++ k) { v4f xx = load4f (x [k]); v4f zero = _mm_setzero_ps (); unsigned stack [50]; // Big enough. unsigned sp = 0; stack [sp ++] = 0; while (sp) { unsigned i = stack [-- sp]; unsigned begin = node_begin [i]; unsigned end = node_end [i]; if (end - begin > 2) { // Does node i's box intersect the specified ball? v4f lo = load4f (node_lohi [i] [0]) - xx; v4f hi = xx - load4f (node_lohi [i] [1]); v4f mx = _mm_max_ps (lo, hi); v4f nneg = _mm_and_ps (_mm_cmpge_ps (mx, zero), mx); v4f dsq = dot (nneg, nneg); if (_mm_comilt_ss (dsq, rsq)) { stack [sp ++] = 2 * i + 2; stack [sp ++] = 2 * i + 1; } } else { for (unsigned n = node_begin [i]; n != node_end [i]; ++ n) { unsigned j = index [n]; if (j > k) { ::bounce (objects, r, x, v, w, j, k); } } } } } // For each wall, find nearby balls and test for collisions. v4f r0 = _mm_set1_ps (R); v4f zero = _mm_setzero_ps (); for (unsigned k = 0; k != 6; ++ k) { v4f a = load4f (walls [k] [0]); v4f n = load4f (walls [k] [1]); v4f mask = _mm_cmpge_ps (n, zero); unsigned stack [50]; // Big enough. unsigned sp = 0; stack [sp ++] = 0; while (sp) { unsigned i = stack [-- sp]; unsigned begin = node_begin [i]; unsigned end = node_end [i]; if (end - begin > 2) { // Does node i's box intersect the specified half-plane? // Only need to test one corner. v4f lo = load4f (node_lohi [i] [0]); v4f hi = load4f (node_lohi [i] [1]); v4f x = _mm_or_ps (_mm_and_ps (mask, lo), _mm_andnot_ps (mask, hi)); v4f d = dot (x - a, n); if (_mm_comilt_ss (d, r0)) { stack [sp ++] = 2 * i + 2; stack [sp ++] = 2 * i + 1; } } else { for (unsigned n = begin; n != end; ++ n) { unsigned j = index [n]; ::bounce (objects, r, x, v, w, walls, k, j); } } } } } <commit_msg>Correct comment.<commit_after>#include "mswin.h" #include "kdtree.h" #include "partition.h" #include "memory.h" #include "aligned-arrays.h" #include "config.h" #include "model.h" #include "vector.h" #include "compiler.h" #include <cstdint> #include <limits> namespace { inline unsigned nodes_required (unsigned point_count) { // http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 unsigned m = 2; unsigned t = point_count - 1; while (t >>= 1) m <<= 1; // Now m is 2^{ceil(log_2(count))}. return m - 1; } inline unsigned node_dimension (unsigned i) { // http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious unsigned m = 0; unsigned t = i + 1; while (t >>= 1) ++ m; // Now m is floor(log_2(i + 1)). return m % 3; } inline v4f dim_mask (unsigned dim) { static const union { std::uint32_t u32 [4]; float f32 [4]; } masks [3] ALIGNED16 = { { { 0xffffffff, 0, 0, 0, }, }, { { 0, 0xffffffff, 0, 0, }, }, { { 0, 0, 0xffffffff, 0, }, }, }; return load4f (masks [dim].f32); } inline void bounce (object_t * objects, const float (* r), const float (* x) [4], float (* v) [4], float (* w) [4], unsigned ix, unsigned iy) { const object_t & A = objects [ix]; const object_t & B = objects [iy]; v4f s = { r [ix] + r [iy], 0.0f, 0.0f, 0.0f, }; v4f ssq = s * s; v4f dx = load4f (x [iy]) - load4f (x [ix]); v4f dxsq = dot (dx, dx); if (_mm_comilt_ss (dxsq, ssq)) { // Spheres interpenetrate? v4f dv = load4f (v [iy]) - load4f (v [ix]); v4f dxdv = dot (dx, dv); v4f zero = _mm_setzero_ps (); if (_mm_comilt_ss (dxdv, zero)) { // Spheres approach? v4f dxlen = _mm_sqrt_ps (dxsq); v4f dxn = dx / dxlen; v4f rw = _mm_set1_ps (r [ix]) * load4f (w [ix]) + _mm_set1_ps (r [iy]) * load4f (w [iy]); v4f unn = dx * dxdv / dxsq; v4f rub = cross (rw, dxn) + unn - dv; v4f kf = _mm_set1_ps (usr::balls_friction); v4f u = kf * rub - unn; // Now take the nonzero multiplier lambda such that the // impulse lambda*u is consistent with conservation of // energy and momentum. // (Lambda is implicit now. See "elastic.tex".) v4f dxu = cross (dxn, u); v4f km2 = { -2.0f, -2.0f, -2.0f, -2.0f, }; v4f top = km2 * (dot (u, dv) - dot (dxu, rw)); v4f uu = dot (u, u); v4f R = { 1.0f, 1.0f, r [ix], r [iy], }; v4f rdxu = (R * R) * dot (dxu, dxu); v4f urdxu = _mm_movehl_ps (rdxu, uu); v4f divisors = { A.m, B.m, A.l, B.l, }; v4f quotients = urdxu / divisors; v4f ha = _mm_hadd_ps (quotients, quotients); v4f hh = _mm_hadd_ps (ha, ha); v4f munu = (top * R) / (hh * divisors); v4f muA, muB, nuA, nuB; UNPACK4 (munu, muA, muB, nuA, nuB); store4f (v [ix], load4f (v [ix]) - muA * u); store4f (v [iy], load4f (v [iy]) + muB * u); store4f (w [ix], load4f (w [ix]) - nuA * dxu); store4f (w [iy], load4f (w [iy]) - nuB * dxu); // sic } } } inline void bounce (object_t * objects, const float (* r), const float (* x) [4], float (* v) [4], float (* w) [4], float (* walls) [2] [4], unsigned iw, unsigned ix) { object_t & A = objects [ix]; v4f anchor = load4f (walls [iw] [0]); v4f normal = load4f (walls [iw] [1]); v4f s = dot (load4f (x [ix]) - anchor, normal); v4f R = _mm_set1_ps (r [ix]); if (_mm_comilt_ss (s, R)) { // Sphere penetrates plane? v4f vn = dot (load4f (v [ix]), normal); v4f zero = _mm_setzero_ps (); if (_mm_comilt_ss (vn, zero)) { // Sphere approaches plane? // vN is the normal component of v. (The normal is a unit vector). // vF is the tangential contact velocity, composed of glide and spin. v4f vN = vn * normal; v4f rn = R * normal; v4f vF = load4f (v [ix]) - vN - cross (load4f (w [ix]), rn); v4f kf = _mm_set1_ps (usr::walls_friction); v4f uneg = vN + kf * vF; v4f vN_sq = vn * vn; v4f vF_sq = dot (vF, vF); v4f kvF_sq = kf * (kf * vF_sq); v4f ml = { A.m, A.l, A.m, A.l, }; v4f wtf = _mm_unpacklo_ps (vN_sq + kvF_sq, (R * R) * kvF_sq) / ml; v4f munu = (vN_sq + kf * vF_sq) / (ml * _mm_hadd_ps (wtf, wtf)); munu += munu; munu = _mm_unpacklo_ps (munu, munu); v4f mu = _mm_movelh_ps (munu, munu); v4f nu = _mm_movehl_ps (munu, munu); store4f (v [ix], load4f (v [ix]) - mu * uneg); store4f (w [ix], load4f (w [ix]) + nu * cross (rn, uneg)); } } } } kdtree_t::~kdtree_t () { deallocate (memory); } #define SETNODE(_i, _lo, _hi, _begin, _end) \ do { \ store4f (node_lohi [_i] [0], _lo); \ store4f (node_lohi [_i] [1], _hi); \ node_begin [_i] = _begin; \ node_end [_i] = _end; \ } while (false) void kdtree_t::compute (unsigned * new_index, const float (* new_x) [4], unsigned count) { index = new_index; x = new_x; unsigned new_node_count = nodes_required (count); reallocate_aligned_arrays (memory, node_count, new_node_count, & node_lohi, & node_begin, & node_end); static const float inf = std::numeric_limits <float>::infinity (); __m128 klo = { -inf, -inf, -inf, 0.0f, }; __m128 khi = { +inf, +inf, +inf, 0.0f, }; SETNODE (0, klo, khi, 0, count); unsigned stack [50]; // Big enough. unsigned sp = 0; stack [sp ++] = 0; while (sp) { unsigned i = stack [-- sp]; unsigned begin = node_begin [i]; unsigned end = node_end [i]; if (end - begin > 2) { unsigned middle = (begin + end) / 2; unsigned dim = node_dimension (i); partition (index, x, begin, middle, end, dim); v4f lo = load4f (node_lohi [i] [0]); v4f hi = load4f (node_lohi [i] [1]); v4f mid = load4f (x [index [middle]]); v4f dm = dim_mask (dim); v4f md = _mm_and_ps (dm, mid); v4f mid_lo = _mm_or_ps (md, _mm_andnot_ps (dm, lo)); v4f mid_hi = _mm_or_ps (md, _mm_andnot_ps (dm, hi)); SETNODE (2 * i + 1, lo, mid_hi, begin, middle); SETNODE (2 * i + 2, mid_lo, hi, middle, end); stack [sp ++] = 2 * i + 2; stack [sp ++] = 2 * i + 1; } } } void kdtree_t::bounce (unsigned count, float R, object_t * objects, const float (* r), float (* v) [4], float (* w) [4], float (* walls) [2] [4]) { // For each ball, find nearby balls and test for collisions. v4f rsq = _mm_set1_ps (R * R); for (unsigned k = 0; k != count; ++ k) { v4f xx = load4f (x [k]); v4f zero = _mm_setzero_ps (); unsigned stack [50]; // Big enough. unsigned sp = 0; stack [sp ++] = 0; while (sp) { unsigned i = stack [-- sp]; unsigned begin = node_begin [i]; unsigned end = node_end [i]; if (end - begin > 2) { // Does node i's box intersect the specified ball? v4f lo = load4f (node_lohi [i] [0]) - xx; v4f hi = xx - load4f (node_lohi [i] [1]); v4f mx = _mm_max_ps (lo, hi); v4f nneg = _mm_and_ps (_mm_cmpge_ps (mx, zero), mx); v4f dsq = dot (nneg, nneg); if (_mm_comilt_ss (dsq, rsq)) { stack [sp ++] = 2 * i + 2; stack [sp ++] = 2 * i + 1; } } else { for (unsigned n = node_begin [i]; n != node_end [i]; ++ n) { unsigned j = index [n]; if (j > k) { ::bounce (objects, r, x, v, w, j, k); } } } } } // For each wall, find nearby balls and test for collisions. v4f r0 = _mm_set1_ps (R); v4f zero = _mm_setzero_ps (); for (unsigned k = 0; k != 6; ++ k) { v4f a = load4f (walls [k] [0]); v4f n = load4f (walls [k] [1]); v4f mask = _mm_cmpge_ps (n, zero); unsigned stack [50]; // Big enough. unsigned sp = 0; stack [sp ++] = 0; while (sp) { unsigned i = stack [-- sp]; unsigned begin = node_begin [i]; unsigned end = node_end [i]; if (end - begin > 2) { // Does node i's box intersect the specified half-plane? // Only need to test one corner. v4f lo = load4f (node_lohi [i] [0]); v4f hi = load4f (node_lohi [i] [1]); v4f x = _mm_or_ps (_mm_and_ps (mask, lo), _mm_andnot_ps (mask, hi)); v4f d = dot (x - a, n); if (_mm_comilt_ss (d, r0)) { stack [sp ++] = 2 * i + 2; stack [sp ++] = 2 * i + 1; } } else { for (unsigned n = begin; n != end; ++ n) { unsigned j = index [n]; ::bounce (objects, r, x, v, w, walls, k, j); } } } } } <|endoftext|>
<commit_before>#include "aquila/global.h" #include "aquila/source/SignalSource.h" #include "aquila/transform/FftFactory.h" #include "aquila/source/WaveFile.h" #include <algorithm> #include <functional> #include <memory> #include <iostream> #include <cstdlib> #include "FFTreader.hpp" using namespace std; #define abs_amp 100000 #define startchirp 201 #define DEBUG_FLAG (1) vector<string> FFTreader::parse(){ std::size_t start = 0; while(start < END){ vector<int> peak= freqOfindex(start); if (peak.size() ==1 && peak.back() == startchirp){ break; } start += SIZE; } int left = start - SIZE,right = start; // while(left < right){ // int mid = (left+right)/2; // vector<int> peak= freqOfindex(mid); // if (peak.size() ==1 && peak.back() == startchirp) right = mid; // else left = mid+ SIZE/8; // } std::vector<std::vector<int>> data; int pre_freq = 0, pkts = 0, step = sampleFreq/10; vector<int> peak= freqOfindex(right); #if DEBUG_FLAG cout << "@ time " << (double)right/(sampleFreq) << "s"<< endl; cout << "Tracked freq (100 Hz): "; for(auto&x : peak) cout<< x <<" "; cout<<endl; #endif if(peak.size()==1 && pre_freq==0 && peak.back() == startchirp){ //first startchirp chirp pre_freq = startchirp; right += step; } peak= freqOfindex(right); if (peak.size()==1 && pre_freq==startchirp && peak.back() ==startchirp){ //second startchirp chirp right += step; } peak = freqOfindex(right); //read pkt lengt int cur = 0; for(auto&x : peak){ int shift = x - (startchirp-16); if(x>=(startchirp-16) && x<=(startchirp-1)) cur |= 1 << shift; } #if DEBUG_FLAG cout << "@ time " << (double)right/(sampleFreq) << "s"<< endl; cout << "Tracked freq (100 Hz): "; for(auto&x : peak) cout<< x <<" "; cout<<endl; #endif pkts = cur; right += step; cout <<"Ready to read pkts:"<< pkts<< endl; while(pkts-- >0){ peak = freqOfindex(right); #if DEBUG_FLAG cout << "@ time " << (double)right/(sampleFreq) << "s"<< endl; cout << "Tracked freq (100 Hz): "; for(auto&x : peak) cout<< x <<" "; cout<<endl; #endif int datalen = 0; for(auto&x : peak){ int shift = x - (startchirp-16); if(x>=(startchirp-16) && x<=(startchirp-1)) datalen |= 1 << shift; } right += step; vector<int> pktdata; cout <<"Ready to read data len :"<< datalen<< endl; while(datalen > 0){ peak = freqOfindex(right); #if DEBUG_FLAG cout << "@ time " << (double)right/(sampleFreq) << "s"<< endl; cout << "Tracked freq (100 Hz): "; for(auto&x : peak) cout<< x <<" "; cout<<endl; #endif int content = 0; for(auto&x : peak){ int shift = x - (startchirp-16); if(shift >=0) content |= 1 << shift; } //if odd, right shift padding if(datalen==1) content >>= 8; pktdata.push_back(content); right += step; //every data has two bytes datalen -= 2; if(right >= END) break; } data.push_back(pktdata); if(right >= END) break; } const unsigned short _8bitMask = 0x00FF; std::vector<string> ret; int pos = 0; for(auto& x: data){ pos++; string ret_str = ""; std::vector<int> ip; for(auto tmp :x) { while(tmp > 0){ int d = tmp & _8bitMask; if(pos==1){ ip.push_back(d); }else{ ret_str+=(char) d; } tmp >>= 8; } } if(ip.size()>0){ for(int xx=0; xx< ip.size(); xx++){ if(xx == ip.size()-1) ret_str += std::to_string(ip[xx]); else ret_str+= std::to_string(ip[xx])+'.'; } } ret.push_back(ret_str); cout<<endl; } //ready to return vector<string> // for(auto& x: ret) cout<< x<< endl; return ret; } vector<int> FFTreader::findMax(Aquila::SpectrumType spectrum){ std::size_t halfLength = spectrum.size() / 2; std::vector<double> absSpectrum(halfLength); double max = 0; int peak_freq = 0; std::vector<int> ret; //search the band of the freq >= 15000 int start = 0; int highpass = startchirp-20; for (std::size_t i = start; i < halfLength; ++i) { absSpectrum[i] = std::abs(spectrum[i]); int round_freq = (int)((i-1)*(sampleFreq/halfLength)/2 + 50) /100; //if(round_freq > highpass) cout << round_freq<< " amp " << absSpectrum[i-1] << endl; if(round_freq > highpass && absSpectrum[i-2] < absSpectrum[i-1] && absSpectrum[i-1] > absSpectrum[i] && absSpectrum[i-1] > abs_amp ){ ret.push_back(round_freq); // cout << round_freq<< " amp " <<absSpectrum[i-1] << endl; } if(absSpectrum[i] > max){ max = absSpectrum[i]; peak_freq = round_freq; } } //cout << "peak freq for input with sample size: "<< halfLength*2 << " which needs to be pow of 2" <<endl; //cout <<peak_freq << " Hz max amp:" << max << endl; //plot(absSpectrum); // if(peak_freq < 190) ret.clear(); return ret; } vector<int> FFTreader::freqOfindex(std::size_t start){ vector<Aquila::SampleType> chunk; for (std::size_t i =start; i< start+SIZE; ++i) { chunk.push_back(wav.sample(i)); } Aquila::SignalSource data(chunk, sampleFreq); auto fft = Aquila::FftFactory::getFft(SIZE); // cout << "\n\nSignal spectrum of time index: "<<start<< endl; Aquila::SpectrumType spectrum = fft->fft(data.toArray()); //plt.plotSpectrum(spectrum); return findMax(spectrum); }<commit_msg>correct len and starting<commit_after>#include "aquila/global.h" #include "aquila/source/SignalSource.h" #include "aquila/transform/FftFactory.h" #include "aquila/source/WaveFile.h" #include <algorithm> #include <functional> #include <memory> #include <iostream> #include <cstdlib> #include "FFTreader.hpp" using namespace std; #define abs_amp 80000 #define startchirp 201 #define DEBUG_FLAG (1) vector<string> FFTreader::parse(){ std::size_t start = 0; while(start < END){ vector<int> peak= freqOfindex(start); if (peak.size() ==1 && peak.back() == startchirp){ break; } start += SIZE; } int left = start - SIZE/2, right = start + SIZE/7; while(left < right){ int mid = (left+right)/2; // cout << wav.sample(mid) << endl; vector<int> peak= freqOfindex(mid); if (peak.size() ==1 && peak.back() == startchirp) right = mid; else left = mid+1; } right += SIZE/2; std::vector<std::vector<int>> data; int pre_freq = 0, pkts = 0, step = sampleFreq/10; vector<int> peak= freqOfindex(right); #if DEBUG_FLAG cout << "@ time " << (double)right/(sampleFreq) << "s"<< endl; cout << "Tracked freq (100 Hz): "; for(auto&x : peak) cout<< x <<" "; cout<<endl; #endif if(peak.size()==1 && pre_freq==0 && peak.back() == startchirp){ //first startchirp chirp pre_freq = startchirp; right += step; } peak= freqOfindex(right); if (peak.size()==1 && pre_freq==startchirp && peak.back() ==startchirp){ //second startchirp chirp right += step; } peak = freqOfindex(right); //read pkt lengt int cur = 0; for(auto&x : peak){ int shift = x - (startchirp-16); if(x>=(startchirp-16) && x<=(startchirp-1)) cur |= 1 << shift; } #if DEBUG_FLAG cout << "@ time " << (double)right/(sampleFreq) << "s"<< endl; cout << "Tracked freq (100 Hz): "; for(auto&x : peak) cout<< x <<" "; cout<<endl; #endif pkts = cur; right += step; cout <<"Ready to read pkts:"<< pkts<< endl; while(pkts-- >0){ peak = freqOfindex(right); #if DEBUG_FLAG cout << "@ time " << (double)right/(sampleFreq) << "s"<< endl; cout << "Tracked freq (100 Hz): "; for(auto&x : peak) cout<< x <<" "; cout<<endl; #endif int datalen = 0; for(auto&x : peak){ int shift = x - (startchirp-16); if(x>=(startchirp-16) && x<=(startchirp-1)) datalen |= 1 << shift; } right += step; vector<int> pktdata; cout <<"Ready to read data len :"<< datalen<< endl; while(datalen > 0){ peak = freqOfindex(right); #if DEBUG_FLAG cout << "@ time " << (double)right/(sampleFreq) << "s"<< endl; cout << "Tracked freq (100 Hz): "; for(auto&x : peak) cout<< x <<" "; cout<<endl; #endif int content = 0; for(auto&x : peak){ int shift = x - (startchirp-16); if(shift >=0) content |= 1 << shift; } //if odd, right shift padding if(datalen==1) content >>= 8; pktdata.push_back(content); right += step; //every data has two bytes datalen -= 2; if(right >= END) break; } data.push_back(pktdata); if(right >= END) break; } const unsigned short _8bitMask = 0x00FF; std::vector<string> ret; int pos = 0; for(auto& x: data){ pos++; string ret_str = ""; std::vector<int> ip; for(auto tmp :x) { while(tmp > 0){ int d = tmp & _8bitMask; if(pos==1){ ip.push_back(d); }else{ ret_str+=(char) d; } tmp >>= 8; } } if(ip.size()>0){ for(int xx=0; xx< ip.size(); xx++){ if(xx == ip.size()-1) ret_str += std::to_string(ip[xx]); else ret_str+= std::to_string(ip[xx])+'.'; } } ret.push_back(ret_str); cout<<endl; } //ready to return vector<string> // for(auto& x: ret) cout<< x<< endl; return ret; } vector<int> FFTreader::findMax(Aquila::SpectrumType spectrum){ std::size_t halfLength = spectrum.size() / 2; std::vector<double> absSpectrum(halfLength); double max = 0; int peak_freq = 0; std::vector<int> ret; //search the band of the freq >= 15000 int start = 0; int highpass = startchirp-20; for (std::size_t i = start; i < halfLength; ++i) { absSpectrum[i] = std::abs(spectrum[i]); int round_freq = (int)((i-1)*(sampleFreq/halfLength)/2 + 50) /100; //if(round_freq > highpass) cout << round_freq<< " amp " << absSpectrum[i-1] << endl; if(round_freq > highpass && absSpectrum[i-2] < absSpectrum[i-1] && absSpectrum[i-1] > absSpectrum[i] && absSpectrum[i-1] > abs_amp ){ // cout << "original freq " << (i-1)*(sampleFreq/halfLength)/2 << endl; ret.push_back(round_freq); // cout << "round freq: "<<round_freq<<endl; // cout << " amp " <<absSpectrum[i-1] << endl; } if(absSpectrum[i] > max){ max = absSpectrum[i]; peak_freq = round_freq; } } //cout << "peak freq for input with sample size: "<< halfLength*2 << " which needs to be pow of 2" <<endl; //cout <<peak_freq << " Hz max amp:" << max << endl; //plot(absSpectrum); // if(peak_freq < 190) ret.clear(); return ret; } vector<int> FFTreader::freqOfindex(std::size_t start){ vector<Aquila::SampleType> chunk; for (std::size_t i =start; i< start+SIZE; ++i) { chunk.push_back(wav.sample(i)); } Aquila::SignalSource data(chunk, sampleFreq); auto fft = Aquila::FftFactory::getFft(SIZE); // cout << "\n\nSignal spectrum of time index: "<<start<< endl; Aquila::SpectrumType spectrum = fft->fft(data.toArray()); //plt.plotSpectrum(spectrum); return findMax(spectrum); }<|endoftext|>
<commit_before>#include "client/libceph.h" #include <string.h> #include <fcntl.h> #include <iostream> #include "common/ceph_argparse.h" #include "common/Mutex.h" #include "messages/MMonMap.h" #include "common/common_init.h" #include "msg/SimpleMessenger.h" #include "client/Client.h" #include "ceph_ver.h" /* ************* ************* ************* ************* * C interface */ extern "C" const char *ceph_version(int *pmajor, int *pminor, int *ppatch) { int major, minor, patch; int n = sscanf(CEPH_GIT_NICE_VER, "%d.%d.%d", &major, &minor, &patch); if (pmajor) *pmajor = (n >= 1) ? major : 0; if (pminor) *pminor = (n >= 2) ? minor : 0; if (ppatch) *ppatch = (n >= 3) ? patch : 0; return VERSION; } static Mutex ceph_client_mutex("ceph_client"); static int client_initialized = 0; static int client_mount = 0; static Client *client = NULL; static MonClient *monclient = NULL; static SimpleMessenger *messenger = NULL; static int instance = 0; extern "C" int ceph_initialize(int argc, const char **argv) { ceph_client_mutex.Lock(); if (!client_initialized) { //create everything to start a client vector<const char*> args; argv_to_vec(argc, argv, args); // The libceph API needs to be fixed so that we don't have to call // common_init here. Libraries should never call common_init. common_init(args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_LIBRARY, 0); keyring_init(&g_conf); //monmap monclient = new MonClient(); if (monclient->build_initial_monmap() < 0) { delete monclient; return -1; //error! } //network connection messenger = new SimpleMessenger(); messenger->register_entity(entity_name_t::CLIENT()); //at last the client client = new Client(messenger, monclient); uint64_t nonce = (uint64_t)++instance * 1000000ull + (uint64_t)getpid(); messenger->start(false, nonce); // do not daemonize client->init(); } ++client_initialized; ceph_client_mutex.Unlock(); return 0; } extern "C" void ceph_deinitialize() { ceph_client_mutex.Lock(); --client_initialized; if(!client_initialized) { if(client_mount) { client_mount = 0; client->unmount(); } client->shutdown(); delete client; messenger->wait(); messenger->destroy(); delete monclient; } ceph_client_mutex.Unlock(); } extern "C" int ceph_mount() { int ret; Mutex::Locker lock(ceph_client_mutex); if(!client_mount) { ret = client->mount(); if (ret!=0) return ret; } ++client_mount; return 0; } extern "C" int ceph_umount() { Mutex::Locker lock(ceph_client_mutex); --client_mount; if (!client_mount) return client->unmount(); return 0; } extern "C" int ceph_statfs(const char *path, struct statvfs *stbuf) { return client->statfs(path, stbuf); } extern "C" int ceph_get_local_osd() { return client->get_local_osd(); } extern "C" int ceph_getcwd(char *buf, int buflen) { string cwd; client->getcwd(cwd); int size = cwd.size()+1; //need space for null character if (size > buflen) { if (buflen == 0) return size; else return -ERANGE; } size = cwd.copy(buf, size); buf[size] = '\0'; //fill in null character return 0; } extern "C" int ceph_chdir (const char *s) { return client->chdir(s); } /*if we want to extern C this, we need to convert it to const char*, which will mean storing it somewhere or else making the caller responsible for delete-ing a c-string they didn't create*/ void ceph_getcwd(string& cwd) { client->getcwd(cwd); } extern "C" int ceph_opendir(const char *name, DIR **dirpp) { return client->opendir(name, dirpp); } extern "C" int ceph_closedir(DIR *dirp) { return client->closedir(dirp); } extern "C" int ceph_readdir_r(DIR *dirp, struct dirent *de) { return client->readdir_r(dirp, de); } extern "C" int ceph_readdirplus_r(DIR *dirp, struct dirent *de, struct stat *st, int *stmask) { return client->readdirplus_r(dirp, de, st, stmask); } extern "C" int ceph_getdents(DIR *dirp, char *buf, int buflen) { return client->getdents(dirp, buf, buflen); } extern "C" int ceph_getdnames(DIR *dirp, char *buf, int buflen) { return client->getdnames(dirp, buf, buflen); } extern "C" void ceph_rewinddir(DIR *dirp) { client->rewinddir(dirp); } extern "C" loff_t ceph_telldir(DIR *dirp) { return client->telldir(dirp); } extern "C" void ceph_seekdir(DIR *dirp, loff_t offset) { client->seekdir(dirp, offset); } extern "C" int ceph_link (const char *existing, const char *newname) { return client->link(existing, newname); } extern "C" int ceph_unlink (const char *path) { return client->unlink(path); } extern "C" int ceph_rename(const char *from, const char *to) { return client->rename(from, to); } // dirs extern "C" int ceph_mkdir(const char *path, mode_t mode) { return client->mkdir(path, mode); } extern "C" int ceph_mkdirs(const char *path, mode_t mode) { return client->mkdirs(path, mode); } extern "C" int ceph_rmdir(const char *path) { return client->rmdir(path); } // symlinks extern "C" int ceph_readlink(const char *path, char *buf, loff_t size) { return client->readlink(path, buf, size); } extern "C" int ceph_symlink(const char *existing, const char *newname) { return client->symlink(existing, newname); } // inode stuff extern "C" int ceph_lstat(const char *path, struct stat *stbuf) { return client->lstat(path, stbuf); } extern "C" int ceph_lstat_precise(const char *path, stat_precise *stbuf) { return client->lstat_precise(path, (Client::stat_precise*)stbuf); } extern "C" int ceph_setattr(const char *relpath, struct stat *attr, int mask) { Client::stat_precise p_attr = Client::stat_precise(*attr); return client->setattr(relpath, &p_attr, mask); } extern "C" int ceph_setattr_precise(const char *relpath, struct stat_precise *attr, int mask) { return client->setattr(relpath, (Client::stat_precise*)attr, mask); } extern "C" int ceph_chmod(const char *path, mode_t mode) { return client->chmod(path, mode); } extern "C" int ceph_chown(const char *path, uid_t uid, gid_t gid) { return client->chown(path, uid, gid); } extern "C" int ceph_utime(const char *path, struct utimbuf *buf) { return client->utime(path, buf); } extern "C" int ceph_truncate(const char *path, loff_t size) { return client->truncate(path, size); } // file ops extern "C" int ceph_mknod(const char *path, mode_t mode, dev_t rdev) { return client->mknod(path, mode, rdev); } extern "C" int ceph_open(const char *path, int flags, mode_t mode) { return client->open(path, flags, mode); } extern "C" int ceph_close(int fd) { return client->close(fd); } extern "C" loff_t ceph_lseek(int fd, loff_t offset, int whence) { return client->lseek(fd, offset, whence); } extern "C" int ceph_read(int fd, char *buf, loff_t size, loff_t offset) { return client->read(fd, buf, size, offset); } extern "C" int ceph_write(int fd, const char *buf, loff_t size, loff_t offset) { return client->write(fd, buf, size, offset); } extern "C" int ceph_ftruncate(int fd, loff_t size) { return client->ftruncate(fd, size); } extern "C" int ceph_fsync(int fd, bool syncdataonly) { return client->fsync(fd, syncdataonly); } extern "C" int ceph_fstat(int fd, struct stat *stbuf) { return client->fstat(fd, stbuf); } extern "C" int ceph_sync_fs() { return client->sync_fs(); } extern "C" int ceph_get_file_stripe_unit(int fh) { return client->get_file_stripe_unit(fh); } extern "C" int ceph_get_file_replication(const char *path) { int fd = client->open(path, O_RDONLY); int rep = client->get_file_replication(fd); client->close(fd); return rep; } extern "C" int ceph_get_default_preferred_pg(int fd) { return client->get_default_preferred_pg(fd); } extern "C" int ceph_set_default_file_stripe_unit(int stripe) { client->set_default_file_stripe_unit(stripe); return 0; } extern "C" int ceph_set_default_file_stripe_count(int count) { client->set_default_file_stripe_unit(count); return 0; } extern "C" int ceph_set_default_object_size(int size) { client->set_default_object_size(size); return 0; } extern "C" int ceph_set_default_file_replication(int replication) { client->set_default_file_replication(replication); return 0; } extern "C" int ceph_set_default_preferred_pg(int pg) { client->set_default_preferred_pg(pg); return 0; } extern "C" int ceph_get_file_stripe_address(int fh, loff_t offset, char *buf, int buflen) { string address; int r = client->get_file_stripe_address(fh, offset, address); if (r != 0) return r; //at time of writing, method ONLY returns // 0 or -EINVAL if there are no known osds int len = address.size()+1; if (len > buflen) { if (buflen == 0) return len; else return -ERANGE; } len = address.copy(buf, len, 0); buf[len] = '\0'; // write a null char to terminate c-style string return 0; } extern "C" int ceph_localize_reads(int val) { if (!client) return -ENOENT; if (!val) client->clear_filer_flags(CEPH_OSD_FLAG_LOCALIZE_READS); else client->set_filer_flags(CEPH_OSD_FLAG_LOCALIZE_READS); return 0; } <commit_msg>libceph: use the proper version header<commit_after>#include "client/libceph.h" #include <string.h> #include <fcntl.h> #include <iostream> #include "common/ceph_argparse.h" #include "common/Mutex.h" #include "messages/MMonMap.h" #include "common/common_init.h" #include "msg/SimpleMessenger.h" #include "client/Client.h" #include "common/version.h" /* ************* ************* ************* ************* * C interface */ extern "C" const char *ceph_version(int *pmajor, int *pminor, int *ppatch) { int major, minor, patch; const char *v = ceph_version_to_str(); int n = sscanf(v, "%d.%d.%d", &major, &minor, &patch); if (pmajor) *pmajor = (n >= 1) ? major : 0; if (pminor) *pminor = (n >= 2) ? minor : 0; if (ppatch) *ppatch = (n >= 3) ? patch : 0; return VERSION; } static Mutex ceph_client_mutex("ceph_client"); static int client_initialized = 0; static int client_mount = 0; static Client *client = NULL; static MonClient *monclient = NULL; static SimpleMessenger *messenger = NULL; static int instance = 0; extern "C" int ceph_initialize(int argc, const char **argv) { ceph_client_mutex.Lock(); if (!client_initialized) { //create everything to start a client vector<const char*> args; argv_to_vec(argc, argv, args); // The libceph API needs to be fixed so that we don't have to call // common_init here. Libraries should never call common_init. common_init(args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_LIBRARY, 0); keyring_init(&g_conf); //monmap monclient = new MonClient(); if (monclient->build_initial_monmap() < 0) { delete monclient; return -1; //error! } //network connection messenger = new SimpleMessenger(); messenger->register_entity(entity_name_t::CLIENT()); //at last the client client = new Client(messenger, monclient); uint64_t nonce = (uint64_t)++instance * 1000000ull + (uint64_t)getpid(); messenger->start(false, nonce); // do not daemonize client->init(); } ++client_initialized; ceph_client_mutex.Unlock(); return 0; } extern "C" void ceph_deinitialize() { ceph_client_mutex.Lock(); --client_initialized; if(!client_initialized) { if(client_mount) { client_mount = 0; client->unmount(); } client->shutdown(); delete client; messenger->wait(); messenger->destroy(); delete monclient; } ceph_client_mutex.Unlock(); } extern "C" int ceph_mount() { int ret; Mutex::Locker lock(ceph_client_mutex); if(!client_mount) { ret = client->mount(); if (ret!=0) return ret; } ++client_mount; return 0; } extern "C" int ceph_umount() { Mutex::Locker lock(ceph_client_mutex); --client_mount; if (!client_mount) return client->unmount(); return 0; } extern "C" int ceph_statfs(const char *path, struct statvfs *stbuf) { return client->statfs(path, stbuf); } extern "C" int ceph_get_local_osd() { return client->get_local_osd(); } extern "C" int ceph_getcwd(char *buf, int buflen) { string cwd; client->getcwd(cwd); int size = cwd.size()+1; //need space for null character if (size > buflen) { if (buflen == 0) return size; else return -ERANGE; } size = cwd.copy(buf, size); buf[size] = '\0'; //fill in null character return 0; } extern "C" int ceph_chdir (const char *s) { return client->chdir(s); } /*if we want to extern C this, we need to convert it to const char*, which will mean storing it somewhere or else making the caller responsible for delete-ing a c-string they didn't create*/ void ceph_getcwd(string& cwd) { client->getcwd(cwd); } extern "C" int ceph_opendir(const char *name, DIR **dirpp) { return client->opendir(name, dirpp); } extern "C" int ceph_closedir(DIR *dirp) { return client->closedir(dirp); } extern "C" int ceph_readdir_r(DIR *dirp, struct dirent *de) { return client->readdir_r(dirp, de); } extern "C" int ceph_readdirplus_r(DIR *dirp, struct dirent *de, struct stat *st, int *stmask) { return client->readdirplus_r(dirp, de, st, stmask); } extern "C" int ceph_getdents(DIR *dirp, char *buf, int buflen) { return client->getdents(dirp, buf, buflen); } extern "C" int ceph_getdnames(DIR *dirp, char *buf, int buflen) { return client->getdnames(dirp, buf, buflen); } extern "C" void ceph_rewinddir(DIR *dirp) { client->rewinddir(dirp); } extern "C" loff_t ceph_telldir(DIR *dirp) { return client->telldir(dirp); } extern "C" void ceph_seekdir(DIR *dirp, loff_t offset) { client->seekdir(dirp, offset); } extern "C" int ceph_link (const char *existing, const char *newname) { return client->link(existing, newname); } extern "C" int ceph_unlink (const char *path) { return client->unlink(path); } extern "C" int ceph_rename(const char *from, const char *to) { return client->rename(from, to); } // dirs extern "C" int ceph_mkdir(const char *path, mode_t mode) { return client->mkdir(path, mode); } extern "C" int ceph_mkdirs(const char *path, mode_t mode) { return client->mkdirs(path, mode); } extern "C" int ceph_rmdir(const char *path) { return client->rmdir(path); } // symlinks extern "C" int ceph_readlink(const char *path, char *buf, loff_t size) { return client->readlink(path, buf, size); } extern "C" int ceph_symlink(const char *existing, const char *newname) { return client->symlink(existing, newname); } // inode stuff extern "C" int ceph_lstat(const char *path, struct stat *stbuf) { return client->lstat(path, stbuf); } extern "C" int ceph_lstat_precise(const char *path, stat_precise *stbuf) { return client->lstat_precise(path, (Client::stat_precise*)stbuf); } extern "C" int ceph_setattr(const char *relpath, struct stat *attr, int mask) { Client::stat_precise p_attr = Client::stat_precise(*attr); return client->setattr(relpath, &p_attr, mask); } extern "C" int ceph_setattr_precise(const char *relpath, struct stat_precise *attr, int mask) { return client->setattr(relpath, (Client::stat_precise*)attr, mask); } extern "C" int ceph_chmod(const char *path, mode_t mode) { return client->chmod(path, mode); } extern "C" int ceph_chown(const char *path, uid_t uid, gid_t gid) { return client->chown(path, uid, gid); } extern "C" int ceph_utime(const char *path, struct utimbuf *buf) { return client->utime(path, buf); } extern "C" int ceph_truncate(const char *path, loff_t size) { return client->truncate(path, size); } // file ops extern "C" int ceph_mknod(const char *path, mode_t mode, dev_t rdev) { return client->mknod(path, mode, rdev); } extern "C" int ceph_open(const char *path, int flags, mode_t mode) { return client->open(path, flags, mode); } extern "C" int ceph_close(int fd) { return client->close(fd); } extern "C" loff_t ceph_lseek(int fd, loff_t offset, int whence) { return client->lseek(fd, offset, whence); } extern "C" int ceph_read(int fd, char *buf, loff_t size, loff_t offset) { return client->read(fd, buf, size, offset); } extern "C" int ceph_write(int fd, const char *buf, loff_t size, loff_t offset) { return client->write(fd, buf, size, offset); } extern "C" int ceph_ftruncate(int fd, loff_t size) { return client->ftruncate(fd, size); } extern "C" int ceph_fsync(int fd, bool syncdataonly) { return client->fsync(fd, syncdataonly); } extern "C" int ceph_fstat(int fd, struct stat *stbuf) { return client->fstat(fd, stbuf); } extern "C" int ceph_sync_fs() { return client->sync_fs(); } extern "C" int ceph_get_file_stripe_unit(int fh) { return client->get_file_stripe_unit(fh); } extern "C" int ceph_get_file_replication(const char *path) { int fd = client->open(path, O_RDONLY); int rep = client->get_file_replication(fd); client->close(fd); return rep; } extern "C" int ceph_get_default_preferred_pg(int fd) { return client->get_default_preferred_pg(fd); } extern "C" int ceph_set_default_file_stripe_unit(int stripe) { client->set_default_file_stripe_unit(stripe); return 0; } extern "C" int ceph_set_default_file_stripe_count(int count) { client->set_default_file_stripe_unit(count); return 0; } extern "C" int ceph_set_default_object_size(int size) { client->set_default_object_size(size); return 0; } extern "C" int ceph_set_default_file_replication(int replication) { client->set_default_file_replication(replication); return 0; } extern "C" int ceph_set_default_preferred_pg(int pg) { client->set_default_preferred_pg(pg); return 0; } extern "C" int ceph_get_file_stripe_address(int fh, loff_t offset, char *buf, int buflen) { string address; int r = client->get_file_stripe_address(fh, offset, address); if (r != 0) return r; //at time of writing, method ONLY returns // 0 or -EINVAL if there are no known osds int len = address.size()+1; if (len > buflen) { if (buflen == 0) return len; else return -ERANGE; } len = address.copy(buf, len, 0); buf[len] = '\0'; // write a null char to terminate c-style string return 0; } extern "C" int ceph_localize_reads(int val) { if (!client) return -ENOENT; if (!val) client->clear_filer_flags(CEPH_OSD_FLAG_LOCALIZE_READS); else client->set_filer_flags(CEPH_OSD_FLAG_LOCALIZE_READS); return 0; } <|endoftext|>
<commit_before>#include "loader.h" Loader::Loader(Disk &diskName) { std::string textFromFile = loadTextFile("..\\res\\Program-File.txt"); //this can be made more efficient by modifying parseString_v method in loader.cpp, having a switch statement inside the while loop to load two //PCB(control cards) and instructions to a vector at the same time. std::vector<std::string> v_JobsCC = parseString_v(textFromFile, "// J"); //job Control Card std::vector<std::string> v_JobsDataCC = parseString_v(textFromFile, "// D");//job data Control Card std::vector<std::string> v_Instructions = parseString_v(textFromFile, "0x");//instructions to be stored in Harddrive std::vector<Loader::JobBlock> loadedJobBlock = loadJobBlock(v_JobsCC); std::vector<Loader::JobDataBlock> loadedJobDataBlock = loadJobDataBlock(v_JobsDataCC); //load into disk jb Disk::JobBlock jb = diskName.getJobBlock(); std::vector<Disk::JobBlock> tempJBVector; for (auto i : loadedJobBlock){ jb.id = i.id; jb.priority = i.priority; jb.wordSize = i.wordSize; tempJBVector.push_back(jb); } diskName.setVectorJB(tempJBVector); //load into disk jdb Disk::JobDataBlock jdb = diskName.getJobDataBlock(); std::vector<Disk::JobDataBlock> tempJDBVector; for (auto i : loadedJobDataBlock){ jdb.inputBufferSize = i.inputBufferSize; jdb.outputBufferSize = i.outputBufferSize; jdb.tempBufferSize = i.tempBufferSize; tempJDBVector.push_back(jdb); } diskName.setVectorJDB(tempJDBVector); //load into disk instructions diskName.getVectorDataInstructions().clear(); diskName.setVectorDataInstruction(v_Instructions); } std::string Loader::loadTextFile(const std::string &fileName) { std::ifstream file; file.open(fileName); std::string output; std::string line; if (file.is_open()) { while (file.good()) { getline(file, line); output.append(line + '\n'); } } else { std::cout << "Unable to load file: " << fileName << '\n'; } return output; } //splits the string into individual lines and adds each line to a vector std::vector<std::string> Loader::parseString_v(std::string &fullStr, std::string const &token){ std::vector<std::string> result; std::string temp; std::istringstream ss(fullStr); while (std::getline(ss, temp)){ if (std::strstr(temp.c_str(), token.c_str())){ result.push_back(temp); } } return result; } std::vector<std::string> splitInit(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; splitInit(s, delim, elems); return elems; } std::vector<Loader::JobBlock> Loader::loadJobBlock(const std::vector<std::string> &str){ std::vector<Loader::JobBlock> result; Loader::JobBlock jb; for (auto i : str){ std::vector<std::string> parsedJobStats = split(i, ' '); unsigned long id = std::stoul(parsedJobStats[2],nullptr, 16); unsigned long wordSize = std::stoul(parsedJobStats[3], nullptr, 16); unsigned long priority = std::stoul(parsedJobStats[4], nullptr, 16); jb.id = id; jb.priority = priority; jb.wordSize = wordSize; result.push_back(jb); } return result; } std::vector<Loader::JobDataBlock> Loader::loadJobDataBlock(const std::vector<std::string> &str){ std::vector<Loader::JobDataBlock> result; Loader::JobDataBlock jdb; for (auto i : str){ std::vector<std::string> parsedJobStats = split(i, ' '); unsigned long inputBufferSize = std::stoul(parsedJobStats[2], nullptr, 16); unsigned long outputBufferSize = std::stoul(parsedJobStats[3], nullptr, 16); unsigned long tempBufferSize = std::stoul(parsedJobStats[4], nullptr, 16); jdb.inputBufferSize = inputBufferSize; jdb.outputBufferSize = outputBufferSize; jdb.tempBufferSize = tempBufferSize; result.push_back(jdb); } return result; } <commit_msg>added cstring header<commit_after>#include "loader.h" #include <cstring> Loader::Loader(Disk &diskName) { std::string textFromFile = loadTextFile("..\\res\\Program-File.txt"); //this can be made more efficient by modifying parseString_v method in loader.cpp, having a switch statement inside the while loop to load two //PCB(control cards) and instructions to a vector at the same time. std::vector<std::string> v_JobsCC = parseString_v(textFromFile, "// J"); //job Control Card std::vector<std::string> v_JobsDataCC = parseString_v(textFromFile, "// D");//job data Control Card std::vector<std::string> v_Instructions = parseString_v(textFromFile, "0x");//instructions to be stored in Harddrive std::vector<Loader::JobBlock> loadedJobBlock = loadJobBlock(v_JobsCC); std::vector<Loader::JobDataBlock> loadedJobDataBlock = loadJobDataBlock(v_JobsDataCC); //load into disk jb Disk::JobBlock jb = diskName.getJobBlock(); std::vector<Disk::JobBlock> tempJBVector; for (auto i : loadedJobBlock){ jb.id = i.id; jb.priority = i.priority; jb.wordSize = i.wordSize; tempJBVector.push_back(jb); } diskName.setVectorJB(tempJBVector); //load into disk jdb Disk::JobDataBlock jdb = diskName.getJobDataBlock(); std::vector<Disk::JobDataBlock> tempJDBVector; for (auto i : loadedJobDataBlock){ jdb.inputBufferSize = i.inputBufferSize; jdb.outputBufferSize = i.outputBufferSize; jdb.tempBufferSize = i.tempBufferSize; tempJDBVector.push_back(jdb); } diskName.setVectorJDB(tempJDBVector); //load into disk instructions diskName.getVectorDataInstructions().clear(); diskName.setVectorDataInstruction(v_Instructions); } std::string Loader::loadTextFile(const std::string &fileName) { std::ifstream file; file.open(fileName); std::string output; std::string line; if (file.is_open()) { while (file.good()) { getline(file, line); output.append(line + '\n'); } } else { std::cout << "Unable to load file: " << fileName << '\n'; } return output; } //splits the string into individual lines and adds each line to a vector std::vector<std::string> Loader::parseString_v(std::string &fullStr, std::string const &token){ std::vector<std::string> result; std::string temp; std::istringstream ss(fullStr); while (std::getline(ss, temp)){ if (std::strstr(temp.c_str(), token.c_str())){ result.push_back(temp); } } return result; } std::vector<std::string> splitInit(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; splitInit(s, delim, elems); return elems; } std::vector<Loader::JobBlock> Loader::loadJobBlock(const std::vector<std::string> &str){ std::vector<Loader::JobBlock> result; Loader::JobBlock jb; for (auto i : str){ std::vector<std::string> parsedJobStats = split(i, ' '); unsigned long id = std::stoul(parsedJobStats[2],nullptr, 16); unsigned long wordSize = std::stoul(parsedJobStats[3], nullptr, 16); unsigned long priority = std::stoul(parsedJobStats[4], nullptr, 16); jb.id = id; jb.priority = priority; jb.wordSize = wordSize; result.push_back(jb); } return result; } std::vector<Loader::JobDataBlock> Loader::loadJobDataBlock(const std::vector<std::string> &str){ std::vector<Loader::JobDataBlock> result; Loader::JobDataBlock jdb; for (auto i : str){ std::vector<std::string> parsedJobStats = split(i, ' '); unsigned long inputBufferSize = std::stoul(parsedJobStats[2], nullptr, 16); unsigned long outputBufferSize = std::stoul(parsedJobStats[3], nullptr, 16); unsigned long tempBufferSize = std::stoul(parsedJobStats[4], nullptr, 16); jdb.inputBufferSize = inputBufferSize; jdb.outputBufferSize = outputBufferSize; jdb.tempBufferSize = tempBufferSize; result.push_back(jdb); } return result; } <|endoftext|>
<commit_before>#include <fstream> #include <string> #include <iostream> #include <sstream> #include "sysfs_w1.h" bool operator== (const TSysfsOnewireDevice & first, const TSysfsOnewireDevice & second) { return first.DeviceName == second.DeviceName; } TSysfsOnewireDevice::TSysfsOnewireDevice(const string& device_name) : DeviceName(device_name) { //FIXME: fill family number Family = TOnewireFamilyType::ProgResThermometer; DeviceId = DeviceName.substr(3, 3+6*2); DeviceDir = SysfsOnewireDevicesPath + DeviceName; } TMaybe<float> TSysfsOnewireDevice::ReadTemperature() const { std::string data; bool bFoundCrcOk=false; static const std::string tag("t="); std::ifstream file; std::string fileName=DeviceDir +"/w1_slave"; file.open(fileName.c_str()); if (file.is_open()) { std::string sLine; while (!file.eof()) { getline(file, sLine); int tpos; if (sLine.find("crc=")!=std::string::npos) { if (sLine.find("YES")!=std::string::npos) { bFoundCrcOk=true; } } else if ((tpos=sLine.find(tag))!=std::string::npos) { data = sLine.substr(tpos+tag.length()); } } file.close(); } if (bFoundCrcOk) { int data_int = std::stoi(data); if (data_int == 85000) { // wrong read return NotDefinedMaybe; } if (data_int == 127937) { // returned max possible temp, probably an error // (it happens for chineese clones) return NotDefinedMaybe; } return (float) data_int/1000.0f; // Temperature given by kernel is in thousandths of degrees } return NotDefinedMaybe; } void TSysfsOnewireManager::RescanBus() { } <commit_msg>wb-homa-w1: fix compiler warning.<commit_after>#include <fstream> #include <string> #include <iostream> #include <sstream> #include "sysfs_w1.h" bool operator== (const TSysfsOnewireDevice & first, const TSysfsOnewireDevice & second) { return first.DeviceName == second.DeviceName; } TSysfsOnewireDevice::TSysfsOnewireDevice(const string& device_name) : DeviceName(device_name) { //FIXME: fill family number Family = TOnewireFamilyType::ProgResThermometer; DeviceId = DeviceName.substr(3, 3+6*2); DeviceDir = SysfsOnewireDevicesPath + DeviceName; } TMaybe<float> TSysfsOnewireDevice::ReadTemperature() const { std::string data; bool bFoundCrcOk=false; static const std::string tag("t="); std::ifstream file; std::string fileName=DeviceDir +"/w1_slave"; file.open(fileName.c_str()); if (file.is_open()) { std::string sLine; while (!file.eof()) { getline(file, sLine); size_t tpos; if (sLine.find("crc=")!=std::string::npos) { if (sLine.find("YES")!=std::string::npos) { bFoundCrcOk=true; } } else if ((tpos=sLine.find(tag))!=std::string::npos) { data = sLine.substr(tpos+tag.length()); } } file.close(); } if (bFoundCrcOk) { int data_int = std::stoi(data); if (data_int == 85000) { // wrong read return NotDefinedMaybe; } if (data_int == 127937) { // returned max possible temp, probably an error // (it happens for chineese clones) return NotDefinedMaybe; } return (float) data_int/1000.0f; // Temperature given by kernel is in thousandths of degrees } return NotDefinedMaybe; } void TSysfsOnewireManager::RescanBus() { } <|endoftext|>
<commit_before>#include <iostream> #include <execinfo.h> #include <sdsl/vectors.hpp> #include <sdsl/lcp.hpp> #include <sdsl/suffix_arrays.hpp> #include <sdsl/wavelet_trees.hpp> #include <sdsl/config.hpp> #include "OrderedAlphabet.hpp" #include "DataTypes.h" #include "WTRank.h" #include "Algorithm1A.h" #include "Algorithm2A.hpp" using namespace std; using namespace sdsl; int main(int argc, char* argv[]){ string file = argv[1]; cache_config cc = true; csa_wt<> csa; construct(csa, file, 1); cc.delete_files = true; lcp_wt<> lcp; // Algorithm run: Start measuring time chrono::high_resolution_clock::time_point t1 = chrono::high_resolution_clock::now(); // START THE ALGORITHM construct(lcp, file, 1); cout << lcp << endl; // Algorithm stop: Stop measuring time chrono::high_resolution_clock::time_point t2 = chrono::high_resolution_clock::now(); // Print algorithm run-time on screen auto duration = chrono::duration_cast<chrono::microseconds>( t2 - t1 ).count(); cout << "Algorithm Duration: " << duration / ((float)1000000) << " seconds" << endl; /* * Measure memory usage of current process... * Measuring RSS... Resident Set Size * the portion of memory occupied by a process * that is held in main memory (RAM) * * @param usage Structure that is holding data of the memory usage */ { struct rusage usage; getrusage(RUSAGE_SELF, &usage); cout << "Memory usage: "<< usage.ru_maxrss/((float)1024) << " MB of RAM" << endl; } } } <commit_msg>mainSG update<commit_after>#include <iostream> #include <execinfo.h> #include <sdsl/vectors.hpp> #include <sdsl/lcp.hpp> #include <sdsl/suffix_arrays.hpp> #include <sdsl/wavelet_trees.hpp> #include <sdsl/config.hpp> #include "OrderedAlphabet.hpp" #include "DataTypes.h" #include "WTRank.h" #include "Algorithm1A.h" #include "Algorithm2A.hpp" using namespace std; using namespace sdsl; int main(int argc, char* argv[]){ string file = argv[1]; cache_config cc = true; csa_wt<> csa; construct(csa, file, 1); cc.delete_files = true; lcp_wt<> LCP; // Algorithm run: Start measuring time chrono::high_resolution_clock::time_point t1 = chrono::high_resolution_clock::now(); // START THE ALGORITHM construct(LCP, file, 1); // Algorithm stop: Stop measuring time chrono::high_resolution_clock::time_point t2 = chrono::high_resolution_clock::now(); // Print algorithm run-time on screen auto duration = chrono::duration_cast<chrono::microseconds>( t2 - t1 ).count(); cout << "Algorithm Duration: " << duration / ((float)1000000) << " seconds" << endl; /* * Measure memory usage of current process... * Measuring RSS... Resident Set Size * the portion of memory occupied by a process * that is held in main memory (RAM) * * @param usage Structure that is holding data of the memory usage */ { struct rusage usage; getrusage(RUSAGE_SELF, &usage); cout << "Memory usage: "<< usage.ru_maxrss/((float)1024) << " MB of RAM" << endl; } // get inFile name with no extension std::string filename = "./"; filename.append(file.substr(0, file.find("."))); // append it with output extension filename.append("_lcp_SG_out.txt"); std::ofstream output_file(filename); std::ostream_iterator<index_type> output_iterator(output_file, " "); std::copy(LCP.begin(), LCP.end(), output_iterator); } <|endoftext|>
<commit_before>#include "Logger.hpp" #include "Environment.hpp" #include "Filesystem.hpp" #include "Renderer.hpp" #include "Taskbar.hpp" #include "Pane.hpp" #include "Util.hpp" #include <ctime> Environment::Environment(sf::VideoMode dimensions, std::string title, int envID) { if (!environment::util::fs_ready()) environment::util:: ready_fs(); logger::setOutputDir("root", ("environment" + std::to_string(envID))); logger::INFO("Creating new Environment instance..."); environmentID = envID; window = std::make_shared<sf::RenderWindow>(dimensions, (title + " (" + std::to_string(envID) + ")"), (sf::Style::Close | sf::Style::Titlebar)); renderman = std::make_shared<Renderer>(window); taskbar = std::make_shared<Taskbar>(this); window->setFramerateLimit(60); nullPane = new Pane(sf::Vector2f(0, 0), "null", 0, this); logger::INFO("New Environment instance created."); } Environment::~Environment() { logger::INFO("Cleaning up..."); window->close(); logger::INFO("Environment destroyed."); } bool mouseIsOver(sf::Shape &object, sf::RenderWindow &window) { if (object.getGlobalBounds().contains(window.mapPixelToCoords(sf::Mouse::getPosition(window)))) return true; else return false; } void Environment::switchFocusedPaneTo(Pane* pane) { if (panes.size() > 1 && pane != nullPane) focusedPane->defocus(); focusedPane = pane; focusedPane->focus(); } void Environment::main() { renderman->addToQueue(&taskbar->bar); renderman->addToQueue(&taskbar->start_button); renderman->addToQueue(&taskbar->div); renderman->addToQueue(&taskbar->time); bool dragging_pane(false); while (window->isOpen()) { sf::Event event; while (window->pollEvent(event)) { if (event.type == sf::Event::EventType::Closed) { panes.clear(); renderman->clearQueue(); window->close(); return; } else if (event.type == sf::Event::EventType::MouseButtonPressed) { if (event.key.code == sf::Mouse::Left) { if (!panes.empty()) // make sure there are panes { bool selected(false); bool already_selected(false); // if we clicked on any pane for (int i = panes.size() - 1; i >= 0; i--) // this doesn't work, i don't know how to fix it. { if (mouseIsOver(panes[i]->boundingbox, *window)) // check if we're in the pane { logger::INFO("Clicked inside the boundingbox of Pane" + std::to_string(panes[i]->PID)); if (mouseIsOver(panes[i]->titlebar, *window)) // then on the title bar { logger::INFO("Clicked inside the titlebar of Pane" + std::to_string(panes[i]->PID)); if (mouseIsOver(panes[i]->closebutton, *window)) // then the close button { logger::INFO("Clicked the close button of Pane" + std::to_string(panes[i]->PID)); renderman->removeFromQueue(&panes[i]->titletext); renderman->removeFromQueue(&panes[i]->titlebar); renderman->removeFromQueue(&panes[i]->mainpane); renderman->removeFromQueue(&panes[i]->closebutton); renderman->removeFromQueue(&panes[i]->leftborder); renderman->removeFromQueue(&panes[i]->rightborder); renderman->removeFromQueue(&panes[i]->bottomborder); delete panes[i]; panes.erase(std::remove(panes.begin(), panes.end(), panes[i]), panes.end()); break; } else { logger::INFO("Clicked only the titlebar, started dragging."); dragging_pane = true; } } if (panes[i] == focusedPane) { already_selected = true; logger::INFO("Pane" + std::to_string(focusedPane->PID) + " was already focused."); } else // wasn't already selected. { logger::INFO("Pane" + std::to_string(focusedPane->PID) + " was not already focused."); switchFocusedPaneTo(panes[i]); selected = true; logger::INFO("Bringing Pane" + std::to_string(focusedPane->PID) + " to the top of the Render Queue."); renderman->pushBack(&focusedPane->titletext); renderman->pushBack(&focusedPane->titlebar); renderman->pushBack(&focusedPane->closebutton); renderman->pushBack(&focusedPane->mainpane); renderman->pushBack(&focusedPane->leftborder); renderman->pushBack(&focusedPane->rightborder); renderman->pushBack(&focusedPane->bottomborder); renderman->pushBack(&focusedPane->titletext); } break; } } // if we didn't select anything, do nothing. // if there is nothing we *could have* selected, do nothing (because they might have clicked the close button). if (!already_selected && !panes.empty()) { if (!selected) { if (focusedPane != nullPane) { logger::INFO("Nothing was selected. (Not even Pane0 D:)"); focusedPane->defocus(); focusedPane = nullPane; } else { logger::INFO("No pane was already selected."); } } else { logger::INFO("Something new was selected. (Pane" + std::to_string(focusedPane->PID) + ")"); } } } if (mouseIsOver(taskbar->bar, *window)) // if we click the taskbar { if (mouseIsOver(taskbar->start_button, *window)) // clicked the startbutton { logger::INFO("Clicked the start button."); taskbar->start_button.setFillColor(sf::Color::Green); if (!panes.empty()) // TODO: this focusedPane->defocus(); // we defocus it because we are focused on the start menu while we do this, we will refocus when the start menu is closed. } } } } else if (event.type == sf::Event::EventType::MouseButtonReleased) { if (mouseIsOver(taskbar->bar, *window)) { if (mouseIsOver(taskbar->start_button, *window)) // let go of the start menu { logger::INFO("Released the start button."); taskbar->start_button.setFillColor(sf::Color::Red); // if (!panes.empty() && focusedPane->focused == true) // focusedPane->focus(); // refocus the panel. // we want to refocus the pane only if it was already focused. } } if (dragging_pane) { logger::INFO("Stopped dragging Pane" + std::to_string(focusedPane->PID) + "."); dragging_pane = false; } } else if (event.type == sf::Event::EventType::KeyPressed) { if (event.key.code == sf::Keyboard::Key::N) // NEW PANE HOTKEY { const int PID = panes.size() + 1; Pane* newpane = new Pane(sf::Vector2f(200, 300), "Pane" + std::to_string(PID), PID, this); // renderman->addToQueue(&newpane->boundingbox); renderman->addToQueue(&newpane->titletext); renderman->addToQueue(&newpane->titlebar); renderman->addToQueue(&newpane->closebutton); renderman->addToQueue(&newpane->mainpane); renderman->addToQueue(&newpane->leftborder); renderman->addToQueue(&newpane->rightborder); renderman->addToQueue(&newpane->bottomborder); renderman->addToQueue(&newpane->titletext); panes.push_back(newpane); // add it to the stack switchFocusedPaneTo(newpane); } else if (focusedPane != nullPane && event.key.code == sf::Keyboard::Key::Delete) // DELETE PANE HOTKEY { renderman->removeFromQueue(&focusedPane->titletext); renderman->removeFromQueue(&focusedPane->titlebar); renderman->removeFromQueue(&focusedPane->mainpane); renderman->removeFromQueue(&focusedPane->closebutton); renderman->removeFromQueue(&focusedPane->leftborder); renderman->removeFromQueue(&focusedPane->rightborder); renderman->removeFromQueue(&focusedPane->bottomborder); delete focusedPane; panes.erase(std::remove(panes.begin(), panes.end(), focusedPane), panes.end()); // remove it from the stack focusedPane = nullPane; } } } // event loop { // if we are holding the left alt key and space at the same time, and there is at least one pane, center it. if (!panes.empty() && sf::Keyboard::isKeyPressed(sf::Keyboard::Key::LAlt) && sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Space)) { focusedPane->setPosition(sf::Vector2f(window->getView().getCenter())); logger::INFO("Pane" + std::to_string(focusedPane->PID) + " centered."); } // if we are left clicking, panes exist, and are holding over the focused one, then move it to the position of the mouse. used for click and drag positioning. else if (dragging_pane) { sf::Vector2i move_origin; move_origin.x = sf::Mouse::getPosition(*window).x; move_origin.y = sf::Mouse::getPosition(*window).y; focusedPane->setPosition(sf::Vector2f(move_origin)); } } taskbar->time.setString(environment::util::getTimestamp()); taskbar->time.setOrigin(sf::Vector2f(taskbar->time.getLocalBounds().width / 2, taskbar->time.getLocalBounds().height / 2)); taskbar->time.setPosition(sf::Vector2f((taskbar->bar.getPosition().x * 2) - (taskbar->time.getLocalBounds().width / 1.7), taskbar->bar.getPosition().y - (taskbar->time.getLocalBounds().height / 2.5))); window->clear(sf::Color::Blue); renderman->render(); window->display(); } } <commit_msg>pane is now closed on release mouse button<commit_after>#include "Logger.hpp" #include "Environment.hpp" #include "Filesystem.hpp" #include "Renderer.hpp" #include "Taskbar.hpp" #include "Pane.hpp" #include "Util.hpp" #include <ctime> Environment::Environment(sf::VideoMode dimensions, std::string title, int envID) { if (!environment::util::fs_ready()) environment::util:: ready_fs(); logger::setOutputDir("root", ("environment" + std::to_string(envID))); logger::INFO("Creating new Environment instance..."); environmentID = envID; window = std::make_shared<sf::RenderWindow>(dimensions, (title + " (" + std::to_string(envID) + ")"), (sf::Style::Close | sf::Style::Titlebar)); renderman = std::make_shared<Renderer>(window); taskbar = std::make_shared<Taskbar>(this); window->setFramerateLimit(60); nullPane = new Pane(sf::Vector2f(0, 0), "null", 0, this); logger::INFO("New Environment instance created."); } Environment::~Environment() { logger::INFO("Cleaning up..."); window->close(); logger::INFO("Environment destroyed."); } bool mouseIsOver(sf::Shape &object, sf::RenderWindow &window) { if (object.getGlobalBounds().contains(window.mapPixelToCoords(sf::Mouse::getPosition(window)))) return true; else return false; } void Environment::switchFocusedPaneTo(Pane* pane) { if (panes.size() > 1 && pane != nullPane) focusedPane->defocus(); focusedPane = pane; focusedPane->focus(); } void Environment::main() { renderman->addToQueue(&taskbar->bar); renderman->addToQueue(&taskbar->start_button); renderman->addToQueue(&taskbar->div); renderman->addToQueue(&taskbar->time); bool dragging_pane(false); while (window->isOpen()) { sf::Event event; while (window->pollEvent(event)) { if (event.type == sf::Event::EventType::Closed) { panes.clear(); renderman->clearQueue(); window->close(); return; } else if (event.type == sf::Event::EventType::MouseButtonPressed) { if (event.key.code == sf::Mouse::Left) { if (!panes.empty()) // make sure there are panes { bool selected(false); bool already_selected(false); // if we clicked on any pane for (int i = panes.size() - 1; i >= 0; i--) // this doesn't work, i don't know how to fix it. { if (mouseIsOver(panes[i]->boundingbox, *window)) // check if we're in the pane { logger::INFO("Clicked inside the boundingbox of Pane" + std::to_string(panes[i]->PID)); if (mouseIsOver(panes[i]->titlebar, *window)) // then on the title bar { logger::INFO("Clicked inside the titlebar of Pane" + std::to_string(panes[i]->PID)); if (!mouseIsOver(panes[i]->closebutton, *window)) // not on the close button { logger::INFO("Clicked only the titlebar, started dragging."); sf::Vector2i mousePosition = sf::Mouse::getPosition(); logger::INFO("distance on y is: " + std::to_string(sf::Mouse::getPosition(*window).y - focusedPane->titlebar.getPosition().y) + " pixels."); if (mousePosition.x > focusedPane->titlebar.getPosition().x) { logger::INFO("mouse is on left of titlebar"); } else if (mousePosition.x > focusedPane->titlebar.getPosition().x) { logger::INFO("mouse is on right of titlebar"); } logger::INFO("mouse pos" + std::to_string(sf::Mouse::getPosition(*window).y)); logger::INFO("titlebar pos" + std::to_string(focusedPane->titlebar.getPosition().y)); if (mousePosition.x > focusedPane->titlebar.getPosition().x) logger::INFO("mouse over titlebar origin"); else if (mousePosition.x < focusedPane->titlebar.getPosition().x) logger::INFO("mouse below titlebar origin"); else logger::INFO("where the fuck is the mouse"); dragging_pane = true; } } if (panes[i] == focusedPane) { already_selected = true; logger::INFO("Pane" + std::to_string(focusedPane->PID) + " was already focused."); } else // wasn't already selected. { logger::INFO("Pane" + std::to_string(focusedPane->PID) + " was not already focused."); switchFocusedPaneTo(panes[i]); selected = true; logger::INFO("Bringing Pane" + std::to_string(focusedPane->PID) + " to the top of the Render Queue."); renderman->pushBack(&focusedPane->titletext); renderman->pushBack(&focusedPane->titlebar); renderman->pushBack(&focusedPane->closebutton); renderman->pushBack(&focusedPane->mainpane); renderman->pushBack(&focusedPane->leftborder); renderman->pushBack(&focusedPane->rightborder); renderman->pushBack(&focusedPane->bottomborder); renderman->pushBack(&focusedPane->titletext); } break; } } // if we didn't select anything, do nothing. // if there is nothing we *could have* selected, do nothing (because they might have clicked the close button). if (!already_selected && !panes.empty()) { if (!selected) { if (focusedPane != nullPane) { logger::INFO("Nothing was selected. (Not even Pane0 D:)"); focusedPane->defocus(); focusedPane = nullPane; } else { logger::INFO("No pane was already selected."); } } else { logger::INFO("Something new was selected. (Pane" + std::to_string(focusedPane->PID) + ")"); } } } if (mouseIsOver(taskbar->bar, *window)) // if we click the taskbar { if (mouseIsOver(taskbar->start_button, *window)) // clicked the startbutton { logger::INFO("Clicked the start button."); taskbar->start_button.setFillColor(sf::Color::Green); if (!panes.empty()) // TODO: this focusedPane->defocus(); // we defocus it because we are focused on the start menu while we do this, we will refocus when the start menu is closed. } } } } else if (event.type == sf::Event::EventType::MouseButtonReleased) { if (mouseIsOver(taskbar->bar, *window)) { if (mouseIsOver(taskbar->start_button, *window)) // let go of the start menu { logger::INFO("Released the start button."); taskbar->start_button.setFillColor(sf::Color::Red); // if (!panes.empty() && focusedPane->focused == true) // focusedPane->focus(); // refocus the panel. // we want to refocus the pane only if it was already focused. } } else if (mouseIsOver(focusedPane->boundingbox, *window)) // check if we're in the pane (and somehow don't crash the entire shitter) { logger::INFO("Released inside the boundingbox of Pane" + std::to_string(focusedPane->PID)); if (mouseIsOver(focusedPane->titlebar, *window)) // then on the title bar { logger::INFO("Released inside the titlebar of Pane" + std::to_string(focusedPane->PID)); if (mouseIsOver(focusedPane->closebutton, *window)) // then the close button { logger::INFO("Released the close button of Pane" + std::to_string(focusedPane->PID)); renderman->removeFromQueue(&focusedPane->titletext); renderman->removeFromQueue(&focusedPane->titlebar); renderman->removeFromQueue(&focusedPane->mainpane); renderman->removeFromQueue(&focusedPane->closebutton); renderman->removeFromQueue(&focusedPane->leftborder); renderman->removeFromQueue(&focusedPane->rightborder); renderman->removeFromQueue(&focusedPane->bottomborder); delete focusedPane; panes.erase(std::remove(panes.begin(), panes.end(), focusedPane), panes.end()); // remove it from the stack focusedPane = nullPane; } } } if (dragging_pane) { logger::INFO("Stopped dragging Pane" + std::to_string(focusedPane->PID) + "."); dragging_pane = false; } } else if (event.type == sf::Event::EventType::KeyPressed) { if (event.key.code == sf::Keyboard::Key::N) // NEW PANE HOTKEY { const int PID = panes.size() + 1; Pane* newpane = new Pane(sf::Vector2f(200, 300), "Pane" + std::to_string(PID), PID, this); // renderman->addToQueue(&newpane->boundingbox); renderman->addToQueue(&newpane->titletext); renderman->addToQueue(&newpane->titlebar); renderman->addToQueue(&newpane->closebutton); renderman->addToQueue(&newpane->mainpane); renderman->addToQueue(&newpane->leftborder); renderman->addToQueue(&newpane->rightborder); renderman->addToQueue(&newpane->bottomborder); renderman->addToQueue(&newpane->titletext); panes.push_back(newpane); // add it to the stack switchFocusedPaneTo(newpane); } else if (focusedPane != nullPane && event.key.code == sf::Keyboard::Key::Delete) // DELETE PANE HOTKEY { renderman->removeFromQueue(&focusedPane->titletext); renderman->removeFromQueue(&focusedPane->titlebar); renderman->removeFromQueue(&focusedPane->mainpane); renderman->removeFromQueue(&focusedPane->closebutton); renderman->removeFromQueue(&focusedPane->leftborder); renderman->removeFromQueue(&focusedPane->rightborder); renderman->removeFromQueue(&focusedPane->bottomborder); delete focusedPane; panes.erase(std::remove(panes.begin(), panes.end(), focusedPane), panes.end()); // remove it from the stack focusedPane = nullPane; } } } // event loop { // if we are holding the left alt key and space at the same time, and there is at least one pane, center it. if (!panes.empty() && sf::Keyboard::isKeyPressed(sf::Keyboard::Key::LAlt) && sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Space)) { focusedPane->setPosition(sf::Vector2f(window->getView().getCenter())); logger::INFO("Pane" + std::to_string(focusedPane->PID) + " centered."); } // if we are left clicking, panes exist, and are holding over the focused one, then move it to the position of the mouse. used for click and drag positioning. else if (dragging_pane) { sf::Vector2i move_origin; move_origin.x = sf::Mouse::getPosition(*window).x; move_origin.y = sf::Mouse::getPosition(*window).y; focusedPane->setPosition(sf::Vector2f(move_origin)); } } taskbar->time.setString(environment::util::getTimestamp()); taskbar->time.setOrigin(sf::Vector2f(taskbar->time.getLocalBounds().width / 2, taskbar->time.getLocalBounds().height / 2)); taskbar->time.setPosition(sf::Vector2f((taskbar->bar.getPosition().x * 2) - (taskbar->time.getLocalBounds().width / 1.7), taskbar->bar.getPosition().y - (taskbar->time.getLocalBounds().height / 2.5))); window->clear(sf::Color::Blue); renderman->render(); window->display(); } } <|endoftext|>
<commit_before>#include <algorithm> // random_shuffle, transform #include <cassert> #include <chrono> #include <fstream> #include <iostream> #include <random> #include <set> #include <utility> // pair #include <sdd/sdd.hh> #include <sdd/dd/lua.hh> #include "mc/bound_error.hh" #include "mc/bounded_post.hh" #include "mc/dead.hh" #include "mc/live.hh" #include "mc/post.hh" #include "mc/pre.hh" #include "mc/work.hh" namespace pnmc { namespace mc { namespace chrono = std::chrono; typedef sdd::conf1 sdd_conf; typedef sdd::SDD<sdd_conf> SDD; typedef sdd::homomorphism<sdd_conf> homomorphism; using sdd::Composition; using sdd::Fixpoint; using sdd::Intersection; using sdd::Sum; using sdd::ValuesFunction; /*------------------------------------------------------------------------------------------------*/ struct mk_order_visitor : public boost::static_visitor<std::pair<std::string, sdd::order_builder<sdd_conf>>> { using order_identifier = sdd::order_identifier<sdd_conf>; using result_type = std::pair<order_identifier, sdd::order_builder<sdd_conf>>; using order_builder = sdd::order_builder<sdd_conf>; const conf::pnmc_configuration& conf; mutable unsigned int artificial_id_counter; mk_order_visitor(const conf::pnmc_configuration& c) : conf(c), artificial_id_counter(0) {} // Place: base case of the recursion, there's no more possible nested hierarchies. result_type operator()(const pn::place* p) const noexcept { return std::make_pair(order_identifier(p->id), order_builder()); } // Hierarchy. result_type operator()(const pn::module_node& m) const noexcept { assert(not m.nested.empty()); std::deque<result_type> tmp; for (const auto& h : m.nested) { const auto res = boost::apply_visitor(*this, *h); tmp.push_back(res); } std::size_t height = 0; for (const auto& p : tmp) { if (not p.second.empty()) { height += p.second.height(); } else { height += 1; // place } } order_builder ob; if (height <= conf.order_min_height) { order_identifier id; for (const auto& p : tmp) { if (not p.second.empty()) { ob = p.second << ob; } else // place { ob.push(p.first, p.second); } } return result_type(id, ob); } else { for (const auto& p : tmp) { ob.push(p.first, p.second); } } return std::make_pair(order_identifier(m.id) , ob); } }; /*------------------------------------------------------------------------------------------------*/ sdd::order<sdd_conf> mk_order(const conf::pnmc_configuration& conf, const pn::net& net) { if (not conf.order_force_flat and net.modules) { return sdd::order<sdd_conf>(boost::apply_visitor(mk_order_visitor(conf), *net.modules).second); } else { sdd::order_builder<sdd_conf> ob; if (conf.order_random) { std::vector<std::string> tmp; tmp.reserve(net.places().size()); std::transform( net.places().cbegin(), net.places().cend(), std::back_inserter(tmp) , [](const pn::place& p){return p.id;}); std::random_device rd; std::mt19937 g(rd()); std::shuffle(tmp.begin(), tmp.end(), g); for (const auto& id : tmp) { ob.push(id); } } else { for (const auto& place : net.places()) { ob.push(place.id); } } return sdd::order<sdd_conf>(ob); } } /*------------------------------------------------------------------------------------------------*/ SDD initial_state(const sdd::order<sdd_conf>& order, const pn::net& net) { return SDD(order, [&](const std::string& id) -> sdd::values::flat_set<unsigned int> { return {net.places_by_id().find(id)->marking}; }); } /*------------------------------------------------------------------------------------------------*/ homomorphism transition_relation( const conf::pnmc_configuration& conf, const sdd::order<sdd_conf>& o , const pn::net& net, boost::dynamic_bitset<>& transitions_bitset) { chrono::time_point<chrono::system_clock> start; chrono::time_point<chrono::system_clock> end; std::size_t elapsed; start = chrono::system_clock::now(); std::set<homomorphism> operands; operands.insert(sdd::Id<sdd_conf>()); for (const auto& transition : net.transitions()) { homomorphism h_t = sdd::Id<sdd_conf>(); // Add a "canary" to detect live transitions. if (conf.compute_dead_transitions) { if (not transition.post.empty()) { const auto f = ValuesFunction<sdd_conf>( o, transition.post.begin()->first , live(transition.index, transitions_bitset)); h_t = sdd::carrier(o, transition.post.begin()->first, f); } } // Post actions. for (const auto& arc : transition.post) { homomorphism f = conf.marking_bound == 0 ? ValuesFunction<sdd_conf>(o, arc.first, post(arc.second)) : ValuesFunction<sdd_conf>(o, arc.first, bounded_post( arc.second , conf.marking_bound , arc.first)); h_t = Composition(h_t, sdd::carrier(o, arc.first, f)); } // Pre actions. for (const auto& arc : transition.pre) { homomorphism f = ValuesFunction<sdd_conf>(o, arc.first, pre(arc.second)); h_t = Composition(h_t, sdd::carrier(o, arc.first, f)); } operands.insert(h_t); } end = chrono::system_clock::now(); elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "Transition relation time: " << elapsed << "s" << std::endl; } start = chrono::system_clock::now(); const auto res = sdd::rewrite(o, Fixpoint(Sum<sdd_conf>(o, operands.cbegin(), operands.cend()))); end = chrono::system_clock::now(); elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "Rewrite time: " << elapsed << "s" << std::endl; } return res; } /*------------------------------------------------------------------------------------------------*/ SDD state_space( const conf::pnmc_configuration& conf, const sdd::order<sdd_conf>& o, SDD m , homomorphism h) { chrono::time_point<chrono::system_clock> start = chrono::system_clock::now(); const auto res = h(o, m); chrono::time_point<chrono::system_clock> end = chrono::system_clock::now(); const std::size_t elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "State space computation time: " << elapsed << "s" << std::endl; } return res; } /*------------------------------------------------------------------------------------------------*/ SDD dead_states( const conf::pnmc_configuration& conf, const sdd::order<sdd_conf>& o, const pn::net& net , const SDD& state_space) { chrono::time_point<chrono::system_clock> start; chrono::time_point<chrono::system_clock> end; std::size_t elapsed; start = chrono::system_clock::now(); std::set<homomorphism> and_operands; std::set<homomorphism> or_operands; for (const auto& transition : net.transitions()) { // We are only interested in pre actions. for (const auto& arc : transition.pre) { const auto h = ValuesFunction<sdd_conf>(o, arc.first, dead(arc.second)); or_operands.insert(sdd::carrier(o, arc.first, h)); } and_operands.insert(Sum(o, or_operands.cbegin(), or_operands.cend())); or_operands.clear(); } const auto h = sdd::rewrite(o, Intersection(o, and_operands.cbegin(), and_operands.cend())); end = chrono::system_clock::now(); elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "Dead states relation time: " << elapsed << "s" << std::endl; } /* -------------------- */ start = chrono::system_clock::now(); const auto res = h(o, state_space); end = chrono::system_clock::now(); elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "Dead states computation time: " << elapsed << "s" << std::endl; } return res; } /*------------------------------------------------------------------------------------------------*/ void work(const conf::pnmc_configuration& conf, const pn::net& net) { auto manager = sdd::manager<sdd_conf>::init(); boost::dynamic_bitset<> transitions_bitset(net.transitions().size()); const sdd::order<sdd_conf>& o = mk_order(conf, net); assert(not o.empty() && "Empty order"); if (conf.order_show) { std::cout << o << std::endl; } const SDD m0 = initial_state(o, net); const homomorphism h = transition_relation(conf, o, net, transitions_bitset); if (conf.show_relation) { std::cout << h << std::endl; } try { SDD m = sdd::zero<sdd_conf>(); m = state_space(conf, o, m0, h); const auto n = sdd::count_combinations(m); std::cout << n.template convert_to<long double>() << " states" << std::endl; if (conf.compute_dead_transitions) { std::deque<std::string> dead_transitions; for (std::size_t i = 0; i < net.transitions().size(); ++i) { if (not transitions_bitset[i]) { dead_transitions.push_back(net.get_transition_by_index(i).id); } } if (not dead_transitions.empty()) { std::cout << dead_transitions.size() << " dead transition(s): "; std::copy( dead_transitions.cbegin(), std::prev(dead_transitions.cend()) , std::ostream_iterator<std::string>(std::cout, ",")); std::cout << *std::prev(dead_transitions.cend()) << std::endl; } else { std::cout << "No dead transitions" << std::endl; } } if (conf.compute_dead_states) { const auto dead = dead_states(conf, o, net, m); if (dead.empty()) { std::cout << "No dead states" << std::endl; } else { std::cout << sdd::count_combinations(dead).template convert_to<long double>() << " dead states" << std::endl; // Get the identifier of each level (SDD::paths() doesn't give this information). std::deque<const std::reference_wrapper<const std::string>> identifiers; o.flat(std::back_inserter(identifiers)); for (const auto& path : dead.paths()) { auto id_cit = identifiers.cbegin(); auto path_cit = path.cbegin(); for (; path_cit != std::prev(path.cend()); ++path_cit, ++id_cit) { std::cout << id_cit->get() << " : " << *path_cit << ", "; } std::cout << id_cit->get() << " : " << *path_cit << std::endl; } } } if (conf.export_to_lua) { std::ofstream lua_file(conf.export_to_lua_file); if (lua_file.is_open()) { lua_file << sdd::lua(m) << std::endl; } } if (conf.show_hash_tables_stats) { std::cout << manager << std::endl; } } catch (const bound_error& be) { std::cout << "Marking limit reached for place " << be.place << std::endl; } } /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::mc <commit_msg>Compile with GCC.<commit_after>#include <algorithm> // random_shuffle, transform #include <cassert> #include <chrono> #include <fstream> #include <iostream> #include <random> #include <set> #include <utility> // pair #include <sdd/sdd.hh> #include <sdd/dd/lua.hh> #include "mc/bound_error.hh" #include "mc/bounded_post.hh" #include "mc/dead.hh" #include "mc/live.hh" #include "mc/post.hh" #include "mc/pre.hh" #include "mc/work.hh" namespace pnmc { namespace mc { namespace chrono = std::chrono; typedef sdd::conf1 sdd_conf; typedef sdd::SDD<sdd_conf> SDD; typedef sdd::homomorphism<sdd_conf> homomorphism; using sdd::Composition; using sdd::Fixpoint; using sdd::Intersection; using sdd::Sum; using sdd::ValuesFunction; /*------------------------------------------------------------------------------------------------*/ struct mk_order_visitor : public boost::static_visitor<std::pair<std::string, sdd::order_builder<sdd_conf>>> { using order_identifier = sdd::order_identifier<sdd_conf>; using result_type = std::pair<order_identifier, sdd::order_builder<sdd_conf>>; using order_builder = sdd::order_builder<sdd_conf>; const conf::pnmc_configuration& conf; mutable unsigned int artificial_id_counter; mk_order_visitor(const conf::pnmc_configuration& c) : conf(c), artificial_id_counter(0) {} // Place: base case of the recursion, there's no more possible nested hierarchies. result_type operator()(const pn::place* p) const noexcept { return std::make_pair(order_identifier(p->id), order_builder()); } // Hierarchy. result_type operator()(const pn::module_node& m) const noexcept { assert(not m.nested.empty()); std::deque<result_type> tmp; for (const auto& h : m.nested) { const auto res = boost::apply_visitor(*this, *h); tmp.push_back(res); } std::size_t height = 0; for (const auto& p : tmp) { if (not p.second.empty()) { height += p.second.height(); } else { height += 1; // place } } order_builder ob; if (height <= conf.order_min_height) { order_identifier id; for (const auto& p : tmp) { if (not p.second.empty()) { ob = p.second << ob; } else // place { ob.push(p.first, p.second); } } return result_type(id, ob); } else { for (const auto& p : tmp) { ob.push(p.first, p.second); } } return std::make_pair(order_identifier(m.id) , ob); } }; /*------------------------------------------------------------------------------------------------*/ sdd::order<sdd_conf> mk_order(const conf::pnmc_configuration& conf, const pn::net& net) { if (not conf.order_force_flat and net.modules) { return sdd::order<sdd_conf>(boost::apply_visitor(mk_order_visitor(conf), *net.modules).second); } else { sdd::order_builder<sdd_conf> ob; if (conf.order_random) { std::vector<std::string> tmp; tmp.reserve(net.places().size()); std::transform( net.places().cbegin(), net.places().cend(), std::back_inserter(tmp) , [](const pn::place& p){return p.id;}); std::random_device rd; std::mt19937 g(rd()); std::shuffle(tmp.begin(), tmp.end(), g); for (const auto& id : tmp) { ob.push(id); } } else { for (const auto& place : net.places()) { ob.push(place.id); } } return sdd::order<sdd_conf>(ob); } } /*------------------------------------------------------------------------------------------------*/ SDD initial_state(const sdd::order<sdd_conf>& order, const pn::net& net) { return SDD(order, [&](const std::string& id) -> sdd::values::flat_set<unsigned int> { return {net.places_by_id().find(id)->marking}; }); } /*------------------------------------------------------------------------------------------------*/ homomorphism transition_relation( const conf::pnmc_configuration& conf, const sdd::order<sdd_conf>& o , const pn::net& net, boost::dynamic_bitset<>& transitions_bitset) { chrono::time_point<chrono::system_clock> start; chrono::time_point<chrono::system_clock> end; std::size_t elapsed; start = chrono::system_clock::now(); std::set<homomorphism> operands; operands.insert(sdd::Id<sdd_conf>()); for (const auto& transition : net.transitions()) { homomorphism h_t = sdd::Id<sdd_conf>(); // Add a "canary" to detect live transitions. if (conf.compute_dead_transitions) { if (not transition.post.empty()) { const auto f = ValuesFunction<sdd_conf>( o, transition.post.begin()->first , live(transition.index, transitions_bitset)); h_t = sdd::carrier(o, transition.post.begin()->first, f); } } // Post actions. for (const auto& arc : transition.post) { homomorphism f = conf.marking_bound == 0 ? ValuesFunction<sdd_conf>(o, arc.first, post(arc.second)) : ValuesFunction<sdd_conf>(o, arc.first, bounded_post( arc.second , conf.marking_bound , arc.first)); h_t = Composition(h_t, sdd::carrier(o, arc.first, f)); } // Pre actions. for (const auto& arc : transition.pre) { homomorphism f = ValuesFunction<sdd_conf>(o, arc.first, pre(arc.second)); h_t = Composition(h_t, sdd::carrier(o, arc.first, f)); } operands.insert(h_t); } end = chrono::system_clock::now(); elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "Transition relation time: " << elapsed << "s" << std::endl; } start = chrono::system_clock::now(); const auto res = sdd::rewrite(o, Fixpoint(Sum<sdd_conf>(o, operands.cbegin(), operands.cend()))); end = chrono::system_clock::now(); elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "Rewrite time: " << elapsed << "s" << std::endl; } return res; } /*------------------------------------------------------------------------------------------------*/ SDD state_space( const conf::pnmc_configuration& conf, const sdd::order<sdd_conf>& o, SDD m , homomorphism h) { chrono::time_point<chrono::system_clock> start = chrono::system_clock::now(); const auto res = h(o, m); chrono::time_point<chrono::system_clock> end = chrono::system_clock::now(); const std::size_t elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "State space computation time: " << elapsed << "s" << std::endl; } return res; } /*------------------------------------------------------------------------------------------------*/ SDD dead_states( const conf::pnmc_configuration& conf, const sdd::order<sdd_conf>& o, const pn::net& net , const SDD& state_space) { chrono::time_point<chrono::system_clock> start; chrono::time_point<chrono::system_clock> end; std::size_t elapsed; start = chrono::system_clock::now(); std::set<homomorphism> and_operands; std::set<homomorphism> or_operands; for (const auto& transition : net.transitions()) { // We are only interested in pre actions. for (const auto& arc : transition.pre) { const auto h = ValuesFunction<sdd_conf>(o, arc.first, dead(arc.second)); or_operands.insert(sdd::carrier(o, arc.first, h)); } and_operands.insert(Sum(o, or_operands.cbegin(), or_operands.cend())); or_operands.clear(); } const auto h = sdd::rewrite(o, Intersection(o, and_operands.cbegin(), and_operands.cend())); end = chrono::system_clock::now(); elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "Dead states relation time: " << elapsed << "s" << std::endl; } /* -------------------- */ start = chrono::system_clock::now(); const auto res = h(o, state_space); end = chrono::system_clock::now(); elapsed = chrono::duration_cast<chrono::seconds>(end-start).count(); if (conf.show_time) { std::cout << "Dead states computation time: " << elapsed << "s" << std::endl; } return res; } /*------------------------------------------------------------------------------------------------*/ void work(const conf::pnmc_configuration& conf, const pn::net& net) { auto manager = sdd::manager<sdd_conf>::init(); boost::dynamic_bitset<> transitions_bitset(net.transitions().size()); const sdd::order<sdd_conf>& o = mk_order(conf, net); assert(not o.empty() && "Empty order"); if (conf.order_show) { std::cout << o << std::endl; } const SDD m0 = initial_state(o, net); const homomorphism h = transition_relation(conf, o, net, transitions_bitset); if (conf.show_relation) { std::cout << h << std::endl; } try { SDD m = sdd::zero<sdd_conf>(); m = state_space(conf, o, m0, h); const auto n = sdd::count_combinations(m); std::cout << n.template convert_to<long double>() << " states" << std::endl; if (conf.compute_dead_transitions) { std::deque<std::string> dead_transitions; for (std::size_t i = 0; i < net.transitions().size(); ++i) { if (not transitions_bitset[i]) { dead_transitions.push_back(net.get_transition_by_index(i).id); } } if (not dead_transitions.empty()) { std::cout << dead_transitions.size() << " dead transition(s): "; std::copy( dead_transitions.cbegin(), std::prev(dead_transitions.cend()) , std::ostream_iterator<std::string>(std::cout, ",")); std::cout << *std::prev(dead_transitions.cend()) << std::endl; } else { std::cout << "No dead transitions" << std::endl; } } if (conf.compute_dead_states) { const auto dead = dead_states(conf, o, net, m); if (dead.empty()) { std::cout << "No dead states" << std::endl; } else { std::cout << sdd::count_combinations(dead).template convert_to<long double>() << " dead states" << std::endl; // Get the identifier of each level (SDD::paths() doesn't give this information). std::deque<std::reference_wrapper<const std::string>> identifiers; o.flat(std::back_inserter(identifiers)); for (const auto& path : dead.paths()) { auto id_cit = identifiers.cbegin(); auto path_cit = path.cbegin(); for (; path_cit != std::prev(path.cend()); ++path_cit, ++id_cit) { std::cout << id_cit->get() << " : " << *path_cit << ", "; } std::cout << id_cit->get() << " : " << *path_cit << std::endl; } } } if (conf.export_to_lua) { std::ofstream lua_file(conf.export_to_lua_file); if (lua_file.is_open()) { lua_file << sdd::lua(m) << std::endl; } } if (conf.show_hash_tables_stats) { std::cout << manager << std::endl; } } catch (const bound_error& be) { std::cout << "Marking limit reached for place " << be.place << std::endl; } } /*------------------------------------------------------------------------------------------------*/ }} // namespace pnmc::mc <|endoftext|>
<commit_before>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * 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 copyright holders 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. * * Authors: Ron Dreslinski * Ali Saidi */ /** * @file * Declaration of a bus object. */ #ifndef __MEM_BUS_HH__ #define __MEM_BUS_HH__ #include <string> #include <list> #include <inttypes.h> #include "base/range.hh" #include "mem/mem_object.hh" #include "mem/packet.hh" #include "mem/port.hh" #include "mem/request.hh" #include "sim/eventq.hh" class Bus : public MemObject { /** a globally unique id for this bus. */ int busId; /** the clock speed for the bus */ int clock; /** the width of the bus in bytes */ int width; /** the next tick at which the bus will be idle */ Tick tickNextIdle; static const int defaultId = -1; struct DevMap { int portId; Range<Addr> range; }; std::vector<DevMap> portList; AddrRangeList defaultRange; std::vector<DevMap> portSnoopList; /** Function called by the port when the bus is recieving a Timing transaction.*/ bool recvTiming(Packet *pkt); /** Function called by the port when the bus is recieving a Atomic transaction.*/ Tick recvAtomic(Packet *pkt); /** Function called by the port when the bus is recieving a Functional transaction.*/ void recvFunctional(Packet *pkt); /** Timing function called by port when it is once again able to process * requests. */ void recvRetry(int id); /** Function called by the port when the bus is recieving a status change.*/ void recvStatusChange(Port::Status status, int id); /** Find which port connected to this bus (if any) should be given a packet * with this address. * @param addr Address to find port for. * @param id Id of the port this packet was received from (to prevent * loops) * @return pointer to port that the packet should be sent out of. */ Port *findPort(Addr addr, int id); /** Find all ports with a matching snoop range, except src port. Keep in mind * that the ranges shouldn't overlap or you will get a double snoop to the same * interface.and the cache will assert out. * @param addr Address to find snoop prts for. * @param id Id of the src port of the request to avoid calling snoop on src * @return vector of IDs to snoop on */ std::vector<int> findSnoopPorts(Addr addr, int id); /** Snoop all relevant ports atomicly. */ Tick atomicSnoop(Packet *pkt); /** Snoop all relevant ports functionally. */ void functionalSnoop(Packet *pkt); /** Call snoop on caches, be sure to set SNOOP_COMMIT bit if you want * the snoop to happen * @return True if succeds. */ bool timingSnoop(Packet *pkt); /** Process address range request. * @param resp addresses that we can respond to * @param snoop addresses that we would like to snoop * @param id ide of the busport that made the request. */ void addressRanges(AddrRangeList &resp, AddrRangeList &snoop, int id); /** Occupy the bus with transmitting the packet pkt */ void occupyBus(PacketPtr pkt); /** Declaration of the buses port type, one will be instantiated for each of the interfaces connecting to the bus. */ class BusPort : public Port { bool _onRetryList; /** A pointer to the bus to which this port belongs. */ Bus *bus; /** A id to keep track of the intercafe ID this port is connected to. */ int id; public: /** Constructor for the BusPort.*/ BusPort(const std::string &_name, Bus *_bus, int _id) : Port(_name), _onRetryList(false), bus(_bus), id(_id) { } bool onRetryList() { return _onRetryList; } void onRetryList(bool newVal) { _onRetryList = newVal; } protected: /** When reciving a timing request from the peer port (at id), pass it to the bus. */ virtual bool recvTiming(Packet *pkt) { pkt->setSrc(id); return bus->recvTiming(pkt); } /** When reciving a Atomic requestfrom the peer port (at id), pass it to the bus. */ virtual Tick recvAtomic(Packet *pkt) { pkt->setSrc(id); return bus->recvAtomic(pkt); } /** When reciving a Functional requestfrom the peer port (at id), pass it to the bus. */ virtual void recvFunctional(Packet *pkt) { pkt->setSrc(id); bus->recvFunctional(pkt); } /** When reciving a status changefrom the peer port (at id), pass it to the bus. */ virtual void recvStatusChange(Status status) { bus->recvStatusChange(status, id); } /** When reciving a retry from the peer port (at id), pass it to the bus. */ virtual void recvRetry() { bus->recvRetry(id); } // This should return all the 'owned' addresses that are // downstream from this bus, yes? That is, the union of all // the 'owned' address ranges of all the other interfaces on // this bus... virtual void getDeviceAddressRanges(AddrRangeList &resp, AddrRangeList &snoop) { bus->addressRanges(resp, snoop, id); } // Hack to make translating port work without changes virtual int deviceBlockSize() { return 32; } }; class BusFreeEvent : public Event { Bus * bus; public: BusFreeEvent(Bus * _bus); void process(); const char *description(); }; BusFreeEvent busIdle; bool inRetry; /** An array of pointers to the peer port interfaces connected to this bus.*/ std::vector<BusPort*> interfaces; /** An array of pointers to ports that retry should be called on because the * original send failed for whatever reason.*/ std::list<BusPort*> retryList; void addToRetryList(BusPort * port) { if (!inRetry) { // The device wasn't retrying a packet, or wasn't at an appropriate // time. assert(!port->onRetryList()); port->onRetryList(true); retryList.push_back(port); } else { if (port->onRetryList()) { // The device was retrying a packet. It didn't work, so we'll leave // it at the head of the retry list. assert(port == retryList.front()); inRetry = false; } else { retryList.push_back(port); } } } /** Port that handles requests that don't match any of the interfaces.*/ Port *defaultPort; public: /** A function used to return the port associated with this bus object. */ virtual Port *getPort(const std::string &if_name, int idx = -1); virtual void init(); Bus(const std::string &n, int bus_id, int _clock, int _width) : MemObject(n), busId(bus_id), clock(_clock), width(_width), tickNextIdle(0), busIdle(this), inRetry(false), defaultPort(NULL) { //Both the width and clock period must be positive if (width <= 0) fatal("Bus width must be positive\n"); if (clock <= 0) fatal("Bus clock period must be positive\n"); } }; #endif //__MEM_BUS_HH__ <commit_msg>Forgot to mark myself as on the retry list<commit_after>/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * 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 copyright holders 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. * * Authors: Ron Dreslinski * Ali Saidi */ /** * @file * Declaration of a bus object. */ #ifndef __MEM_BUS_HH__ #define __MEM_BUS_HH__ #include <string> #include <list> #include <inttypes.h> #include "base/range.hh" #include "mem/mem_object.hh" #include "mem/packet.hh" #include "mem/port.hh" #include "mem/request.hh" #include "sim/eventq.hh" class Bus : public MemObject { /** a globally unique id for this bus. */ int busId; /** the clock speed for the bus */ int clock; /** the width of the bus in bytes */ int width; /** the next tick at which the bus will be idle */ Tick tickNextIdle; static const int defaultId = -1; struct DevMap { int portId; Range<Addr> range; }; std::vector<DevMap> portList; AddrRangeList defaultRange; std::vector<DevMap> portSnoopList; /** Function called by the port when the bus is recieving a Timing transaction.*/ bool recvTiming(Packet *pkt); /** Function called by the port when the bus is recieving a Atomic transaction.*/ Tick recvAtomic(Packet *pkt); /** Function called by the port when the bus is recieving a Functional transaction.*/ void recvFunctional(Packet *pkt); /** Timing function called by port when it is once again able to process * requests. */ void recvRetry(int id); /** Function called by the port when the bus is recieving a status change.*/ void recvStatusChange(Port::Status status, int id); /** Find which port connected to this bus (if any) should be given a packet * with this address. * @param addr Address to find port for. * @param id Id of the port this packet was received from (to prevent * loops) * @return pointer to port that the packet should be sent out of. */ Port *findPort(Addr addr, int id); /** Find all ports with a matching snoop range, except src port. Keep in mind * that the ranges shouldn't overlap or you will get a double snoop to the same * interface.and the cache will assert out. * @param addr Address to find snoop prts for. * @param id Id of the src port of the request to avoid calling snoop on src * @return vector of IDs to snoop on */ std::vector<int> findSnoopPorts(Addr addr, int id); /** Snoop all relevant ports atomicly. */ Tick atomicSnoop(Packet *pkt); /** Snoop all relevant ports functionally. */ void functionalSnoop(Packet *pkt); /** Call snoop on caches, be sure to set SNOOP_COMMIT bit if you want * the snoop to happen * @return True if succeds. */ bool timingSnoop(Packet *pkt); /** Process address range request. * @param resp addresses that we can respond to * @param snoop addresses that we would like to snoop * @param id ide of the busport that made the request. */ void addressRanges(AddrRangeList &resp, AddrRangeList &snoop, int id); /** Occupy the bus with transmitting the packet pkt */ void occupyBus(PacketPtr pkt); /** Declaration of the buses port type, one will be instantiated for each of the interfaces connecting to the bus. */ class BusPort : public Port { bool _onRetryList; /** A pointer to the bus to which this port belongs. */ Bus *bus; /** A id to keep track of the intercafe ID this port is connected to. */ int id; public: /** Constructor for the BusPort.*/ BusPort(const std::string &_name, Bus *_bus, int _id) : Port(_name), _onRetryList(false), bus(_bus), id(_id) { } bool onRetryList() { return _onRetryList; } void onRetryList(bool newVal) { _onRetryList = newVal; } protected: /** When reciving a timing request from the peer port (at id), pass it to the bus. */ virtual bool recvTiming(Packet *pkt) { pkt->setSrc(id); return bus->recvTiming(pkt); } /** When reciving a Atomic requestfrom the peer port (at id), pass it to the bus. */ virtual Tick recvAtomic(Packet *pkt) { pkt->setSrc(id); return bus->recvAtomic(pkt); } /** When reciving a Functional requestfrom the peer port (at id), pass it to the bus. */ virtual void recvFunctional(Packet *pkt) { pkt->setSrc(id); bus->recvFunctional(pkt); } /** When reciving a status changefrom the peer port (at id), pass it to the bus. */ virtual void recvStatusChange(Status status) { bus->recvStatusChange(status, id); } /** When reciving a retry from the peer port (at id), pass it to the bus. */ virtual void recvRetry() { bus->recvRetry(id); } // This should return all the 'owned' addresses that are // downstream from this bus, yes? That is, the union of all // the 'owned' address ranges of all the other interfaces on // this bus... virtual void getDeviceAddressRanges(AddrRangeList &resp, AddrRangeList &snoop) { bus->addressRanges(resp, snoop, id); } // Hack to make translating port work without changes virtual int deviceBlockSize() { return 32; } }; class BusFreeEvent : public Event { Bus * bus; public: BusFreeEvent(Bus * _bus); void process(); const char *description(); }; BusFreeEvent busIdle; bool inRetry; /** An array of pointers to the peer port interfaces connected to this bus.*/ std::vector<BusPort*> interfaces; /** An array of pointers to ports that retry should be called on because the * original send failed for whatever reason.*/ std::list<BusPort*> retryList; void addToRetryList(BusPort * port) { if (!inRetry) { // The device wasn't retrying a packet, or wasn't at an appropriate // time. assert(!port->onRetryList()); port->onRetryList(true); retryList.push_back(port); } else { if (port->onRetryList()) { // The device was retrying a packet. It didn't work, so we'll leave // it at the head of the retry list. assert(port == retryList.front()); inRetry = false; } else { port->onRetryList(true); retryList.push_back(port); } } } /** Port that handles requests that don't match any of the interfaces.*/ Port *defaultPort; public: /** A function used to return the port associated with this bus object. */ virtual Port *getPort(const std::string &if_name, int idx = -1); virtual void init(); Bus(const std::string &n, int bus_id, int _clock, int _width) : MemObject(n), busId(bus_id), clock(_clock), width(_width), tickNextIdle(0), busIdle(this), inRetry(false), defaultPort(NULL) { //Both the width and clock period must be positive if (width <= 0) fatal("Bus width must be positive\n"); if (clock <= 0) fatal("Bus clock period must be positive\n"); } }; #endif //__MEM_BUS_HH__ <|endoftext|>
<commit_before>//===------------------------ memory.cpp ----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #define _LIBCPP_BUILDING_MEMORY #include "memory" #ifndef _LIBCPP_HAS_NO_THREADS #include "mutex" #include "thread" #endif #include "include/atomic_support.h" _LIBCPP_BEGIN_NAMESPACE_STD const allocator_arg_t allocator_arg = allocator_arg_t(); bad_weak_ptr::~bad_weak_ptr() _NOEXCEPT {} const char* bad_weak_ptr::what() const _NOEXCEPT { return "bad_weak_ptr"; } __shared_count::~__shared_count() { } __shared_weak_count::~__shared_weak_count() { } #if defined(_LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS) void __shared_count::__add_shared() _NOEXCEPT { __libcpp_atomic_refcount_increment(__shared_owners_); } bool __shared_count::__release_shared() _NOEXCEPT { if (__libcpp_atomic_refcount_decrement(__shared_owners_) == -1) { __on_zero_shared(); return true; } return false; } void __shared_weak_count::__add_shared() _NOEXCEPT { __shared_count::__add_shared(); } void __shared_weak_count::__add_weak() _NOEXCEPT { __libcpp_atomic_refcount_increment(__shared_weak_owners_); } void __shared_weak_count::__release_shared() _NOEXCEPT { if (__shared_count::__release_shared()) __release_weak(); } #endif // _LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS void __shared_weak_count::__release_weak() _NOEXCEPT { // NOTE: The acquire load here is an optimization of the very // common case where a shared pointer is being destructed while // having no other contended references. // // BENEFIT: We avoid expensive atomic stores like XADD and STREX // in a common case. Those instructions are slow and do nasty // things to caches. // // IS THIS SAFE? Yes. During weak destruction, if we see that we // are the last reference, we know that no-one else is accessing // us. If someone were accessing us, then they would be doing so // while the last shared / weak_ptr was being destructed, and // that's undefined anyway. // // If we see anything other than a 0, then we have possible // contention, and need to use an atomicrmw primitive. // The same arguments don't apply for increment, where it is legal // (though inadvisable) to share shared_ptr references between // threads, and have them all get copied at once. The argument // also doesn't apply for __release_shared, because an outstanding // weak_ptr::lock() could read / modify the shared count. if (__libcpp_atomic_load(&__shared_weak_owners_, _AO_Acquire) == 0) { // no need to do this store, because we are about // to destroy everything. //__libcpp_atomic_store(&__shared_weak_owners_, -1, _AO_Release); __on_zero_shared_weak(); } else if (__libcpp_atomic_refcount_decrement(__shared_weak_owners_) == -1) __on_zero_shared_weak(); } __shared_weak_count* __shared_weak_count::lock() _NOEXCEPT { long object_owners = __libcpp_atomic_load(&__shared_owners_); while (object_owners != -1) { if (__libcpp_atomic_compare_exchange(&__shared_owners_, &object_owners, object_owners+1)) return this; } return nullptr; } #if !defined(_LIBCPP_NO_RTTI) || !defined(_LIBCPP_BUILD_STATIC) const void* __shared_weak_count::__get_deleter(const type_info&) const _NOEXCEPT { return nullptr; } #endif // _LIBCPP_NO_RTTI #if !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER) _LIBCPP_SAFE_STATIC static const std::size_t __sp_mut_count = 16; _LIBCPP_SAFE_STATIC static __libcpp_mutex_t mut_back[__sp_mut_count] = { _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER }; _LIBCPP_CONSTEXPR __sp_mut::__sp_mut(void* p) _NOEXCEPT : __lx(p) { } void __sp_mut::lock() _NOEXCEPT { auto m = static_cast<__libcpp_mutex_t*>(__lx); unsigned count = 0; while (__libcpp_mutex_trylock(m) != 0) { if (++count > 16) { __libcpp_mutex_lock(m); break; } this_thread::yield(); } } void __sp_mut::unlock() _NOEXCEPT { __libcpp_mutex_unlock(static_cast<__libcpp_mutex_t*>(__lx)); } __sp_mut& __get_sp_mut(const void* p) { static __sp_mut muts[__sp_mut_count] { &mut_back[ 0], &mut_back[ 1], &mut_back[ 2], &mut_back[ 3], &mut_back[ 4], &mut_back[ 5], &mut_back[ 6], &mut_back[ 7], &mut_back[ 8], &mut_back[ 9], &mut_back[10], &mut_back[11], &mut_back[12], &mut_back[13], &mut_back[14], &mut_back[15] }; return muts[hash<const void*>()(p) & (__sp_mut_count-1)]; } #endif // !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER) void declare_reachable(void*) { } void declare_no_pointers(char*, size_t) { } void undeclare_no_pointers(char*, size_t) { } #if !defined(_LIBCPP_ABI_POINTER_SAFETY_ENUM_TYPE) pointer_safety get_pointer_safety() _NOEXCEPT { return pointer_safety::relaxed; } #endif void* __undeclare_reachable(void* p) { return p; } void* align(size_t alignment, size_t size, void*& ptr, size_t& space) { void* r = nullptr; if (size <= space) { char* p1 = static_cast<char*>(ptr); char* p2 = reinterpret_cast<char*>(reinterpret_cast<size_t>(p1 + (alignment - 1)) & -alignment); size_t d = static_cast<size_t>(p2 - p1); if (d <= space - size) { r = p2; ptr = r; space -= d; } } return r; } _LIBCPP_END_NAMESPACE_STD <commit_msg>Fix incorrect usage of __libcpp_mutex_trylock. Patch from Andrey Khalyavin<commit_after>//===------------------------ memory.cpp ----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #define _LIBCPP_BUILDING_MEMORY #include "memory" #ifndef _LIBCPP_HAS_NO_THREADS #include "mutex" #include "thread" #endif #include "include/atomic_support.h" _LIBCPP_BEGIN_NAMESPACE_STD const allocator_arg_t allocator_arg = allocator_arg_t(); bad_weak_ptr::~bad_weak_ptr() _NOEXCEPT {} const char* bad_weak_ptr::what() const _NOEXCEPT { return "bad_weak_ptr"; } __shared_count::~__shared_count() { } __shared_weak_count::~__shared_weak_count() { } #if defined(_LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS) void __shared_count::__add_shared() _NOEXCEPT { __libcpp_atomic_refcount_increment(__shared_owners_); } bool __shared_count::__release_shared() _NOEXCEPT { if (__libcpp_atomic_refcount_decrement(__shared_owners_) == -1) { __on_zero_shared(); return true; } return false; } void __shared_weak_count::__add_shared() _NOEXCEPT { __shared_count::__add_shared(); } void __shared_weak_count::__add_weak() _NOEXCEPT { __libcpp_atomic_refcount_increment(__shared_weak_owners_); } void __shared_weak_count::__release_shared() _NOEXCEPT { if (__shared_count::__release_shared()) __release_weak(); } #endif // _LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS void __shared_weak_count::__release_weak() _NOEXCEPT { // NOTE: The acquire load here is an optimization of the very // common case where a shared pointer is being destructed while // having no other contended references. // // BENEFIT: We avoid expensive atomic stores like XADD and STREX // in a common case. Those instructions are slow and do nasty // things to caches. // // IS THIS SAFE? Yes. During weak destruction, if we see that we // are the last reference, we know that no-one else is accessing // us. If someone were accessing us, then they would be doing so // while the last shared / weak_ptr was being destructed, and // that's undefined anyway. // // If we see anything other than a 0, then we have possible // contention, and need to use an atomicrmw primitive. // The same arguments don't apply for increment, where it is legal // (though inadvisable) to share shared_ptr references between // threads, and have them all get copied at once. The argument // also doesn't apply for __release_shared, because an outstanding // weak_ptr::lock() could read / modify the shared count. if (__libcpp_atomic_load(&__shared_weak_owners_, _AO_Acquire) == 0) { // no need to do this store, because we are about // to destroy everything. //__libcpp_atomic_store(&__shared_weak_owners_, -1, _AO_Release); __on_zero_shared_weak(); } else if (__libcpp_atomic_refcount_decrement(__shared_weak_owners_) == -1) __on_zero_shared_weak(); } __shared_weak_count* __shared_weak_count::lock() _NOEXCEPT { long object_owners = __libcpp_atomic_load(&__shared_owners_); while (object_owners != -1) { if (__libcpp_atomic_compare_exchange(&__shared_owners_, &object_owners, object_owners+1)) return this; } return nullptr; } #if !defined(_LIBCPP_NO_RTTI) || !defined(_LIBCPP_BUILD_STATIC) const void* __shared_weak_count::__get_deleter(const type_info&) const _NOEXCEPT { return nullptr; } #endif // _LIBCPP_NO_RTTI #if !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER) _LIBCPP_SAFE_STATIC static const std::size_t __sp_mut_count = 16; _LIBCPP_SAFE_STATIC static __libcpp_mutex_t mut_back[__sp_mut_count] = { _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER, _LIBCPP_MUTEX_INITIALIZER }; _LIBCPP_CONSTEXPR __sp_mut::__sp_mut(void* p) _NOEXCEPT : __lx(p) { } void __sp_mut::lock() _NOEXCEPT { auto m = static_cast<__libcpp_mutex_t*>(__lx); unsigned count = 0; while (!__libcpp_mutex_trylock(m)) { if (++count > 16) { __libcpp_mutex_lock(m); break; } this_thread::yield(); } } void __sp_mut::unlock() _NOEXCEPT { __libcpp_mutex_unlock(static_cast<__libcpp_mutex_t*>(__lx)); } __sp_mut& __get_sp_mut(const void* p) { static __sp_mut muts[__sp_mut_count] { &mut_back[ 0], &mut_back[ 1], &mut_back[ 2], &mut_back[ 3], &mut_back[ 4], &mut_back[ 5], &mut_back[ 6], &mut_back[ 7], &mut_back[ 8], &mut_back[ 9], &mut_back[10], &mut_back[11], &mut_back[12], &mut_back[13], &mut_back[14], &mut_back[15] }; return muts[hash<const void*>()(p) & (__sp_mut_count-1)]; } #endif // !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER) void declare_reachable(void*) { } void declare_no_pointers(char*, size_t) { } void undeclare_no_pointers(char*, size_t) { } #if !defined(_LIBCPP_ABI_POINTER_SAFETY_ENUM_TYPE) pointer_safety get_pointer_safety() _NOEXCEPT { return pointer_safety::relaxed; } #endif void* __undeclare_reachable(void* p) { return p; } void* align(size_t alignment, size_t size, void*& ptr, size_t& space) { void* r = nullptr; if (size <= space) { char* p1 = static_cast<char*>(ptr); char* p2 = reinterpret_cast<char*>(reinterpret_cast<size_t>(p1 + (alignment - 1)) & -alignment); size_t d = static_cast<size_t>(p2 - p1); if (d <= space - size) { r = p2; ptr = r; space -= d; } } return r; } _LIBCPP_END_NAMESPACE_STD <|endoftext|>
<commit_before>/* * Mickey Scheme * * Copyright (C) 2011-2012 Christian Stigen Larsen <csl@sublevel3.org> * http://csl.sublevel3.org _ * \ * Distributed under the LGPL 2.1; see LICENSE /\ * Please post bugfixes and suggestions to the author. / \_ * */ #include <stdlib.h> #include <libgen.h> // dirname #include "mickey.h" #include "repl.h" #include "import.h" /* * Environment variables: */ #define MICKEY_LIB "MICKEY_LIB" void version(); void help(); void execute(const char* file) { TRY { environment_t *env = null_import_environment(); reset_for_programs(&global_opts, file); load(file, env); } CATCH (const exception_t& e) { const char* file = global_opts.current_filename; bool has_file = file && strcmp(file, "-"); /* * Finish any unfinished printing before * writing errors. */ fflush(stdout); fprintf(stderr, "\nError%s%s: %s\n\n", has_file? " in " : "", has_file? file : "", e.what()); backtrace(); backtrace_clear(); exit(1); } } void execute_string(const char* s) { TRY { environment_t *env = null_import_environment(); reset_for_programs(&global_opts, NULL); program_t *p = parse(s, env); p->root = cons(symbol("begin"), p->root); printf("%s\n", sprint(eval(p->root, env)).c_str()); } CATCH (const exception_t& e) { fprintf(stderr, "\nError: %s\n", e.what()); backtrace(); backtrace_clear(); exit(1); } } // return true if rest of parameters are files bool parse_option(const char* s, struct options_t* p) { #define ARGHIT(_short, _long) (!strcmp(s, _short) || !strcmp(s, _long)) if ( !strcmp(s, "--") ) { return true; } else if ( !strncmp(s, "-I", 2) && strlen(s) > 2 ) { p->include_path = s+2; } else if ( !strncmp(s, "-L", 2) && strlen(s) > 2 ) { p->lib_path.push_back(s+2); } else if ( !strcmp(s, "-") ) { // TODO: read from standard input } else if ( ARGHIT("-v", "--verbose") ) { p->verbose = true; } else if ( ARGHIT("-V", "--version") ) { version(); exit(0); } else if ( ARGHIT("-h", "--help") ) { help(); exit(0); } else if ( ARGHIT("-e", "--eval") ) { p->eval_next = true; } else if ( ARGHIT("-z", "--zero-env") ) { p->empty_repl_env = true; } else { fprintf(stderr, "Unknown option: %s\n\n", s); help(); exit(1); } return false; } void help() { printf("Usage: mickey [ option(s) ] [ file(s) | - ]\n" "\n" "Options:\n" " - Read program from standard input\n" " -- Rest of arguments are files, i.e. files can now begin with -\n" " -e --eval Execute expression and print result\n" " -h --help Print help\n" " -I<path> Set include path for (load)\n" " -L<path> Set location for library imports\n" " -V --version Print version\n" " -v --verbose Verbose operation\n" " -z --zero-env Start REPL with only (import) defined\n" "\n"); } void version() { printf("%s\n", VERSION); printf("Compiler version: %s\n", __VERSION__); } int main(int argc, char** argv) { bool rest_is_files = false; // used with option `--` bool run_repl = true; set_default(&global_opts, argc, argv); /* * If there was no -L<path> option, set library path using either * environment variable or current working directory. */ if ( global_opts.lib_path.empty() ) { if ( getenv(MICKEY_LIB) ) add_lib_path(&global_opts, getenv(MICKEY_LIB)); else { const char* s = strdup(format("%s/lib/", global_opts.mickey_absolute_path).c_str()); add_lib_path(&global_opts,s); global_opts.mickey_absolute_lib_path = s; } } std::vector<std::string> files; for ( int n=1; n<argc; ++n ) { if ( global_opts.eval_next ) { execute_string(argv[n]); global_opts.eval_next = false; run_repl = false; } else if ( !rest_is_files && argv[n][0] == '-' ) { if ( argv[n][1] == '\0' ) files.push_back("-"); // stdin else rest_is_files |= parse_option(argv[n], &global_opts); } else files.push_back(argv[n]); } scan_for_library_files(); if ( !files.empty() ) { for ( size_t n=0; n<files.size(); ++n ) execute(files[n].c_str()); } else repl(); return 0; } <commit_msg>Removed unused variable<commit_after>/* * Mickey Scheme * * Copyright (C) 2011-2012 Christian Stigen Larsen <csl@sublevel3.org> * http://csl.sublevel3.org _ * \ * Distributed under the LGPL 2.1; see LICENSE /\ * Please post bugfixes and suggestions to the author. / \_ * */ #include <stdlib.h> #include <libgen.h> // dirname #include "mickey.h" #include "repl.h" #include "import.h" /* * Environment variables: */ #define MICKEY_LIB "MICKEY_LIB" void version(); void help(); void execute(const char* file) { TRY { environment_t *env = null_import_environment(); reset_for_programs(&global_opts, file); load(file, env); } CATCH (const exception_t& e) { const char* file = global_opts.current_filename; bool has_file = file && strcmp(file, "-"); /* * Finish any unfinished printing before * writing errors. */ fflush(stdout); fprintf(stderr, "\nError%s%s: %s\n\n", has_file? " in " : "", has_file? file : "", e.what()); backtrace(); backtrace_clear(); exit(1); } } void execute_string(const char* s) { TRY { environment_t *env = null_import_environment(); reset_for_programs(&global_opts, NULL); program_t *p = parse(s, env); p->root = cons(symbol("begin"), p->root); printf("%s\n", sprint(eval(p->root, env)).c_str()); } CATCH (const exception_t& e) { fprintf(stderr, "\nError: %s\n", e.what()); backtrace(); backtrace_clear(); exit(1); } } // return true if rest of parameters are files bool parse_option(const char* s, struct options_t* p) { #define ARGHIT(_short, _long) (!strcmp(s, _short) || !strcmp(s, _long)) if ( !strcmp(s, "--") ) { return true; } else if ( !strncmp(s, "-I", 2) && strlen(s) > 2 ) { p->include_path = s+2; } else if ( !strncmp(s, "-L", 2) && strlen(s) > 2 ) { p->lib_path.push_back(s+2); } else if ( !strcmp(s, "-") ) { // TODO: read from standard input } else if ( ARGHIT("-v", "--verbose") ) { p->verbose = true; } else if ( ARGHIT("-V", "--version") ) { version(); exit(0); } else if ( ARGHIT("-h", "--help") ) { help(); exit(0); } else if ( ARGHIT("-e", "--eval") ) { p->eval_next = true; } else if ( ARGHIT("-z", "--zero-env") ) { p->empty_repl_env = true; } else { fprintf(stderr, "Unknown option: %s\n\n", s); help(); exit(1); } return false; } void help() { printf("Usage: mickey [ option(s) ] [ file(s) | - ]\n" "\n" "Options:\n" " - Read program from standard input\n" " -- Rest of arguments are files, i.e. files can now begin with -\n" " -e --eval Execute expression and print result\n" " -h --help Print help\n" " -I<path> Set include path for (load)\n" " -L<path> Set location for library imports\n" " -V --version Print version\n" " -v --verbose Verbose operation\n" " -z --zero-env Start REPL with only (import) defined\n" "\n"); } void version() { printf("%s\n", VERSION); printf("Compiler version: %s\n", __VERSION__); } int main(int argc, char** argv) { bool rest_is_files = false; // used with option `--` set_default(&global_opts, argc, argv); /* * If there was no -L<path> option, set library path using either * environment variable or current working directory. */ if ( global_opts.lib_path.empty() ) { if ( getenv(MICKEY_LIB) ) add_lib_path(&global_opts, getenv(MICKEY_LIB)); else { const char* s = strdup(format("%s/lib/", global_opts.mickey_absolute_path).c_str()); add_lib_path(&global_opts,s); global_opts.mickey_absolute_lib_path = s; } } std::vector<std::string> files; for ( int n=1; n<argc; ++n ) { if ( global_opts.eval_next ) { execute_string(argv[n]); global_opts.eval_next = false; } else if ( !rest_is_files && argv[n][0] == '-' ) { if ( argv[n][1] == '\0' ) files.push_back("-"); // stdin else rest_is_files |= parse_option(argv[n], &global_opts); } else files.push_back(argv[n]); } scan_for_library_files(); if ( !files.empty() ) { for ( size_t n=0; n<files.size(); ++n ) execute(files[n].c_str()); } else repl(); return 0; } <|endoftext|>
<commit_before>#include "box.hpp" #include <utility> #include <stdexcept> #include <iostream> #include <cassert> #include <array> #include <glm/gtx/io.hpp> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/component_wise.hpp> namespace mo { Box::Box(){ } Box::Box(const glm::vec3 & min, const glm::vec3 & max, const glm::mat4 & transform, const float obstruction) : transform_(transform), min_(min), max_(max), obstruction_(obstruction) { if(glm::all(glm::lessThan(max_, min_))){ throw std::invalid_argument("Min must be less than max."); } } glm::vec3 Box::min() const { return (glm::vec3)(transform() * glm::vec4(min_, 1.0f)); } glm::vec3 Box::max() const { return (glm::vec3)(transform() * glm::vec4(max_, 1.0f)); } RayIntersection Box::intersect(const glm::vec3 & origin, const glm::vec3 direction, float t1, float t2) { // Intersection method from Real-Time Rendering and Essential Mathematics for Games glm::mat4 model_matrix = transform(); glm::vec3 ray_origin = origin; glm::vec3 ray_direction = direction; glm::vec3 aabb_min = min_; glm::vec3 aabb_max = max_; float t_min = 0.0f; float t_max = 100000.0f; const float limit = 0.001f; //glm::vec3 position_worldspace(model_matrix[3].x, model_matrix[3].y, model_matrix[3].z); glm::vec3 position_worldspace = (glm::vec3)(transform()*glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)); glm::vec3 delta = position_worldspace - ray_origin; // Test intersection with the 2 planes perpendicular to the OBB's X axis { glm::vec3 xaxis(model_matrix[0].x, model_matrix[0].y, model_matrix[0].z); float e = glm::dot(xaxis, delta); float f = glm::dot(ray_direction, xaxis); if ( fabs(f) > limit ){ // Standard case float t1 = (e+aabb_min.x)/f; // Intersection with the "left" plane float t2 = (e+aabb_max.x)/f; // Intersection with the "right" plane // t1 and t2 now contain distances betwen ray origin and ray-plane intersections // We want t1 to represent the nearest intersection, // so if it's not the case, invert t1 and t2 if (t1>t2){ float w=t1;t1=t2;t2=w; // swap t1 and t2 } // tMax is the nearest "far" intersection (amongst the X,Y and Z planes pairs) if ( t2 < t_max ){ t_max = t2; } // tMin is the farthest "near" intersection (amongst the X,Y and Z planes pairs) if ( t1 > t_min ){ t_min = t1; } // And here's the trick : // If "far" is closer than "near", then there is NO intersection. // See the images in the tutorials for the visual explanation. if (t_max < t_min ){ return RayIntersection(false, 0.0f); } }else{ // Rare case : the ray is almost parallel to the planes, so they don't have any "intersection" if(-e+aabb_min.x > 0.0f || -e+aabb_max.x < 0.0f){ return RayIntersection(false, 0.0f); } } } // Test intersection with the 2 planes perpendicular to the OBB's Y axis // Exactly the same thing than above. { glm::vec3 yaxis(model_matrix[1].x, model_matrix[1].y, model_matrix[1].z); float e = glm::dot(yaxis, delta); float f = glm::dot(ray_direction, yaxis); if ( fabs(f) > limit ){ float t1 = (e+aabb_min.y)/f; float t2 = (e+aabb_max.y)/f; if (t1>t2){ float w=t1;t1=t2;t2=w; } if ( t2 < t_max ){ t_max = t2; } if ( t1 > t_min ){ t_min = t1; } if (t_min > t_max){ return RayIntersection(false, 0.0f); } }else{ if(-e+aabb_min.y > 0.0f || -e+aabb_max.y < 0.0f){ return RayIntersection(false, 0.0f); } } } // Test intersection with the 2 planes perpendicular to the OBB's Z axis // Exactly the same thing than above. { glm::vec3 zaxis(model_matrix[2].x, model_matrix[2].y, model_matrix[2].z); float e = glm::dot(zaxis, delta); float f = glm::dot(ray_direction, zaxis); if ( fabs(f) > limit ){ float t1 = (e+aabb_min.z)/f; float t2 = (e+aabb_max.z)/f; if (t1>t2){ float w=t1;t1=t2;t2=w; } if ( t2 < t_max ){ t_max = t2; } if ( t1 > t_min ){ t_min = t1; } if (t_min > t_max){ return RayIntersection(false, 0.0f); } }else{ if(-e+aabb_min.z > 0.0f || -e+aabb_max.z < 0.0f) return RayIntersection(false, 0.0f); } } float intersection_distance = t_min; return RayIntersection(true, intersection_distance); } RayIntersection Box::intersect(glm::vec3 point1, glm::vec3 point2) { return intersect(point1, glm::normalize(point2 - point1), 0.0f, glm::distance(point1, point2)); } BoxIntersection Box::intersects(const Box &other) { static const std::array<glm::vec3, 6> faces = { glm::vec3(-1, 0, 0), // 'left' face normal (-x direction) glm::vec3( 1, 0, 0), // 'right' face normal (+x direction) glm::vec3( 0,-1, 0), // 'bottom' face normal (-y direction) glm::vec3( 0, 1, 0), // 'top' face normal (+y direction) glm::vec3( 0, 0,-1), // 'far' face normal (-z direction) glm::vec3( 0, 0, 1), // 'near' face normal (+x direction) }; glm::vec3 maxa = this->max(); glm::vec3 mina = this->min(); if (maxa.x < mina.x){std::swap(maxa.x, mina.x);} if (maxa.y < mina.y){std::swap(maxa.y, mina.y);} if (maxa.z < mina.z){std::swap(maxa.z, mina.z);} glm::vec3 maxb = other.max(); glm::vec3 minb = other.min(); if (maxb.x < minb.x){std::swap(maxb.x, minb.x);} if (maxb.y < minb.y){std::swap(maxb.y, minb.y);} if (maxb.z < minb.z){std::swap(maxb.z, minb.z);} std::array<float, 6> distances = { (maxb.x - mina.x), // distance of box 'b' to face on 'left' side of 'a'. (maxa.x - minb.x), // distance of box 'b' to face on 'right' side of 'a'. (maxb.y - mina.y), // distance of box 'b' to face on 'bottom' side of 'a'. (maxa.y - minb.y), // distance of box 'b' to face on 'top' side of 'a'. (maxb.z - mina.z), // distance of box 'b' to face on 'far' side of 'a'. (maxa.z - minb.z), // distance of box 'b' to face on 'near' side of 'a'. }; glm::vec3 normal(0.0f); float distance = 0.0f; for(int i = 0; i < 6; i ++) { // box does not intersect face. So boxes don't intersect at all. if(distances[i] < 0.0f){ return BoxIntersection{false, glm::vec3(0.0f), distance}; } // face of least intersection depth. That's our candidate. if((i == 0) || (distances[i] < distance)) { //fcoll = i; normal = faces[i]; distance = distances[i]; } } return BoxIntersection{true, normal, distance}; } glm::mat4 Box::transform() const { return transform_; } void Box::transform(const glm::mat4 &transform) { glm::vec3 position; position.x = transform[3][0]; position.y = transform[3][1]; position.z = transform[3][2]; transform_ = glm::translate(glm::mat4(1.0f), position); } float Box::volume() const { return glm::abs(glm::compMul(max() - min())); } float Box::obstruction() const { return obstruction_; } glm::vec3 Box::size() const { return glm::vec3(glm::abs(max_.x-min_.x), glm::abs(max_.y-min_.y), glm::abs(max_.z-min_.z)); } } <commit_msg>Comment.<commit_after>#include "box.hpp" #include <utility> #include <stdexcept> #include <iostream> #include <cassert> #include <array> #include <glm/gtx/io.hpp> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/component_wise.hpp> namespace mo { Box::Box(){ } Box::Box(const glm::vec3 & min, const glm::vec3 & max, const glm::mat4 & transform, const float obstruction) : transform_(transform), min_(min), max_(max), obstruction_(obstruction) { if(glm::all(glm::lessThan(max_, min_))){ throw std::invalid_argument("Min must be less than max."); } } glm::vec3 Box::min() const { return (glm::vec3)(transform() * glm::vec4(min_, 1.0f)); } glm::vec3 Box::max() const { return (glm::vec3)(transform() * glm::vec4(max_, 1.0f)); } RayIntersection Box::intersect(const glm::vec3 & origin, const glm::vec3 direction, float t1, float t2) { // Intersection method from Real-Time Rendering and Essential Mathematics for Games glm::mat4 model_matrix = transform(); glm::vec3 ray_origin = origin; glm::vec3 ray_direction = direction; glm::vec3 aabb_min = min_; glm::vec3 aabb_max = max_; float t_min = 0.0f; float t_max = 100000.0f; const float limit = 0.001f; //glm::vec3 position_worldspace(model_matrix[3].x, model_matrix[3].y, model_matrix[3].z); glm::vec3 position_worldspace = (glm::vec3)(transform()*glm::vec4(0.0f, 0.0f, 0.0f, 1.0f)); glm::vec3 delta = position_worldspace - ray_origin; // Test intersection with the 2 planes perpendicular to the OBB's X axis { glm::vec3 xaxis(model_matrix[0].x, model_matrix[0].y, model_matrix[0].z); float e = glm::dot(xaxis, delta); float f = glm::dot(ray_direction, xaxis); if ( fabs(f) > limit ){ // Standard case float t1 = (e+aabb_min.x)/f; // Intersection with the "left" plane float t2 = (e+aabb_max.x)/f; // Intersection with the "right" plane // t1 and t2 now contain distances betwen ray origin and ray-plane intersections // We want t1 to represent the nearest intersection, // so if it's not the case, invert t1 and t2 if (t1>t2){ float w=t1;t1=t2;t2=w; // swap t1 and t2 } // tMax is the nearest "far" intersection (amongst the X,Y and Z planes pairs) if ( t2 < t_max ){ t_max = t2; } // tMin is the farthest "near" intersection (amongst the X,Y and Z planes pairs) if ( t1 > t_min ){ t_min = t1; } // And here's the trick : // If "far" is closer than "near", then there is NO intersection. // See the images in the tutorials for the visual explanation. if (t_max < t_min ){ return RayIntersection(false, 0.0f); } }else{ // Rare case : the ray is almost parallel to the planes, so they don't have any "intersection" if(-e+aabb_min.x > 0.0f || -e+aabb_max.x < 0.0f){ return RayIntersection(false, 0.0f); } } } // Test intersection with the 2 planes perpendicular to the OBB's Y axis // Exactly the same thing than above. { glm::vec3 yaxis(model_matrix[1].x, model_matrix[1].y, model_matrix[1].z); float e = glm::dot(yaxis, delta); float f = glm::dot(ray_direction, yaxis); if ( fabs(f) > limit ){ float t1 = (e+aabb_min.y)/f; float t2 = (e+aabb_max.y)/f; if (t1>t2){ float w=t1;t1=t2;t2=w; } if ( t2 < t_max ){ t_max = t2; } if ( t1 > t_min ){ t_min = t1; } if (t_min > t_max){ return RayIntersection(false, 0.0f); } }else{ if(-e+aabb_min.y > 0.0f || -e+aabb_max.y < 0.0f){ return RayIntersection(false, 0.0f); } } } // Test intersection with the 2 planes perpendicular to the OBB's Z axis // Exactly the same thing than above. { glm::vec3 zaxis(model_matrix[2].x, model_matrix[2].y, model_matrix[2].z); float e = glm::dot(zaxis, delta); float f = glm::dot(ray_direction, zaxis); if ( fabs(f) > limit ){ float t1 = (e+aabb_min.z)/f; float t2 = (e+aabb_max.z)/f; if (t1>t2){ float w=t1;t1=t2;t2=w; } if ( t2 < t_max ){ t_max = t2; } if ( t1 > t_min ){ t_min = t1; } if (t_min > t_max){ return RayIntersection(false, 0.0f); } }else{ if(-e+aabb_min.z > 0.0f || -e+aabb_max.z < 0.0f) return RayIntersection(false, 0.0f); } } float intersection_distance = t_min; return RayIntersection(true, intersection_distance); } RayIntersection Box::intersect(glm::vec3 point1, glm::vec3 point2) { return intersect(point1, glm::normalize(point2 - point1), 0.0f, glm::distance(point1, point2)); } BoxIntersection Box::intersects(const Box &other) { static const std::array<glm::vec3, 6> faces = { glm::vec3(-1, 0, 0), // 'left' face normal (-x direction) glm::vec3( 1, 0, 0), // 'right' face normal (+x direction) glm::vec3( 0,-1, 0), // 'bottom' face normal (-y direction) glm::vec3( 0, 1, 0), // 'top' face normal (+y direction) glm::vec3( 0, 0,-1), // 'far' face normal (-z direction) glm::vec3( 0, 0, 1), // 'near' face normal (+x direction) }; glm::vec3 maxa = this->max(); glm::vec3 mina = this->min(); //TODO: This swapping is kind of nasty. Look throgh the whol BB thing. if (maxa.x < mina.x){std::swap(maxa.x, mina.x);} if (maxa.y < mina.y){std::swap(maxa.y, mina.y);} if (maxa.z < mina.z){std::swap(maxa.z, mina.z);} glm::vec3 maxb = other.max(); glm::vec3 minb = other.min(); if (maxb.x < minb.x){std::swap(maxb.x, minb.x);} if (maxb.y < minb.y){std::swap(maxb.y, minb.y);} if (maxb.z < minb.z){std::swap(maxb.z, minb.z);} std::array<float, 6> distances = { (maxb.x - mina.x), // distance of box 'b' to face on 'left' side of 'a'. (maxa.x - minb.x), // distance of box 'b' to face on 'right' side of 'a'. (maxb.y - mina.y), // distance of box 'b' to face on 'bottom' side of 'a'. (maxa.y - minb.y), // distance of box 'b' to face on 'top' side of 'a'. (maxb.z - mina.z), // distance of box 'b' to face on 'far' side of 'a'. (maxa.z - minb.z), // distance of box 'b' to face on 'near' side of 'a'. }; glm::vec3 normal(0.0f); float distance = 0.0f; for(int i = 0; i < 6; i ++) { // box does not intersect face. So boxes don't intersect at all. if(distances[i] < 0.0f){ return BoxIntersection{false, glm::vec3(0.0f), distance}; } // face of least intersection depth. That's our candidate. if((i == 0) || (distances[i] < distance)) { //fcoll = i; normal = faces[i]; distance = distances[i]; } } return BoxIntersection{true, normal, distance}; } glm::mat4 Box::transform() const { return transform_; } void Box::transform(const glm::mat4 &transform) { glm::vec3 position; position.x = transform[3][0]; position.y = transform[3][1]; position.z = transform[3][2]; transform_ = glm::translate(glm::mat4(1.0f), position); } float Box::volume() const { return glm::abs(glm::compMul(max() - min())); } float Box::obstruction() const { return obstruction_; } glm::vec3 Box::size() const { return glm::vec3(glm::abs(max_.x-min_.x), glm::abs(max_.y-min_.y), glm::abs(max_.z-min_.z)); } } <|endoftext|>
<commit_before>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "of_html.hh" #include "coverage.hh" #include "helper.hh" #include "model.hh" #include <map> std::string OutputFormat_Html::header() { std::string script( "<SCRIPT LANGUAGE=\"JavaScript\">\n" "<!--\n" "function showHide(elementid){\n" "if (document.getElementById(elementid).style.display == 'none'){\n" "document.getElementById(elementid).style.display = '';\n" "} else {\n" "document.getElementById(elementid).style.display = 'none';\n" "}\n" "} \n" "//-->\n" "</SCRIPT>\n"); std::string ret("<html><header>"+script+"</header>"); ret+="<body>"; ret+="<table border=\"1\">\n<tr><th>UC</th>\n<th>verdict</th>\n"; for(unsigned i=0;i<covnames.size();i++) { ret=ret+"<th>"+covnames[i]+"</th>\n"; } ret=ret+"</tr>\n"; return ret; } std::string OutputFormat_Html::footer() { return "</table>"; } std::string OutputFormat_Html::format_covs() { std::string ret("<tr>\n"); //testname ret=ret+"<td>"+testnames.back()+"</td>"; //verdict ret=ret+"<td></td>\n"; for(unsigned i=0;i<covnames.size();i++) { ret=ret+"<td>"+to_string(covs[i]->getCoverage())+ "</td>\n"; } return ret+"</tr>\n"; } /* We might want to have more than one comparator for different orders */ bool vcmp (const std::vector<int>& lhs, const std::vector<int>& rhs) { if (lhs.size()==rhs.size()) { return lhs<rhs; } return lhs.size()<rhs.size(); } std::string OutputFormat_Html::report() { std::string ret("<table border=\"2\"><tr><th>Name</th><th>trace</th></tr>\n"); std::vector<std::string>& an(model->getActionNames()); for(unsigned i=0;i<reportnames.size();i++) { bool(*cmprp)(const std::vector<int>&, const std::vector<int>&) = vcmp; std::vector<std::vector<int> >& traces(rcovs[i]->traces); std::map<std::vector<int> , int, bool(*)(const std::vector<int>&,const std::vector<int>&) > cnt(cmprp); for(unsigned j=0;j<traces.size();j++) { cnt[traces[j]]++; } ret=ret+"<tr><td><a href=\"javascript:showHide('"+reportnames[i]+"')\"><table><tr><td>" + reportnames[i]+"</td></tr><tr><td>Number of executed tests:"+to_string((unsigned)traces.size())+"</td></tr><tr><td>unique tests:"+to_string(unsigned(cnt.size()))+"</td></tr></table></a></td>"; ret=ret+"<td>\n<div id=\""+reportnames[i]+"\">\n"+ "<table border=\"4\">"; printf("reportnames %s\n",reportnames[i].c_str()); printf("vector size %i\n",(int)traces.size()); printf("Unique traces %i\n",cnt.size()); for(std::map<std::vector<int>,int>::iterator j=cnt.begin(); j!=cnt.end();j++) { ret=ret+"<td valign=\"top\">\n" "<table border=\"0\">\n" "<caption>Count:"+to_string((unsigned)j->second)+"</caption><td>"; ret=ret+"\n<ol>\n"; const std::vector<int>& t(j->first); for(unsigned k=0; k<t.size();k++) { ret=ret+"<li>"+an[t[k]]; } ret=ret+"</ol>\n"; ret=ret+"</td></tr></table></td>"; } /* for(unsigned j=0;j<traces.size();j++) { ret=ret+"<td>"; ret=ret+"\n<ol>\n"; std::vector<int>& t(traces[j]); for(unsigned k=0; k<t.size();k++) { ret=ret+"<li>"+an[t[k]]; } ret=ret+"</ol>\n"; ret=ret+"</td>"; } */ ret=ret+"</table>\n" "</div>\n</tr>"; } ret=ret+"</table>"; return ret; } FACTORY_DEFAULT_CREATOR(OutputFormat, OutputFormat_Html, "html") <commit_msg>warnings...<commit_after>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "of_html.hh" #include "coverage.hh" #include "helper.hh" #include "model.hh" #include <map> std::string OutputFormat_Html::header() { std::string script( "<SCRIPT LANGUAGE=\"JavaScript\">\n" "<!--\n" "function showHide(elementid){\n" "if (document.getElementById(elementid).style.display == 'none'){\n" "document.getElementById(elementid).style.display = '';\n" "} else {\n" "document.getElementById(elementid).style.display = 'none';\n" "}\n" "} \n" "//-->\n" "</SCRIPT>\n"); std::string ret("<html><header>"+script+"</header>"); ret+="<body>"; ret+="<table border=\"1\">\n<tr><th>UC</th>\n<th>verdict</th>\n"; for(unsigned i=0;i<covnames.size();i++) { ret=ret+"<th>"+covnames[i]+"</th>\n"; } ret=ret+"</tr>\n"; return ret; } std::string OutputFormat_Html::footer() { return "</table>"; } std::string OutputFormat_Html::format_covs() { std::string ret("<tr>\n"); //testname ret=ret+"<td>"+testnames.back()+"</td>"; //verdict ret=ret+"<td></td>\n"; for(unsigned i=0;i<covnames.size();i++) { ret=ret+"<td>"+to_string(covs[i]->getCoverage())+ "</td>\n"; } return ret+"</tr>\n"; } /* We might want to have more than one comparator for different orders */ bool vcmp (const std::vector<int>& lhs, const std::vector<int>& rhs) { if (lhs.size()==rhs.size()) { return lhs<rhs; } return lhs.size()<rhs.size(); } std::string OutputFormat_Html::report() { std::string ret("<table border=\"2\"><tr><th>Name</th><th>trace</th></tr>\n"); std::vector<std::string>& an(model->getActionNames()); for(unsigned i=0;i<reportnames.size();i++) { bool(*cmprp)(const std::vector<int>&, const std::vector<int>&) = vcmp; std::vector<std::vector<int> >& traces(rcovs[i]->traces); std::map<std::vector<int> , int, bool(*)(const std::vector<int>&,const std::vector<int>&) > cnt(cmprp); for(unsigned j=0;j<traces.size();j++) { cnt[traces[j]]++; } ret=ret+"<tr><td><a href=\"javascript:showHide('"+reportnames[i]+"')\"><table><tr><td>" + reportnames[i]+"</td></tr><tr><td>Number of executed tests:"+to_string((unsigned)traces.size())+"</td></tr><tr><td>unique tests:"+to_string(unsigned(cnt.size()))+"</td></tr></table></a></td>"; ret=ret+"<td>\n<div id=\""+reportnames[i]+"\">\n"+ "<table border=\"4\">"; printf("reportnames %s\n",reportnames[i].c_str()); printf("vector size %i\n",(int)traces.size()); printf("Unique traces %i\n",(int)cnt.size()); for(std::map<std::vector<int>,int>::iterator j=cnt.begin(); j!=cnt.end();j++) { ret=ret+"<td valign=\"top\">\n" "<table border=\"0\">\n" "<caption>Count:"+to_string((unsigned)j->second)+"</caption><td>"; ret=ret+"\n<ol>\n"; const std::vector<int>& t(j->first); for(unsigned k=0; k<t.size();k++) { ret=ret+"<li>"+an[t[k]]; } ret=ret+"</ol>\n"; ret=ret+"</td></tr></table></td>"; } /* for(unsigned j=0;j<traces.size();j++) { ret=ret+"<td>"; ret=ret+"\n<ol>\n"; std::vector<int>& t(traces[j]); for(unsigned k=0; k<t.size();k++) { ret=ret+"<li>"+an[t[k]]; } ret=ret+"</ol>\n"; ret=ret+"</td>"; } */ ret=ret+"</table>\n" "</div>\n</tr>"; } ret=ret+"</table>"; return ret; } FACTORY_DEFAULT_CREATOR(OutputFormat, OutputFormat_Html, "html") <|endoftext|>
<commit_before>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "of_html.hh" #include "coverage.hh" #include "helper.hh" #include "model.hh" #include <map> #include <sstream> std::string OutputFormat_Html::header() { std::string script( "<SCRIPT LANGUAGE=\"JavaScript\">\n" "<!--\n" "function showHide(elementid){\n" "if (document.getElementById(elementid).style.display == 'none'){\n" "document.getElementById(elementid).style.display = '';\n" "} else {\n" "document.getElementById(elementid).style.display = 'none';\n" "}\n" "} \n" "//-->\n" "</SCRIPT>\n"); std::string ret("<html><header>"+script+"</header>"); ret+="<body>"; ret+="<table border=\"1\">\n<tr><th>UC</th>\n<th>verdict</th>\n"; for(unsigned i=0;i<covnames.size();i++) { ret=ret+"<th>"+covnames[i]+"</th>\n"; } ret=ret+"</tr>\n"; return ret; } std::string OutputFormat_Html::footer() { return "</table>"; } std::string OutputFormat_Html::format_covs() { std::string ret("<tr>\n"); //testname ret=ret+"<td>"+testnames.back()+"</td>"; //verdict ret=ret+"<td>"+test_verdict+"</td>\n"; for(unsigned i=0;i<covnames.size();i++) { ret=ret+"<td>"+to_string(covs[i]->getCoverage())+ "</td>\n"; } return ret+"</tr>\n"; } /* We might want to have more than one comparator for different orders */ bool vcmp (const std::vector<std::pair<int,std::vector<int> > >& lhs, const std::vector<std::pair<int,std::vector<int> > >& rhs) { if (lhs.size()==rhs.size()) { return lhs<rhs; } return lhs.size()<rhs.size(); } std::string OutputFormat_Html::report() { std::ostringstream html; html << "<table border=\"2\">" << "<tr><th>Name</th><th>trace</th></tr>\n"; std::vector<std::string>& an(model->getActionNames()); for(unsigned i=0;i<reportnames.size();i++) { bool(*cmprp)(const std::vector<std::pair<int,std::vector<int> > >&, const std::vector<std::pair<int,std::vector<int> > >&) = vcmp; std::vector<std::vector<std::pair<int,std::vector<int> > > >& traces(rcovs[i]->traces); std::map<std::vector<std::pair<int,std::vector<int> > > , int, bool(*)(const std::vector<std::pair<int,std::vector<int> > >&,const std::vector<std::pair<int,std::vector<int> > >&) > cnt(cmprp); for(unsigned j=0;j<traces.size();j++) { cnt[traces[j]]++; } struct timeval time_tmp; struct timeval time_consumed={0,0}; for(unsigned j=0;j<rcovs[i]->times.size();j++) { struct timeval t1=rcovs[i]->times[j].second; struct timeval t2=rcovs[i]->times[j].first; timersub(&t1,&t2, &time_tmp); timeradd(&time_consumed,&time_tmp,&time_consumed); } html << "<tr><td><a href=\"javascript:showHide('ID" << to_string(i) << "')\"><table><tr><td>" << reportnames[i] << "</td></tr><tr><td>Number of executed tests:" << to_string((unsigned)traces.size()) << "</td></tr><tr><td>unique tests:" << to_string(unsigned(cnt.size())) << "</td></tr><tr><td>time used:" << to_string(time_consumed) << "</td></tr></table></a></td>" "<td>\n<div id=\"ID" << to_string(i) << "\">\n" << "<table border=\"4\">"; for(std::map<std::vector<std::pair<int,std::vector<int> > >,int>::iterator j=cnt.begin(); j!=cnt.end();j++) { html << "<td valign=\"top\">\n" << "<table border=\"0\">\n" << "<caption>Count:" << to_string((unsigned)j->second) << "</caption><td>" << "\n<ol>\n"; const std::vector<std::pair<int,std::vector<int> > >& t(j->first); for(unsigned k=0; k<t.size();k++) { html << "<li>" << an[t[k].first]; } html << "</ol>\n" << "</td></tr></table></td>"; } /* for(unsigned j=0;j<traces.size();j++) { ret=ret+"<td>"; ret=ret+"\n<ol>\n"; std::vector<int>& t(traces[j]); for(unsigned k=0; k<t.size();k++) { ret=ret+"<li>"+an[t[k]]; } ret=ret+"</ol>\n"; ret=ret+"</td>"; } */ html << "</table>\n" << "</div>\n</tr>"; } html << "</table>"; return html.str(); } FACTORY_DEFAULT_CREATOR(OutputFormat, OutputFormat_Html, "html") <commit_msg>Print arithmetic average, variance, min and max of the time used in the use case<commit_after>/* * fMBT, free Model Based Testing tool * Copyright (c) 2011, Intel Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "of_html.hh" #include "coverage.hh" #include "helper.hh" #include "model.hh" #include <map> #include <sstream> #include <algorithm> std::string OutputFormat_Html::header() { std::string script( "<SCRIPT LANGUAGE=\"JavaScript\">\n" "<!--\n" "function showHide(elementid){\n" "if (document.getElementById(elementid).style.display == 'none'){\n" "document.getElementById(elementid).style.display = '';\n" "} else {\n" "document.getElementById(elementid).style.display = 'none';\n" "}\n" "} \n" "//-->\n" "</SCRIPT>\n"); std::string ret("<html><header>"+script+"</header>"); ret+="<body>"; ret+="<table border=\"1\">\n<tr><th>UC</th>\n<th>verdict</th>\n"; for(unsigned i=0;i<covnames.size();i++) { ret=ret+"<th>"+covnames[i]+"</th>\n"; } ret=ret+"</tr>\n"; return ret; } std::string OutputFormat_Html::footer() { return "</table>"; } std::string OutputFormat_Html::format_covs() { std::string ret("<tr>\n"); //testname ret=ret+"<td>"+testnames.back()+"</td>"; //verdict ret=ret+"<td>"+test_verdict+"</td>\n"; for(unsigned i=0;i<covnames.size();i++) { ret=ret+"<td>"+to_string(covs[i]->getCoverage())+ "</td>\n"; } return ret+"</tr>\n"; } /* We might want to have more than one comparator for different orders */ bool vcmp (const std::vector<std::pair<int,std::vector<int> > >& lhs, const std::vector<std::pair<int,std::vector<int> > >& rhs) { if (lhs.size()==rhs.size()) { return lhs<rhs; } return lhs.size()<rhs.size(); } bool mytimercmp(struct timeval t1, struct timeval t2) { return timercmp(&t1,&t2,<); } std::string OutputFormat_Html::report() { std::ostringstream html; html << "<table border=\"2\">" << "<tr><th>Name</th><th>trace</th></tr>\n"; std::vector<std::string>& an(model->getActionNames()); for(unsigned i=0;i<reportnames.size();i++) { bool(*cmprp)(const std::vector<std::pair<int,std::vector<int> > >&, const std::vector<std::pair<int,std::vector<int> > >&) = vcmp; std::vector<std::vector<std::pair<int,std::vector<int> > > >& traces(rcovs[i]->traces); std::map<std::vector<std::pair<int,std::vector<int> > > , int, bool(*)(const std::vector<std::pair<int,std::vector<int> > >&,const std::vector<std::pair<int,std::vector<int> > >&) > cnt(cmprp); for(unsigned j=0;j<traces.size();j++) { cnt[traces[j]]++; } struct timeval time_tmp; struct timeval time_consumed={0,0}; struct timeval average_time={0,0}; std::vector<struct timeval> t; for(unsigned j=0;j<rcovs[i]->times.size();j++) { struct timeval t1=rcovs[i]->times[j].second; struct timeval t2=rcovs[i]->times[j].first; timersub(&t1,&t2, &time_tmp); t.push_back(time_tmp); timeradd(&time_consumed,&time_tmp,&time_consumed); } if (rcovs[i]->times.size()) { average_time.tv_sec=time_consumed.tv_sec/rcovs[i]->times.size(); average_time.tv_usec=(((time_consumed.tv_sec%rcovs[i]->times.size())*1000000)+time_consumed.tv_usec)/rcovs[i]->times.size(); } float variance=0; for(unsigned j=0;j<rcovs[i]->times.size();j++) { timersub(&t[j],&average_time,&time_tmp); float tmp=time_tmp.tv_sec+(1.0*time_tmp.tv_usec)/1000000.0; variance+=tmp*tmp; } if (rcovs[i]->times.size()) { variance=variance/rcovs[i]->times.size(); } html << "<tr><td><a href=\"javascript:showHide('ID" << to_string(i) << "')\"><table><tr><td>" << reportnames[i] << "</td></tr><tr><td>Number of executed tests:" << to_string((unsigned)traces.size()) << "</td></tr><tr><td>unique tests:" << to_string(unsigned(cnt.size())) << "</td></tr><tr><td>time used:" << to_string(time_consumed) << " Variance:" << to_string(variance) << " Average:" << to_string(average_time); if (rcovs[i]->times.size()) { html << " Min:" << to_string(*min_element(t.begin(),t.end(),mytimercmp)) << " Max:" << to_string(*max_element(t.begin(),t.end(),mytimercmp)); } html << "</td></tr></table></a></td>" "<td>\n<div id=\"ID" << to_string(i) << "\">\n" << "<table border=\"4\">"; for(std::map<std::vector<std::pair<int,std::vector<int> > >,int>::iterator j=cnt.begin(); j!=cnt.end();j++) { html << "<td valign=\"top\">\n" << "<table border=\"0\">\n" << "<caption>Count:" << to_string((unsigned)j->second) << "</caption><td>" << "\n<ol>\n"; const std::vector<std::pair<int,std::vector<int> > >& t(j->first); for(unsigned k=0; k<t.size();k++) { html << "<li>" << an[t[k].first]; } html << "</ol>\n" << "</td></tr></table></td>"; } /* for(unsigned j=0;j<traces.size();j++) { ret=ret+"<td>"; ret=ret+"\n<ol>\n"; std::vector<int>& t(traces[j]); for(unsigned k=0; k<t.size();k++) { ret=ret+"<li>"+an[t[k]]; } ret=ret+"</ol>\n"; ret=ret+"</td>"; } */ html << "</table>\n" << "</div>\n</tr>"; } html << "</table>"; return html.str(); } FACTORY_DEFAULT_CREATOR(OutputFormat, OutputFormat_Html, "html") <|endoftext|>
<commit_before>#include "parquet/parquet.h" #include "encodings.h" #include <string> #include <string.h> #include <thrift/protocol/TDebugProtocol.h> const int DATA_PAGE_SIZE = 64 * 1024; using namespace boost; using namespace parquet; using namespace std; namespace parquet_cpp { InMemoryInputStream::InMemoryInputStream(const uint8_t* buffer, int64_t len) : buffer_(buffer), len_(len), offset_(0) { } const uint8_t* InMemoryInputStream::Peek(int num_to_peek, int* num_bytes) { *num_bytes = ::min(static_cast<int64_t>(num_to_peek), len_ - offset_); return buffer_ + offset_; } const uint8_t* InMemoryInputStream::Read(int num_to_read, int* num_bytes) { const uint8_t* result = Peek(num_to_read, num_bytes); offset_ += *num_bytes; return result; } ColumnReader::ColumnReader(const ColumnMetaData* metadata, const SchemaElement* schema, InputStream* stream) : metadata_(metadata), schema_(schema), stream_(stream), current_decoder_(NULL), num_buffered_values_(0), num_decoded_values_(0), buffered_values_offset_(0) { int value_byte_size; switch (metadata->type) { case parquet::Type::BOOLEAN: value_byte_size = 1; break; case parquet::Type::INT32: value_byte_size = sizeof(int32_t); break; case parquet::Type::INT64: value_byte_size = sizeof(int64_t); break; case parquet::Type::FLOAT: value_byte_size = sizeof(float); break; case parquet::Type::DOUBLE: value_byte_size = sizeof(double); break; case parquet::Type::BYTE_ARRAY: value_byte_size = sizeof(ByteArray); break; default: ParquetException::NYI(); } if (metadata->codec != CompressionCodec::UNCOMPRESSED) ParquetException::NYI(); config_ = Config::DefaultConfig(); values_buffer_.resize(config_.batch_size * value_byte_size); } void ColumnReader::BatchDecode() { buffered_values_offset_ = 0; uint8_t* buf= &values_buffer_[0]; int batch_size = config_.batch_size; switch (metadata_->type) { case parquet::Type::BOOLEAN: num_decoded_values_ = current_decoder_->GetBool(reinterpret_cast<bool*>(buf), batch_size); break; case parquet::Type::INT32: num_decoded_values_ = current_decoder_->GetInt32(reinterpret_cast<int32_t*>(buf), batch_size); break; case parquet::Type::INT64: num_decoded_values_ = current_decoder_->GetInt64(reinterpret_cast<int64_t*>(buf), batch_size); break; case parquet::Type::FLOAT: num_decoded_values_ = current_decoder_->GetFloat(reinterpret_cast<float*>(buf), batch_size); break; case parquet::Type::DOUBLE: num_decoded_values_ = current_decoder_->GetDouble(reinterpret_cast<double*>(buf), batch_size); break; case parquet::Type::BYTE_ARRAY: num_decoded_values_ = current_decoder_->GetByteArray(reinterpret_cast<ByteArray*>(buf), batch_size); break; default: ParquetException::NYI(); } } // PLAIN_DICTIONARY is deprecated but used to be used as a dictionary index // encoding. static bool IsDictionaryIndexEncoding(const Encoding::type& e) { return e == Encoding::RLE_DICTIONARY || e == Encoding::PLAIN_DICTIONARY; } bool ColumnReader::ReadNewPage() { // Loop until we find the next data page. while (true) { int bytes_read = 0; const uint8_t* buffer = stream_->Peek(DATA_PAGE_SIZE, &bytes_read); if (bytes_read == 0) return false; uint32_t header_size = bytes_read; DeserializeThriftMsg(buffer, &header_size, &current_page_header_); stream_->Read(header_size, &bytes_read); // TODO: handle decompression. int uncompressed_len = current_page_header_.uncompressed_page_size; buffer = stream_->Read(uncompressed_len, &bytes_read); if (bytes_read != uncompressed_len) ParquetException::EofException(); if (current_page_header_.type == PageType::DICTIONARY_PAGE) { unordered_map<Encoding::type, shared_ptr<Decoder> >::iterator it = decoders_.find(Encoding::RLE_DICTIONARY); if (it != decoders_.end()) { throw ParquetException("Column cannot have more than one dictionary."); } PlainDecoder dictionary(schema_); dictionary.SetData(current_page_header_.dictionary_page_header.num_values, buffer, uncompressed_len); shared_ptr<Decoder> decoder(new DictionaryDecoder(schema_, &dictionary)); decoders_[Encoding::RLE_DICTIONARY] = decoder; current_decoder_ = decoders_[Encoding::RLE_DICTIONARY].get(); continue; } else if (current_page_header_.type == PageType::DATA_PAGE) { // Read a data page. num_buffered_values_ = current_page_header_.data_page_header.num_values; // Read definition levels. if (schema_->repetition_type != FieldRepetitionType::REQUIRED) { int num_definition_bytes = *reinterpret_cast<const uint32_t*>(buffer); buffer += sizeof(uint32_t); definition_level_decoder_.reset( new impala::RleDecoder(buffer, num_definition_bytes, 1)); buffer += num_definition_bytes; uncompressed_len -= sizeof(uint32_t); uncompressed_len -= num_definition_bytes; } // TODO: repetition levels // Get a decoder object for this page or create a new decoder if this is the // first page with this encoding. Encoding::type encoding = current_page_header_.data_page_header.encoding; if (IsDictionaryIndexEncoding(encoding)) encoding = Encoding::RLE_DICTIONARY; unordered_map<Encoding::type, shared_ptr<Decoder> >::iterator it = decoders_.find(encoding); if (it != decoders_.end()) { current_decoder_ = it->second.get(); } else { switch (encoding) { case Encoding::PLAIN: { shared_ptr<Decoder> decoder; if (schema_->type == Type::BOOLEAN) { decoder.reset(new BoolDecoder(schema_)); } else { shared_ptr<Decoder> decoder(new PlainDecoder(schema_)); } decoders_[encoding] = decoder; current_decoder_ = decoder.get(); break; } case Encoding::RLE_DICTIONARY: throw ParquetException("Dictionary page must be before data page."); case Encoding::DELTA_BINARY_PACKED: case Encoding::DELTA_LENGTH_BYTE_ARRAY: case Encoding::DELTA_BYTE_ARRAY: ParquetException::NYI(); default: throw ParquetException("Unknown encoding type."); } } current_decoder_->SetData(num_buffered_values_, buffer, uncompressed_len); } else { // We don't know what this page type is. We're allowed to skip non-data pages. continue; } } return true; } } <commit_msg>fix core-dump while reading PLAIN_ENCODING; fix readNewPage to return page instead of the last one<commit_after>#include "parquet/parquet.h" #include "encodings.h" #include <string> #include <string.h> #include <thrift/protocol/TDebugProtocol.h> const int DATA_PAGE_SIZE = 64 * 1024; using namespace boost; using namespace parquet; using namespace std; namespace parquet_cpp { InMemoryInputStream::InMemoryInputStream(const uint8_t* buffer, int64_t len) : buffer_(buffer), len_(len), offset_(0) { } const uint8_t* InMemoryInputStream::Peek(int num_to_peek, int* num_bytes) { *num_bytes = ::min(static_cast<int64_t>(num_to_peek), len_ - offset_); return buffer_ + offset_; } const uint8_t* InMemoryInputStream::Read(int num_to_read, int* num_bytes) { const uint8_t* result = Peek(num_to_read, num_bytes); offset_ += *num_bytes; return result; } ColumnReader::ColumnReader(const ColumnMetaData* metadata, const SchemaElement* schema, InputStream* stream) : metadata_(metadata), schema_(schema), stream_(stream), current_decoder_(NULL), num_buffered_values_(0), num_decoded_values_(0), buffered_values_offset_(0) { int value_byte_size; switch (metadata->type) { case parquet::Type::BOOLEAN: value_byte_size = 1; break; case parquet::Type::INT32: value_byte_size = sizeof(int32_t); break; case parquet::Type::INT64: value_byte_size = sizeof(int64_t); break; case parquet::Type::FLOAT: value_byte_size = sizeof(float); break; case parquet::Type::DOUBLE: value_byte_size = sizeof(double); break; case parquet::Type::BYTE_ARRAY: value_byte_size = sizeof(ByteArray); break; default: ParquetException::NYI(); } if (metadata->codec != CompressionCodec::UNCOMPRESSED) ParquetException::NYI(); config_ = Config::DefaultConfig(); values_buffer_.resize(config_.batch_size * value_byte_size); } void ColumnReader::BatchDecode() { buffered_values_offset_ = 0; uint8_t* buf= &values_buffer_[0]; int batch_size = config_.batch_size; switch (metadata_->type) { case parquet::Type::BOOLEAN: num_decoded_values_ = current_decoder_->GetBool(reinterpret_cast<bool*>(buf), batch_size); break; case parquet::Type::INT32: num_decoded_values_ = current_decoder_->GetInt32(reinterpret_cast<int32_t*>(buf), batch_size); break; case parquet::Type::INT64: num_decoded_values_ = current_decoder_->GetInt64(reinterpret_cast<int64_t*>(buf), batch_size); break; case parquet::Type::FLOAT: num_decoded_values_ = current_decoder_->GetFloat(reinterpret_cast<float*>(buf), batch_size); break; case parquet::Type::DOUBLE: num_decoded_values_ = current_decoder_->GetDouble(reinterpret_cast<double*>(buf), batch_size); break; case parquet::Type::BYTE_ARRAY: num_decoded_values_ = current_decoder_->GetByteArray(reinterpret_cast<ByteArray*>(buf), batch_size); break; default: ParquetException::NYI(); } } // PLAIN_DICTIONARY is deprecated but used to be used as a dictionary index // encoding. static bool IsDictionaryIndexEncoding(const Encoding::type& e) { return e == Encoding::RLE_DICTIONARY || e == Encoding::PLAIN_DICTIONARY; } bool ColumnReader::ReadNewPage() { // Loop until we find the next data page. while (true) { int bytes_read = 0; const uint8_t* buffer = stream_->Peek(DATA_PAGE_SIZE, &bytes_read); if (bytes_read == 0) return false; uint32_t header_size = bytes_read; DeserializeThriftMsg(buffer, &header_size, &current_page_header_); stream_->Read(header_size, &bytes_read); // TODO: handle decompression. int uncompressed_len = current_page_header_.uncompressed_page_size; buffer = stream_->Read(uncompressed_len, &bytes_read); if (bytes_read != uncompressed_len) ParquetException::EofException(); if (current_page_header_.type == PageType::DICTIONARY_PAGE) { unordered_map<Encoding::type, shared_ptr<Decoder> >::iterator it = decoders_.find(Encoding::RLE_DICTIONARY); if (it != decoders_.end()) { throw ParquetException("Column cannot have more than one dictionary."); } PlainDecoder dictionary(schema_); dictionary.SetData(current_page_header_.dictionary_page_header.num_values, buffer, uncompressed_len); shared_ptr<Decoder> decoder(new DictionaryDecoder(schema_, &dictionary)); decoders_[Encoding::RLE_DICTIONARY] = decoder; current_decoder_ = decoders_[Encoding::RLE_DICTIONARY].get(); continue; } else if (current_page_header_.type == PageType::DATA_PAGE) { // Read a data page. num_buffered_values_ = current_page_header_.data_page_header.num_values; // Read definition levels. if (schema_->repetition_type != FieldRepetitionType::REQUIRED) { int num_definition_bytes = *reinterpret_cast<const uint32_t*>(buffer); buffer += sizeof(uint32_t); definition_level_decoder_.reset( new impala::RleDecoder(buffer, num_definition_bytes, 1)); buffer += num_definition_bytes; uncompressed_len -= sizeof(uint32_t); uncompressed_len -= num_definition_bytes; } // TODO: repetition levels // Get a decoder object for this page or create a new decoder if this is the // first page with this encoding. Encoding::type encoding = current_page_header_.data_page_header.encoding; if (IsDictionaryIndexEncoding(encoding)) encoding = Encoding::RLE_DICTIONARY; unordered_map<Encoding::type, shared_ptr<Decoder> >::iterator it = decoders_.find(encoding); if (it != decoders_.end()) { current_decoder_ = it->second.get(); } else { switch (encoding) { case Encoding::PLAIN: { shared_ptr<Decoder> decoder; if (schema_->type == Type::BOOLEAN) { decoder.reset(new BoolDecoder(schema_)); } else { decoder.reset(new PlainDecoder(schema_)); } decoders_[encoding] = decoder; current_decoder_ = decoder.get(); break; } case Encoding::RLE_DICTIONARY: throw ParquetException("Dictionary page must be before data page."); case Encoding::DELTA_BINARY_PACKED: case Encoding::DELTA_LENGTH_BYTE_ARRAY: case Encoding::DELTA_BYTE_ARRAY: ParquetException::NYI(); default: throw ParquetException("Unknown encoding type."); } } current_decoder_->SetData(num_buffered_values_, buffer, uncompressed_len); return true; } else { // We don't know what this page type is. We're allowed to skip non-data pages. continue; } } return true; } } <|endoftext|>
<commit_before>#include "parser.hpp" namespace { bool isdigit(char c) { // TODO Should we instanciate the locate every times ? static std::locale loc; return std::isdigit(c, loc); } } namespace lyza { namespace json { void parser::error(lj::producer& p, std::string const& msg) { std::string until_eof; while (!p.eof()) { until_eof += p.nextc(); } throw parse_error(p.get_line(), p.get_column(), msg + " (until_eof=\"" + until_eof + "\")"); } bool parser::has(lj::producer& p, char c) { if (p.peekc() == c) { return true; } return false; } bool parser::may_have(lj::producer& p, char c) { if (p.peekc() == c) { p.nextc(); return true; } return false; } std::string parser::char_to_code(char c) { std::stringstream ss; ss << static_cast<int>(c); return ss.str(); } void parser::expects(lj::producer& p, char c) { char cc = p.nextc(); if (cc != c) { throw parse_error(p.get_line(), p.get_column(), std::string("parse error: ") + "'" + std::string(c, 1) + "'" + "(code=" + char_to_code(c) + ")" + " expected, got: " + "'" + std::string(cc, 1) + "'" + "' (code=" + char_to_code(cc) + ")"); } } void parser::match_string(lj::producer&p, std::string const& s) { for (auto c : s) { expects(p, c); } } lj::string parser::parse_string(lj::producer& p) { //std::cout << "parse_string" << std::endl; std::string acc; expects(p, '"'); p.skip_ws(false); while (!has(p, '"')) { if (may_have(p, '\\')) { acc += p.nextc(); } else { acc += p.nextc(); } } expects(p, '"'); p.skip_ws(true); return acc; } lj::boolean parser::parse_bool(lj::producer& p) { lj::boolean b = false; if (has(p, 't')) { match_string(p, "true"); b = true; } else if (has(p, 'f')) { match_string(p, "false"); b = false; } else { error(p, "expected boolean"); } return b; } lj::null parser::parse_null(lj::producer& p) { //std::cout << "parse_null" << std::endl; if (has(p, 'n')) { match_string(p, "null"); } else { error(p, "expected null"); } return lj::null(); } lj::array parser::parse_array(lj::producer& p) { //std::cout << "parse_array" << std::endl; lj::array a; expects(p, '['); if (has(p, ']')) { // empty p.nextc(); return a; } bool more = true; while (more) { a.push_back(parse_value(p)); if (has(p, ',')) { p.nextc(); more = true; } else more = false; } expects(p, ']'); return a; } lj::object parser::parse_object(lj::producer& p) { //std::cout << "parse_object" << std::endl; lj::object o; expects(p, '{'); if (has(p, '}')) { // empty p.nextc(); return o; } bool more = true; while (more) { if (has(p, '"')) { lj::string key = parse_string(p); expects(p, ':'); o[key] = parse_value(p); if (has(p, ',')) { p.nextc(); more = true; } else more = false; } else { error(p, "expected key"); } } expects(p, '}'); return o; } lj::number parser::parse_number(lj::producer& p) { //std::cout << "parse_number" << std::endl; bool neg = false; if (has(p, '-')) { p.nextc(); neg = true; } std::string num; if (has(p, '0')) { num += p.nextc(); } else { if ('0' < p.peekc() && p.peekc() <= '9') { num += p.nextc(); } else { error(p, "expected number"); } while (isdigit(p.peekc())) { num += p.nextc(); } } if (has(p, '.')) { num += p.nextc(); if (isdigit(p.peekc())) { num += p.nextc(); } else { error(p, "expected number"); } } while (isdigit(p.peekc())) { num += p.nextc(); } double dnum = std::stod(num); if (has(p, 'e') || has(p, 'E')) { p.nextc(); char op = '+'; if (has(p, '-') || has(p, '+')) { op = p.nextc(); } std::string exp; while (isdigit(p.peekc())) { exp += p.nextc(); } double dexp = std::pow(10, (op == '-' ? -1. : 1.) * std::stod(exp)); dnum = dnum * dexp; } return neg ? -dnum : dnum; } lj::value parser::parse_value(lj::producer& p) { //std::cout << "parse_value" << std::endl; lj::value val; if (has(p, '"')) { val = parse_string(p); } else if (has(p, '[')) { val = parse_array(p); } else if (has(p, '{')) { val = parse_object(p); } else if (has(p, 't') || has(p, 'f')) { val = parse_bool(p); } else if (has(p, 'n')) { val = parse_null(p); } else if (has(p, '-') || isdigit(p.peekc())) { val = parse_number(p); } else { error(p, "expected value"); } return val; } lj::object parser::parse(lj::producer& p) { p.skip_ws(true); return parse_object(p); } lj::object parser::parse(lj::producer&& p) { p.skip_ws(true); return parse_object(p); } }} <commit_msg>Code cosmetic<commit_after>#include "parser.hpp" namespace { bool isdigit(char c) { // TODO Should we instanciate the locate every times ? static std::locale loc; return std::isdigit(c, loc); } } namespace lyza { namespace json { void parser::error(lj::producer& p, std::string const& msg) { std::string until_eof; while (!p.eof()) { until_eof += p.nextc(); } throw parse_error(p.get_line(), p.get_column(), msg + " (until_eof=\"" + until_eof + "\")"); } bool parser::has(lj::producer& p, char c) { return p.peekc() == c; } bool parser::may_have(lj::producer& p, char c) { if (p.peekc() == c) { p.nextc(); return true; } return false; } std::string parser::char_to_code(char c) { std::stringstream ss; ss << static_cast<int>(c); return ss.str(); } void parser::expects(lj::producer& p, char c) { char cc = p.nextc(); if (cc != c) { throw parse_error(p.get_line(), p.get_column(), std::string("parse error: ") + "'" + std::string(c, 1) + "'" + "(code=" + char_to_code(c) + ")" + " expected, got: " + "'" + std::string(cc, 1) + "'" + "' (code=" + char_to_code(cc) + ")"); } } void parser::match_string(lj::producer&p, std::string const& s) { for (auto c : s) { expects(p, c); } } lj::string parser::parse_string(lj::producer& p) { //std::cout << "parse_string" << std::endl; std::string acc; expects(p, '"'); p.skip_ws(false); while (!has(p, '"')) { if (may_have(p, '\\')) { acc += p.nextc(); } else { acc += p.nextc(); } } expects(p, '"'); p.skip_ws(true); return acc; } lj::boolean parser::parse_bool(lj::producer& p) { lj::boolean b = false; if (has(p, 't')) { match_string(p, "true"); b = true; } else if (has(p, 'f')) { match_string(p, "false"); b = false; } else { error(p, "expected boolean"); } return b; } lj::null parser::parse_null(lj::producer& p) { //std::cout << "parse_null" << std::endl; if (has(p, 'n')) { match_string(p, "null"); } else { error(p, "expected null"); } return lj::null(); } lj::array parser::parse_array(lj::producer& p) { //std::cout << "parse_array" << std::endl; lj::array a; expects(p, '['); if (has(p, ']')) { // empty p.nextc(); return a; } bool more = true; while (more) { a.push_back(parse_value(p)); if (has(p, ',')) { p.nextc(); more = true; } else more = false; } expects(p, ']'); return a; } lj::object parser::parse_object(lj::producer& p) { //std::cout << "parse_object" << std::endl; lj::object o; expects(p, '{'); if (has(p, '}')) { // empty p.nextc(); return o; } bool more = true; while (more) { if (has(p, '"')) { lj::string key = parse_string(p); expects(p, ':'); o[key] = parse_value(p); if (has(p, ',')) { p.nextc(); more = true; } else more = false; } else { error(p, "expected key"); } } expects(p, '}'); return o; } lj::number parser::parse_number(lj::producer& p) { //std::cout << "parse_number" << std::endl; bool neg = false; if (has(p, '-')) { p.nextc(); neg = true; } std::string num; if (has(p, '0')) { num += p.nextc(); } else { if ('0' < p.peekc() && p.peekc() <= '9') { num += p.nextc(); } else { error(p, "expected number"); } while (isdigit(p.peekc())) { num += p.nextc(); } } if (has(p, '.')) { num += p.nextc(); if (isdigit(p.peekc())) { num += p.nextc(); } else { error(p, "expected number"); } } while (isdigit(p.peekc())) { num += p.nextc(); } double dnum = std::stod(num); if (has(p, 'e') || has(p, 'E')) { p.nextc(); char op = '+'; if (has(p, '-') || has(p, '+')) { op = p.nextc(); } std::string exp; while (isdigit(p.peekc())) { exp += p.nextc(); } double dexp = std::pow(10, (op == '-' ? -1. : 1.) * std::stod(exp)); dnum = dnum * dexp; } return neg ? -dnum : dnum; } lj::value parser::parse_value(lj::producer& p) { //std::cout << "parse_value" << std::endl; lj::value val; if (has(p, '"')) { val = parse_string(p); } else if (has(p, '[')) { val = parse_array(p); } else if (has(p, '{')) { val = parse_object(p); } else if (has(p, 't') || has(p, 'f')) { val = parse_bool(p); } else if (has(p, 'n')) { val = parse_null(p); } else if (has(p, '-') || isdigit(p.peekc())) { val = parse_number(p); } else { error(p, "expected value"); } return val; } lj::object parser::parse(lj::producer& p) { p.skip_ws(true); return parse_object(p); } lj::object parser::parse(lj::producer&& p) { p.skip_ws(true); return parse_object(p); } }} <|endoftext|>
<commit_before>/** * \file prastar.cc * * * * \author Seth Lemons * \date 2008-11-19 */ #include <assert.h> #include <math.h> #include <errno.h> #include <vector> #include <limits> extern "C" { #include "lockfree/include/atomic.h" } #include "util/timer.h" #include "util/mutex.h" #include "util/msg_buffer.h" #include "util/sync_solution_stream.h" #include "prastar.h" #include "projection.h" #include "search.h" #include "state.h" using namespace std; PRAStar::PRAStarThread::PRAStarThread(PRAStar *p, vector<PRAStarThread *> *threads, CompletionCounter* cc) : p(p), threads(threads), cc(cc), q_empty(true) { time_spinning = 0; out_qs.resize(threads->size(), NULL); completed = false; } PRAStar::PRAStarThread::~PRAStarThread(void) { vector<MsgBuffer<State*> *>::iterator i; for (i = out_qs.begin(); i != out_qs.end(); i++) if (*i) delete *i; } vector<State*> *PRAStar::PRAStarThread::get_queue(void) { return &q; } Mutex *PRAStar::PRAStarThread::get_mutex(void) { return &mutex; } void PRAStar::PRAStarThread::post_send(void *t) { PRAStarThread *thr = (PRAStarThread*) t; if (thr->completed) { thr->cc->uncomplete(); thr->completed = false; } thr->q_empty = false; } bool PRAStar::PRAStarThread::flush_sends(void) { unsigned int i; bool has_sends = false; for (i = 0; i < threads->size(); i += 1) { if (!out_qs[i]) continue; if (out_qs[i]) { out_qs[i]->try_flush(); if (!out_qs[i]->is_empty()) has_sends = true; } } return has_sends; } /** * Flush the queue */ void PRAStar::PRAStarThread::flush_receives(bool has_sends) { // wait for either completion or more nodes to expand if (open.empty() || !p->async_recv) mutex.lock(); else if (!mutex.try_lock()) // asynchronous return; if (q_empty && !has_sends) { if (!open.empty()) { mutex.unlock(); return; } completed = true; cc->complete(); // busy wait mutex.unlock(); while (q_empty && !cc->is_complete() && !p->is_done()) ; mutex.lock(); // we are done, just return if (cc->is_complete()) { assert(q_empty); mutex.unlock(); return; } } // got some stuff on the queue, lets do duplicate detection // and add stuff to the open list for (unsigned int i = 0; i < q.size(); i += 1) { State *c = q[i]; if (c->get_f() >= p->bound.read()) { delete c; continue; } State *dup = closed.lookup(c); if (dup){ if (dup->get_g() > c->get_g()) { dup->update(c->get_parent(), c->get_c(), c->get_g()); if (dup->is_open()) open.see_update(dup); else open.add(dup); } delete c; } else{ open.add(c); closed.add(c); } } q.clear(); q_empty = true; mutex.unlock(); } void PRAStar::PRAStarThread::do_async_send(unsigned int dest_tid, State *c) { if (!out_qs[dest_tid]) { Mutex *lk = threads->at(dest_tid)->get_mutex(); vector<State*> *qu = threads->at(dest_tid)->get_queue(); out_qs[dest_tid] = new MsgBuffer<State*>(lk, qu, post_send, threads->at(dest_tid)); } out_qs[dest_tid]->try_send(c); } void PRAStar::PRAStarThread::do_sync_send(unsigned int dest_tid, State *c) { PRAStarThread *dest = threads->at(dest_tid); dest->get_mutex()->lock(); dest->get_queue()->push_back(c); post_send(dest); dest->get_mutex()->unlock(); } void PRAStar::PRAStarThread::send_state(State *c) { unsigned long hash = p->use_abstraction ? p->project->project(c) : c->hash(); unsigned int dest_tid = threads->at(hash % p->n_threads)->get_id(); bool self_add = dest_tid == this->get_id(); assert (p->n_threads != 1 || self_add); if (self_add) { State *dup = closed.lookup(c); if (dup){ if (dup->get_g() > c->get_g()) { dup->update(c->get_parent(), c->get_c(), c->get_g()); if (dup->is_open()) open.see_update(dup); else open.add(dup); } delete c; } else{ open.add(c); closed.add(c); } return; } // not a self add if (p->async_send) do_async_send(dest_tid, c); else do_sync_send(dest_tid, c); } State *PRAStar::PRAStarThread::take(void) { Timer t; bool entered_loop = false; bool has_sends = flush_sends(); if (open.empty() || !q_empty) t.start(); while (open.empty() || !q_empty) { entered_loop = true; if (has_sends) has_sends = flush_sends(); flush_receives(has_sends); if (cc->is_complete()){ p->set_done(); return NULL; } } if (entered_loop) { t.stop(); time_spinning += t.get_wall_time(); } State *ret = NULL; if (!p->is_done()) ret = open.take(); return ret; } /** * Run the search thread. */ void PRAStar::PRAStarThread::run(void){ vector<State *> *children = NULL; while(!p->is_done()){ State *s = take(); if (s == NULL) continue; if (s->get_f() >= p->bound.read()) { open.prune(); continue; } if (s->is_goal()) { p->set_path(s->get_path()); } children = p->expand(s); for (unsigned int i = 0; i < children->size(); i += 1) { State *c = children->at(i); if (c->get_f() < p->bound.read()) send_state(c); else delete c; } delete children; } } /************************************************************/ PRAStar::PRAStar(unsigned int n_threads, bool use_abst, bool a_send, bool a_recv) : n_threads(n_threads), bound(fp_infinity), project(NULL), use_abstraction(use_abst), async_send(a_send), async_recv(a_recv) { done = false; } PRAStar::~PRAStar(void) { for (iter = threads.begin(); iter != threads.end(); iter++) { if (*iter) delete (*iter); } } void PRAStar::set_done() { mutex.lock(); done = true; mutex.unlock(); } bool PRAStar::is_done() { return done; } void PRAStar::set_path(vector<State *> *p) { fp_type b, oldb; assert(solutions); solutions->see_solution(p, get_generated(), get_expanded()); b = solutions->get_best_path()->at(0)->get_g(); // CAS in our new solution bound if it is still indeed better // than the previous bound. do { oldb = bound.read(); if (oldb <= b) return; } while (bound.cmp_and_swap(oldb, b) != oldb); } vector<State *> *PRAStar::search(Timer *timer, State *init) { solutions = new SyncSolutionStream(timer, 0.0001); project = init->get_domain()->get_projection(); CompletionCounter cc = CompletionCounter(n_threads); threads.resize(n_threads, NULL); for (unsigned int i = 0; i < n_threads; i += 1) threads.at(i) = new PRAStarThread(this, &threads, &cc); if (use_abstraction) threads.at(project->project(init)%n_threads)->open.add(init); else threads.at(init->hash() % n_threads)->open.add(init); for (iter = threads.begin(); iter != threads.end(); iter++) { (*iter)->start(); } for (iter = threads.begin(); iter != threads.end(); iter++) (*iter)->join(); return solutions->get_best_path(); } void PRAStar::output_stats(void) { time_spinning = 0.0; max_open_size = 0; avg_open_size = 0; for (iter = threads.begin(); iter != threads.end(); iter++) { time_spinning += (*iter)->time_spinning; avg_open_size += (*iter)->open.get_avg_size(); if ((*iter)->open.get_max_size() > max_open_size) max_open_size = (*iter)->open.get_max_size(); } avg_open_size /= n_threads; if (solutions) solutions->output(cout); cout << "total-time-acquiring-locks: " << Mutex::get_total_lock_acquisition_time() << endl; cout << "average-time-acquiring-locks: " << Mutex::get_total_lock_acquisition_time() / n_threads << endl; cout << "total-time-waiting: " << time_spinning << endl; cout << "average-time-waiting: " << time_spinning / n_threads << endl; cout << "average-open-size: " << avg_open_size << endl; cout << "max-open-size: " << max_open_size << endl; } <commit_msg>Fix a race condition in the waiting timer.<commit_after>/** * \file prastar.cc * * * * \author Seth Lemons * \date 2008-11-19 */ #include <assert.h> #include <math.h> #include <errno.h> #include <vector> #include <limits> extern "C" { #include "lockfree/include/atomic.h" } #include "util/timer.h" #include "util/mutex.h" #include "util/msg_buffer.h" #include "util/sync_solution_stream.h" #include "prastar.h" #include "projection.h" #include "search.h" #include "state.h" using namespace std; PRAStar::PRAStarThread::PRAStarThread(PRAStar *p, vector<PRAStarThread *> *threads, CompletionCounter* cc) : p(p), threads(threads), cc(cc), q_empty(true) { time_spinning = 0; out_qs.resize(threads->size(), NULL); completed = false; } PRAStar::PRAStarThread::~PRAStarThread(void) { vector<MsgBuffer<State*> *>::iterator i; for (i = out_qs.begin(); i != out_qs.end(); i++) if (*i) delete *i; } vector<State*> *PRAStar::PRAStarThread::get_queue(void) { return &q; } Mutex *PRAStar::PRAStarThread::get_mutex(void) { return &mutex; } void PRAStar::PRAStarThread::post_send(void *t) { PRAStarThread *thr = (PRAStarThread*) t; if (thr->completed) { thr->cc->uncomplete(); thr->completed = false; } thr->q_empty = false; } bool PRAStar::PRAStarThread::flush_sends(void) { unsigned int i; bool has_sends = false; for (i = 0; i < threads->size(); i += 1) { if (!out_qs[i]) continue; if (out_qs[i]) { out_qs[i]->try_flush(); if (!out_qs[i]->is_empty()) has_sends = true; } } return has_sends; } /** * Flush the queue */ void PRAStar::PRAStarThread::flush_receives(bool has_sends) { // wait for either completion or more nodes to expand if (open.empty() || !p->async_recv) mutex.lock(); else if (!mutex.try_lock()) // asynchronous return; if (q_empty && !has_sends) { if (!open.empty()) { mutex.unlock(); return; } completed = true; cc->complete(); // busy wait mutex.unlock(); while (q_empty && !cc->is_complete() && !p->is_done()) ; mutex.lock(); // we are done, just return if (cc->is_complete()) { assert(q_empty); mutex.unlock(); return; } } // got some stuff on the queue, lets do duplicate detection // and add stuff to the open list for (unsigned int i = 0; i < q.size(); i += 1) { State *c = q[i]; if (c->get_f() >= p->bound.read()) { delete c; continue; } State *dup = closed.lookup(c); if (dup){ if (dup->get_g() > c->get_g()) { dup->update(c->get_parent(), c->get_c(), c->get_g()); if (dup->is_open()) open.see_update(dup); else open.add(dup); } delete c; } else{ open.add(c); closed.add(c); } } q.clear(); q_empty = true; mutex.unlock(); } void PRAStar::PRAStarThread::do_async_send(unsigned int dest_tid, State *c) { if (!out_qs[dest_tid]) { Mutex *lk = threads->at(dest_tid)->get_mutex(); vector<State*> *qu = threads->at(dest_tid)->get_queue(); out_qs[dest_tid] = new MsgBuffer<State*>(lk, qu, post_send, threads->at(dest_tid)); } out_qs[dest_tid]->try_send(c); } void PRAStar::PRAStarThread::do_sync_send(unsigned int dest_tid, State *c) { PRAStarThread *dest = threads->at(dest_tid); dest->get_mutex()->lock(); dest->get_queue()->push_back(c); post_send(dest); dest->get_mutex()->unlock(); } void PRAStar::PRAStarThread::send_state(State *c) { unsigned long hash = p->use_abstraction ? p->project->project(c) : c->hash(); unsigned int dest_tid = threads->at(hash % p->n_threads)->get_id(); bool self_add = dest_tid == this->get_id(); assert (p->n_threads != 1 || self_add); if (self_add) { State *dup = closed.lookup(c); if (dup){ if (dup->get_g() > c->get_g()) { dup->update(c->get_parent(), c->get_c(), c->get_g()); if (dup->is_open()) open.see_update(dup); else open.add(dup); } delete c; } else{ open.add(c); closed.add(c); } return; } // not a self add if (p->async_send) do_async_send(dest_tid, c); else do_sync_send(dest_tid, c); } State *PRAStar::PRAStarThread::take(void) { Timer t; bool entered_loop = false; bool timer_started = false; bool has_sends = flush_sends(); while (open.empty() || !q_empty) { if (!timer_started) { timer_started = true; t.start(); } entered_loop = true; if (has_sends) has_sends = flush_sends(); flush_receives(has_sends); if (cc->is_complete()){ p->set_done(); return NULL; } } if (timer_started) { t.stop(); time_spinning += t.get_wall_time(); } State *ret = NULL; if (!p->is_done()) ret = open.take(); return ret; } /** * Run the search thread. */ void PRAStar::PRAStarThread::run(void){ vector<State *> *children = NULL; while(!p->is_done()){ State *s = take(); if (s == NULL) continue; if (s->get_f() >= p->bound.read()) { open.prune(); continue; } if (s->is_goal()) { p->set_path(s->get_path()); } children = p->expand(s); for (unsigned int i = 0; i < children->size(); i += 1) { State *c = children->at(i); if (c->get_f() < p->bound.read()) send_state(c); else delete c; } delete children; } } /************************************************************/ PRAStar::PRAStar(unsigned int n_threads, bool use_abst, bool a_send, bool a_recv) : n_threads(n_threads), bound(fp_infinity), project(NULL), use_abstraction(use_abst), async_send(a_send), async_recv(a_recv) { done = false; } PRAStar::~PRAStar(void) { for (iter = threads.begin(); iter != threads.end(); iter++) { if (*iter) delete (*iter); } } void PRAStar::set_done() { mutex.lock(); done = true; mutex.unlock(); } bool PRAStar::is_done() { return done; } void PRAStar::set_path(vector<State *> *p) { fp_type b, oldb; assert(solutions); solutions->see_solution(p, get_generated(), get_expanded()); b = solutions->get_best_path()->at(0)->get_g(); // CAS in our new solution bound if it is still indeed better // than the previous bound. do { oldb = bound.read(); if (oldb <= b) return; } while (bound.cmp_and_swap(oldb, b) != oldb); } vector<State *> *PRAStar::search(Timer *timer, State *init) { solutions = new SyncSolutionStream(timer, 0.0001); project = init->get_domain()->get_projection(); CompletionCounter cc = CompletionCounter(n_threads); threads.resize(n_threads, NULL); for (unsigned int i = 0; i < n_threads; i += 1) threads.at(i) = new PRAStarThread(this, &threads, &cc); if (use_abstraction) threads.at(project->project(init)%n_threads)->open.add(init); else threads.at(init->hash() % n_threads)->open.add(init); for (iter = threads.begin(); iter != threads.end(); iter++) { (*iter)->start(); } for (iter = threads.begin(); iter != threads.end(); iter++) (*iter)->join(); return solutions->get_best_path(); } void PRAStar::output_stats(void) { time_spinning = 0.0; max_open_size = 0; avg_open_size = 0; for (iter = threads.begin(); iter != threads.end(); iter++) { time_spinning += (*iter)->time_spinning; avg_open_size += (*iter)->open.get_avg_size(); if ((*iter)->open.get_max_size() > max_open_size) max_open_size = (*iter)->open.get_max_size(); } avg_open_size /= n_threads; if (solutions) solutions->output(cout); cout << "total-time-acquiring-locks: " << Mutex::get_total_lock_acquisition_time() << endl; cout << "average-time-acquiring-locks: " << Mutex::get_total_lock_acquisition_time() / n_threads << endl; cout << "total-time-waiting: " << time_spinning << endl; cout << "average-time-waiting: " << time_spinning / n_threads << endl; cout << "average-open-size: " << avg_open_size << endl; cout << "max-open-size: " << max_open_size << endl; } <|endoftext|>
<commit_before>#ifndef ALEPH_TOPOLOGY_IO_GML_HH__ #define ALEPH_TOPOLOGY_IO_GML_HH__ #include <fstream> #include <map> #include <set> #include <regex> #include <sstream> #include <stack> #include <string> #include <unordered_map> #include <vector> #include <aleph/utilities/String.hh> namespace aleph { namespace topology { namespace io { /** @class GMLReader @brief Parses files in GML (Graph Modeling Language) format This is a simple reader for graphs in GML format. It suports a basic subset of the GML specification, viz. the specification of different attributes for nodes, as well as weight specifications for edges. Currently, the following attributes will be read: - \c id (for nodes) - \c label (for nodes) - \c source (for edges) - \c target (for edges) - \c weight (for edges) */ class GMLReader { public: /** Reads a simplicial complex from a file, using the default maximum functor for weight assignment. If you want to change the functor, please refer to the overloaded variant of this method. @param filename Input filename @param K Simplicial complex @see operator()( const std::string&, SimplicialComplex& ) */ template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K ) { using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; this->operator()( filename, K, [] ( DataType a, DataType b ) { return std::max(a,b); } ); } /** Reads a simplicial complex from a file while supporting arbitrary functors for weight assignment. The functor needs to support this interface: \code{.cpp} using SimplexType = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; DataType Functor::operator()( DataType a, DataType b ) { // Do something with a and b. Typically, this would be calculating // either the minimum or the maximum... return std::max(a, b); } \endcode Please refer to the documentation of SimplicialComplexReader::operator()( const std::string& SimplicialComplex&, Functor ) for more details. */ template <class SimplicialComplex, class Functor> void operator()( const std::string& filename, SimplicialComplex& K, Functor f ) { std::ifstream in( filename ); if( !in ) throw std::runtime_error( "Unable to read input file" ); this->operator()( in, K, f ); } /** @overload operator()( const std::string&, SimplicialComplex& ) */ template <class SimplicialComplex> void operator()( std::ifstream& in, SimplicialComplex& K ) { using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; this->operator()( in, K, [] ( DataType a, DataType b ) { return std::max(a,b); } ); } /** @overload operator()( const std::string&, SimplicialComplex&, SimplicialComplex&, Functor ) */ template <class SimplicialComplex, class Functor> void operator()( std::ifstream& in, SimplicialComplex& K, Functor f ) { _nodes.clear(); _edges.clear(); using namespace aleph::utilities; using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; using VertexType = typename Simplex::VertexType; std::string line; std::set<std::string> levels = { "graph", "node", "edge" }; std::set<std::string> attributes = { "id", "label", "source", "target", "value", "weight" }; auto isLevel = [&levels] ( const std::string& name ) { return levels.find( name ) != levels.end(); }; auto isAttribute = [&attributes] ( const std::string& name ) { return attributes.find( name ) != attributes.end(); }; // Specifies the current level the parser is in. May be either one // of the known levels above. std::stack<std::string> currentLevel; // Last level that was read by the parser. If an open bracket '[' is // identified, this will become the current level. std::string lastLevel; Graph graph; Node node; Edge edge; std::regex reAttribute = std::regex( "([[:alpha:]]+)[[:space:]]*.*" ); std::regex reKeyValue = std::regex( "([[:alpha:]]+)[[:space:]]+([[:alnum:]\\.]+)" ); std::regex reLabel = std::regex( "(label)[[:space:]]+\"([^\"]+)\"" ); while( std::getline( in, line ) ) { line = trim( line ); auto tokens = split( line ); // Skip comment lines. This is somewhat wasteful because I am // splitting the complete string even though I merely need to // know the first token. if( tokens.empty() == false && ( tokens.front() == "comment" || tokens.front() == "Creator" ) ) continue; // A new level may also be opened "inline" by specifying a name // and the opening bracket at the same time. bool newLevel = isLevel( line ) || ( tokens.size() == 2 && tokens.back() == "[" && isLevel( tokens.front() ) ); // Detecting a new level if( newLevel ) { auto level = tokens.size() == 2 ? tokens.front() : line; if( lastLevel.empty() ) lastLevel = level; else throw std::runtime_error( "Encountered incorrectly-nested levels" ); // Only store the level directly when it has been specified // inline if( tokens.size() == 2 ) { currentLevel.push( level ); lastLevel = ""; } } // Opening a new level else if( line == "[" ) { currentLevel.push( lastLevel ); lastLevel = ""; } // Closing a new level else if( line == "]" ) { if( currentLevel.top() == "node" ) _nodes.push_back( node ); else if( currentLevel.top() == "edge" ) _edges.push_back( edge ); // Reset node and edge data structure to fill them again once // a new level is being encountered. node = {}; edge = {}; currentLevel.pop(); } // Check for attributes else { if( currentLevel.empty() ) throw std::runtime_error( "Expected a non-empty current level" ); std::smatch matches; auto* dict = currentLevel.top() == "node" ? &node.dict : currentLevel.top() == "edge" ? &edge.dict : currentLevel.top() == "graph" ? &graph.dict : throw std::runtime_error( "Current level is unknown" ); if( std::regex_match( line, matches, reAttribute ) ) { auto name = matches[1]; if( isAttribute( name ) ) { // Special matching for labels if( name == "label" ) std::regex_match( line, matches, reLabel ); // Regular matching for all other attributes else std::regex_match( line, matches, reKeyValue ); auto value = matches[2]; if( name == "id" ) node.id = value; else if( name == "source" ) edge.source = value; else if( name == "target" ) edge.target = value; // Just add it to the dictionary of optional values else dict->operator[]( name ) = value; } // Skip unknown attributes... else { } } } } // Creates nodes (vertices) ---------------------------------------- std::set<std::string> nodeIDs; for( auto&& node : _nodes ) { auto pair = nodeIDs.insert( node.id ); if( !pair.second ) throw std::runtime_error( "Duplicate node id '" + node.id + "'" ); } std::vector<Simplex> simplices; simplices.reserve( _nodes.size() + _edges.size() ); // Maps an ID directly to its corresponding simplex in order to // facilitate the assignment of weights. std::unordered_map<VertexType, Simplex> id_to_simplex; for( auto&& node : _nodes ) { auto id = static_cast<VertexType>( getID( nodeIDs, node.id ) ); if( node.dict.find( "weight" ) != node.dict.end() ) simplices.push_back( Simplex( id, convert<DataType>( node.dict.at( "weight" ) ) ) ); else if( node.dict.find( "value" ) != node.dict.end() ) simplices.push_back( Simplex( id, convert<DataType>( node.dict.at( "value" ) ) ) ); else simplices.push_back( Simplex( id ) ); id_to_simplex[id] = simplices.back(); } // Create edges ---------------------------------------------------- for( auto&& edge : _edges ) { auto u = static_cast<VertexType>( getID( nodeIDs, edge.source ) ); auto v = static_cast<VertexType>( getID( nodeIDs, edge.target ) ); // No optional data attached; need to create weight based on node // weights, if those are available. if( edge.dict.find( "weight" ) == edge.dict.end() && edge.dict.find( "value" ) == edge.dict.end() ) { auto uSimplex = id_to_simplex.at(u); auto vSimplex = id_to_simplex.at(v); simplices.push_back( Simplex( {u,v}, f( uSimplex.data(), vSimplex.data() ) ) ); } // Use converted weight else if( edge.dict.find( "weight" ) != edge.dict.end() ) simplices.push_back( Simplex( {u,v}, convert<DataType>( edge.dict.at( "weight" ) ) ) ); else if( edge.dict.find( "value" ) != edge.dict.end() ) simplices.push_back( Simplex( {u,v}, convert<DataType>( edge.dict.at( "value" ) ) ) ); } _graph = graph; K = SimplicialComplex( simplices.begin(), simplices.end() ); } /** Retrieves a map of attribute values for each node. The attributes will be assigned to the node ID. Empty attributes signify that no such information is available. */ std::map<std::string, std::string> getNodeAttribute( const std::string& attribute ) const { std::map<std::string, std::string> map; for( auto&& node : _nodes ) { if( node.dict.find( attribute ) == node.dict.end() ) map[ node.id ] = std::string(); else map[ node.id ] = node.dict.at( attribute ); } return map; } /** Returns a map that maps a node ID to an index. It corresponds to the order in which node IDs were allocated. It is *always* zero-indexed. */ template <class VertexType> std::map<std::string, VertexType> id_to_index() const noexcept { std::set<std::string> nodeIDs; for( auto&& node : _nodes ) nodeIDs.insert( node.id ); std::map<std::string, VertexType> result; for( auto&& node : _nodes ) result[ node.id ] = static_cast<VertexType>( getID( nodeIDs, node.id ) ); return result; } private: /** Auxiliary function for creating a numerical ID out of a parsed ID. In case non-numerical IDs are being used in the source file, this function ensures that internal IDs *always* start with a zero. If, however, numerical IDs are being used, they are converted as-is. */ static std::size_t getID( const std::set<std::string>& ids, const std::string& id ) { // Try to be smart: If the node ID can be converted into the // vertex type, we use the converted number instead. try { auto convertedID = std::stoll( id ); return static_cast<std::size_t>( convertedID ); } catch( std::out_of_range& e ) { throw; } catch( std::invalid_argument& ) { return static_cast<std::size_t>( std::distance( ids.begin(), ids.find( id ) ) ); } }; /** Describes a parsed graph along with all of its attributes */ struct Graph { std::map<std::string, std::string> dict; // all remaining attributes }; /** Describes a parsed node along with all of its attributes */ struct Node { std::string id; std::map<std::string, std::string> dict; // all remaining attributes }; /** Describes a parsed edge along with all of its attributes */ struct Edge { std::string source; std::string target; std::map<std::string, std::string> dict; // all remaining attributes }; // Local storage ----------------------------------------------------- // // Variables in this section contain the result of the last parsing // process. This is useful when clients are querying attributes. Graph _graph; std::vector<Node> _nodes; std::vector<Edge> _edges; }; /** @class GMLWriter @brief Writes files in GML (Graph Modeling Language) format This is a simple writer for graphs in GML format. It suports a basic subset of the GML specification, viz. the specification of different attributes for nodes, as well as weight specifications for edges. Given a simplicial complex, it will store it as a weighted graph. Currently, the following attributes will be written: * \c id (for nodes) * \c source (for edges) * \c target (for edges) * \c weight (for edges) */ class GMLWriter { public: template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K ) { std::ofstream out( filename ); if( !out ) throw std::runtime_error( "Unable to open output file" ); this->operator()( out, K ); } template <class SimplicialComplex> void operator()( std::ostream& out, SimplicialComplex& K ) { std::ostringstream streamNodes; std::ostringstream streamEdges; for( auto&& simplex : K ) { if( simplex.dimension() == 0 ) { streamNodes << " node [\n" << " id " << *simplex.begin() << "\n" << " ]\n"; } else if( simplex.dimension() == 1 ) { auto u = *( simplex.begin() ); auto v = *( simplex.begin() + 1 ); streamEdges << " edge [\n" << " source " << u << "\n" << " target " << v << "\n" << " weight " << simplex.data() << "\n" << " ]\n"; } } out << "graph [\n" << " directed 0\n" << streamNodes.str() << "\n" << streamEdges.str() << "\n" << "]\n"; } }; } // namespace io } // namespace topology } // namespace aleph #endif <commit_msg>Improved handling of unknown attributes<commit_after>#ifndef ALEPH_TOPOLOGY_IO_GML_HH__ #define ALEPH_TOPOLOGY_IO_GML_HH__ #include <fstream> #include <map> #include <set> #include <regex> #include <sstream> #include <stack> #include <string> #include <unordered_map> #include <vector> #include <aleph/utilities/String.hh> namespace aleph { namespace topology { namespace io { /** @class GMLReader @brief Parses files in GML (Graph Modeling Language) format This is a simple reader for graphs in GML format. It suports a basic subset of the GML specification, viz. the specification of different attributes for nodes, as well as weight specifications for edges. Currently, the following attributes will be read: - \c id (for nodes) - \c label (for nodes) - \c source (for edges) - \c target (for edges) - \c weight (for edges) */ class GMLReader { public: /** Reads a simplicial complex from a file, using the default maximum functor for weight assignment. If you want to change the functor, please refer to the overloaded variant of this method. @param filename Input filename @param K Simplicial complex @see operator()( const std::string&, SimplicialComplex& ) */ template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K ) { using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; this->operator()( filename, K, [] ( DataType a, DataType b ) { return std::max(a,b); } ); } /** Reads a simplicial complex from a file while supporting arbitrary functors for weight assignment. The functor needs to support this interface: \code{.cpp} using SimplexType = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; DataType Functor::operator()( DataType a, DataType b ) { // Do something with a and b. Typically, this would be calculating // either the minimum or the maximum... return std::max(a, b); } \endcode Please refer to the documentation of SimplicialComplexReader::operator()( const std::string& SimplicialComplex&, Functor ) for more details. */ template <class SimplicialComplex, class Functor> void operator()( const std::string& filename, SimplicialComplex& K, Functor f ) { std::ifstream in( filename ); if( !in ) throw std::runtime_error( "Unable to read input file" ); this->operator()( in, K, f ); } /** @overload operator()( const std::string&, SimplicialComplex& ) */ template <class SimplicialComplex> void operator()( std::ifstream& in, SimplicialComplex& K ) { using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; this->operator()( in, K, [] ( DataType a, DataType b ) { return std::max(a,b); } ); } /** @overload operator()( const std::string&, SimplicialComplex&, SimplicialComplex&, Functor ) */ template <class SimplicialComplex, class Functor> void operator()( std::ifstream& in, SimplicialComplex& K, Functor f ) { _nodes.clear(); _edges.clear(); using namespace aleph::utilities; using Simplex = typename SimplicialComplex::ValueType; using DataType = typename Simplex::DataType; using VertexType = typename Simplex::VertexType; std::string line; std::set<std::string> levels = { "graph", "node", "edge" }; std::set<std::string> attributes = { "id", "label", "source", "target", "value", "weight" }; auto isLevel = [&levels] ( const std::string& name ) { return levels.find( name ) != levels.end(); }; auto isAttribute = [&attributes] ( const std::string& name ) { return attributes.find( name ) != attributes.end(); }; // Specifies the current level the parser is in. May be either one // of the known levels above. std::stack<std::string> currentLevel; // Last level that was read by the parser. If an open bracket '[' is // identified, this will become the current level. std::string lastLevel; Graph graph; Node node; Edge edge; std::regex reAttribute = std::regex( "([_\\|[:alpha:]]+)[[:space:]]*.*" ); std::regex reKeyValue = std::regex( "([_\\|[:alpha:]]+)[[:space:]]+([[:alnum:]\\.]+)" ); std::regex reLabel = std::regex( "(label)[[:space:]]+\"([^\"]+)\"" ); while( std::getline( in, line ) ) { line = trim( line ); auto tokens = split( line ); // Skip comment lines. This is somewhat wasteful because I am // splitting the complete string even though I merely need to // know the first token. if( tokens.empty() == false && ( tokens.front() == "comment" || tokens.front() == "Creator" ) ) continue; // A new level may also be opened "inline" by specifying a name // and the opening bracket at the same time. bool newLevel = isLevel( line ) || ( tokens.size() == 2 && tokens.back() == "[" && isLevel( tokens.front() ) ); // Detecting a new level if( newLevel ) { auto level = tokens.size() == 2 ? tokens.front() : line; if( lastLevel.empty() ) lastLevel = level; else throw std::runtime_error( "Encountered incorrectly-nested levels" ); // Only store the level directly when it has been specified // inline if( tokens.size() == 2 ) { currentLevel.push( level ); lastLevel = ""; } } // Opening a new level else if( line == "[" ) { currentLevel.push( lastLevel ); lastLevel = ""; } // Closing a new level else if( line == "]" ) { if( currentLevel.top() == "node" ) _nodes.push_back( node ); else if( currentLevel.top() == "edge" ) _edges.push_back( edge ); // Reset node and edge data structure to fill them again once // a new level is being encountered. node = {}; edge = {}; currentLevel.pop(); } // Check for attributes else { if( currentLevel.empty() ) throw std::runtime_error( "Expected a non-empty current level" ); std::smatch matches; auto* dict = currentLevel.top() == "node" ? &node.dict : currentLevel.top() == "edge" ? &edge.dict : currentLevel.top() == "graph" ? &graph.dict : throw std::runtime_error( "Current level is unknown" ); if( std::regex_match( line, matches, reAttribute ) ) { auto name = matches[1]; if( isAttribute( name ) ) { // Special matching for labels if( name == "label" ) std::regex_match( line, matches, reLabel ); // Regular matching for all other attributes else std::regex_match( line, matches, reKeyValue ); auto value = matches[2]; if( name == "id" ) node.id = value; else if( name == "source" ) edge.source = value; else if( name == "target" ) edge.target = value; // Just add it to the dictionary of optional values else dict->operator[]( name ) = value; } // Attempt key--value matching for the unknown attribute and // store it in the dictionary. else { std::regex_match( line, matches, reKeyValue ); if( matches.size() >= 3 ) { auto value = matches[2]; dict->operator[]( name ) = value; } } } } } // Creates nodes (vertices) ---------------------------------------- std::set<std::string> nodeIDs; for( auto&& node : _nodes ) { auto pair = nodeIDs.insert( node.id ); if( !pair.second ) throw std::runtime_error( "Duplicate node id '" + node.id + "'" ); } std::vector<Simplex> simplices; simplices.reserve( _nodes.size() + _edges.size() ); // Maps an ID directly to its corresponding simplex in order to // facilitate the assignment of weights. std::unordered_map<VertexType, Simplex> id_to_simplex; for( auto&& node : _nodes ) { auto id = static_cast<VertexType>( getID( nodeIDs, node.id ) ); if( node.dict.find( "weight" ) != node.dict.end() ) simplices.push_back( Simplex( id, convert<DataType>( node.dict.at( "weight" ) ) ) ); else if( node.dict.find( "value" ) != node.dict.end() ) simplices.push_back( Simplex( id, convert<DataType>( node.dict.at( "value" ) ) ) ); else simplices.push_back( Simplex( id ) ); id_to_simplex[id] = simplices.back(); } // Create edges ---------------------------------------------------- for( auto&& edge : _edges ) { auto u = static_cast<VertexType>( getID( nodeIDs, edge.source ) ); auto v = static_cast<VertexType>( getID( nodeIDs, edge.target ) ); // No optional data attached; need to create weight based on node // weights, if those are available. if( edge.dict.find( "weight" ) == edge.dict.end() && edge.dict.find( "value" ) == edge.dict.end() ) { auto uSimplex = id_to_simplex.at(u); auto vSimplex = id_to_simplex.at(v); simplices.push_back( Simplex( {u,v}, f( uSimplex.data(), vSimplex.data() ) ) ); } // Use converted weight else if( edge.dict.find( "weight" ) != edge.dict.end() ) simplices.push_back( Simplex( {u,v}, convert<DataType>( edge.dict.at( "weight" ) ) ) ); else if( edge.dict.find( "value" ) != edge.dict.end() ) simplices.push_back( Simplex( {u,v}, convert<DataType>( edge.dict.at( "value" ) ) ) ); } _graph = graph; K = SimplicialComplex( simplices.begin(), simplices.end() ); } /** Retrieves a map of attribute values for each node. The attributes will be assigned to the node ID. Empty attributes signify that no such information is available. */ std::map<std::string, std::string> getNodeAttribute( const std::string& attribute ) const { std::map<std::string, std::string> map; for( auto&& node : _nodes ) { if( node.dict.find( attribute ) == node.dict.end() ) map[ node.id ] = std::string(); else map[ node.id ] = node.dict.at( attribute ); } return map; } /** Returns a map that maps a node ID to an index. It corresponds to the order in which node IDs were allocated. It is *always* zero-indexed. */ template <class VertexType> std::map<std::string, VertexType> id_to_index() const noexcept { std::set<std::string> nodeIDs; for( auto&& node : _nodes ) nodeIDs.insert( node.id ); std::map<std::string, VertexType> result; for( auto&& node : _nodes ) result[ node.id ] = static_cast<VertexType>( getID( nodeIDs, node.id ) ); return result; } private: /** Auxiliary function for creating a numerical ID out of a parsed ID. In case non-numerical IDs are being used in the source file, this function ensures that internal IDs *always* start with a zero. If, however, numerical IDs are being used, they are converted as-is. */ static std::size_t getID( const std::set<std::string>& ids, const std::string& id ) { // Try to be smart: If the node ID can be converted into the // vertex type, we use the converted number instead. try { auto convertedID = std::stoll( id ); return static_cast<std::size_t>( convertedID ); } catch( std::out_of_range& e ) { throw; } catch( std::invalid_argument& ) { return static_cast<std::size_t>( std::distance( ids.begin(), ids.find( id ) ) ); } }; /** Describes a parsed graph along with all of its attributes */ struct Graph { std::map<std::string, std::string> dict; // all remaining attributes }; /** Describes a parsed node along with all of its attributes */ struct Node { std::string id; std::map<std::string, std::string> dict; // all remaining attributes }; /** Describes a parsed edge along with all of its attributes */ struct Edge { std::string source; std::string target; std::map<std::string, std::string> dict; // all remaining attributes }; // Local storage ----------------------------------------------------- // // Variables in this section contain the result of the last parsing // process. This is useful when clients are querying attributes. Graph _graph; std::vector<Node> _nodes; std::vector<Edge> _edges; }; /** @class GMLWriter @brief Writes files in GML (Graph Modeling Language) format This is a simple writer for graphs in GML format. It suports a basic subset of the GML specification, viz. the specification of different attributes for nodes, as well as weight specifications for edges. Given a simplicial complex, it will store it as a weighted graph. Currently, the following attributes will be written: * \c id (for nodes) * \c source (for edges) * \c target (for edges) * \c weight (for edges) */ class GMLWriter { public: template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K ) { std::ofstream out( filename ); if( !out ) throw std::runtime_error( "Unable to open output file" ); this->operator()( out, K ); } template <class SimplicialComplex> void operator()( std::ostream& out, SimplicialComplex& K ) { std::ostringstream streamNodes; std::ostringstream streamEdges; for( auto&& simplex : K ) { if( simplex.dimension() == 0 ) { streamNodes << " node [\n" << " id " << *simplex.begin() << "\n" << " ]\n"; } else if( simplex.dimension() == 1 ) { auto u = *( simplex.begin() ); auto v = *( simplex.begin() + 1 ); streamEdges << " edge [\n" << " source " << u << "\n" << " target " << v << "\n" << " weight " << simplex.data() << "\n" << " ]\n"; } } out << "graph [\n" << " directed 0\n" << streamNodes.str() << "\n" << streamEdges.str() << "\n" << "]\n"; } }; } // namespace io } // namespace topology } // namespace aleph #endif <|endoftext|>
<commit_before>#pragma once #include <stdlib.h> // aligned_alloc & free #include <stdint.h> // uintptr_t #include <cstring> // std::memset #include <stdexcept> // std::runtime_error #include "anyode/anyode_blas_lapack.hpp" namespace AnyODE { template<typename T> constexpr std::size_t n_padded(std::size_t n, int alignment_bytes){ return ((n*sizeof(T) + alignment_bytes - 1) & ~(alignment_bytes - 1)) / sizeof(T); } static constexpr int alignment_bytes_ = 64; // L1 cache line template<typename Real_t> class MatrixBase; template<typename Real_t> class MatrixBase { void * m_array_ = nullptr; bool m_own_array_ = false; Real_t * alloc_array_(int n){ m_array_ = aligned_alloc(alignment_bytes_, sizeof(Real_t)*n); m_own_array_ = true; return static_cast<Real_t *>(m_array_); } public: Real_t * m_data; int m_nr, m_nc, m_ld, m_ndata; bool m_own_data; MatrixBase(Real_t * const data, int nr, int nc, int ld, int ndata, bool own_data=false) : m_data(data ? data : alloc_array_(ndata)), m_nr(nr), m_nc(nc), m_ld(ld), m_ndata(ndata), m_own_data(own_data) { if (data == nullptr and own_data) throw std::runtime_error("Cannot own a nullptr"); } MatrixBase(const MatrixBase<Real_t>& ori) : MatrixBase(nullptr, ori.m_nr, ori.m_nc, ori.m_ld, ori.m_ndata) { std::copy(ori.m_data, ori.m_data + m_ndata, m_data); } virtual ~MatrixBase(){ if (m_own_array_ and m_array_) free(m_array_); if (m_own_data and m_data) free(m_data); } virtual Real_t& operator()(int /* ri */, int /* ci */) { throw std::runtime_error("Not implemented."); }; const Real_t& operator()(int ri, int ci) const { return (*const_cast<MatrixBase<Real_t>* >(this))(ri, ci); } virtual bool valid_index(const int ri, const int ci) const { return (0 <= ri) and (ri < this->m_nr) and (0 <= ci) and (ci < this->m_nc); } virtual bool guaranteed_zero_index(int /* ri */, int /* ci */) const { throw std::runtime_error("Not implemented."); }; virtual void dot_vec(const Real_t * const, Real_t * const) { throw std::runtime_error("Not implemented."); }; virtual void set_to_eye_plus_scaled_mtx(Real_t, const MatrixBase&) { throw std::runtime_error("Not implemented."); }; void set_to(Real_t value) noexcept { std::memset(m_data, value, m_ndata*sizeof(Real_t)); } }; template<typename Real_t = double> struct DenseMatrix : public MatrixBase<Real_t> { bool m_colmaj; DenseMatrix(Real_t * const data, int nr, int nc, int ld, bool colmaj=true, bool own_data=false) : MatrixBase<Real_t>(data, nr, nc, ld, ld*(colmaj ? nc : nr), own_data), m_colmaj(colmaj) {} DenseMatrix(const DenseMatrix<Real_t>& ori) : MatrixBase<Real_t>(ori), m_colmaj(ori.m_colmaj) {} DenseMatrix(const MatrixBase<Real_t>& source) : MatrixBase<Real_t>(nullptr, source.m_nr, source.m_nc, source.m_nr, source.m_nr*source.m_nc), m_colmaj(true) { for (int imaj = 0; imaj < (m_colmaj ? this->m_nc : this->m_nr); ++imaj){ for (int imin = 0; imin < (m_colmaj ? this->m_nr : this->m_nc); ++imin){ const int ri = m_colmaj ? imin : imaj; const int ci = m_colmaj ? imaj : imin; this->m_data[this->m_ld*imaj + imin] = source(ri, ci); } } } Real_t& operator()(int ri, int ci) noexcept override final { const int imaj = m_colmaj ? ci : ri; const int imin = m_colmaj ? ri : ci; return this->m_data[imaj*this->m_ld + imin]; } virtual bool guaranteed_zero_index(const int /* ri */, const int /* ci */) const override { return false; } void dot_vec(const Real_t * const vec, Real_t * const out) override final { Real_t alpha=1, beta=0; int inc=1; char trans= m_colmaj ? 'N' : 'T'; int sundials_dummy = 0; constexpr gemv_callback<Real_t> gemv{}; gemv(&trans, &(this->m_nr), &(this->m_nc), &alpha, this->m_data, &(this->m_ld), const_cast<Real_t *>(vec), &inc, &beta, out, &inc, sundials_dummy); } void set_to_eye_plus_scaled_mtx(Real_t scale, const MatrixBase<Real_t>& source) override final { for (int imaj = 0; imaj < (m_colmaj ? this->m_nc : this->m_nr); ++imaj){ for (int imin = 0; imin < (m_colmaj ? this->m_nr : this->m_nc); ++imin){ const int ri = m_colmaj ? imin : imaj; const int ci = m_colmaj ? imaj : imin; this->m_data[this->m_ld*imaj + imin] = scale*source(ri, ci) + ((imaj == imin) ? 1 : 0); } } } }; constexpr int banded_padded_ld(int kl, int ku) { return 2*kl+ku+1; } template<typename Real_t = double> struct BandedMatrix : public MatrixBase<Real_t> { int m_kl, m_ku; static constexpr bool m_colmaj = true; // dgbmv takes a trans arg, but not used at the moment. #define LD (ld ? ld : banded_padded_ld(kl, ku)) BandedMatrix(Real_t * const data, int nr, int nc, int kl, int ku, int ld=0, bool own_data=false) : MatrixBase<Real_t>(data, nr, nc, LD, LD*nc, own_data), m_kl(kl), m_ku(ku) {} void read(const MatrixBase<Real_t>& source){ for (int ci = 0; ci < this->m_nc; ++ci){ for (int ri = std::max(0, ci-m_ku); ri < std::min(this->m_nr, ci+m_kl+1); ++ri){ (*this)(ri, ci) = (source.guaranteed_zero_index(ri, ci)) ? 0 : source(ri, ci); } } } BandedMatrix(const MatrixBase<Real_t>& source, int kl, int ku, int ld=0) : MatrixBase<Real_t>(nullptr, source.m_nr, source.m_nc, LD, LD*source.m_nc), m_kl(kl), m_ku(ku) { read(source); } #undef LD BandedMatrix(const BandedMatrix<Real_t>& ori) : MatrixBase<Real_t>(ori), m_kl(ori.m_kl), m_ku(ori.m_ku) {} Real_t& operator()(int ri, int ci) noexcept override final { return this->m_data[m_kl + m_ku + ri - ci + ci*this->m_ld]; // m_kl paddding } virtual bool guaranteed_zero_index(const int ri, const int ci) const override { const int delta = ri - ci; return (this->m_ku < delta) or (delta < -(this->m_kl)); } void dot_vec(const Real_t * const vec, Real_t * const out) override final { Real_t alpha=1, beta=0; int inc=1; const char trans='N'; int sundials_dummy = 0; constexpr gbmv_callback<Real_t> gbmv{}; gbmv(&trans, &(this->m_nr), &(this->m_nc), &(m_kl), &(m_ku), &alpha, this->m_data+m_kl, // m_kl padding &(this->m_ld), const_cast<Real_t *>(vec), &inc, &beta, out, &inc, sundials_dummy); } void set_to_eye_plus_scaled_mtx(Real_t scale, const MatrixBase<Real_t>& source) override final { for (int ci = 0; ci < this->m_nc; ++ci) for (int ri = std::max(0, ci-m_ku); ri < std::min(this->m_nr, ci+m_kl+1); ++ri) (*this)(ri, ci) = scale*source(ri, ci) + ((ri == ci) ? 1 : 0); } }; } <commit_msg>Remove trailing extra semi-colon<commit_after>#pragma once #include <stdlib.h> // aligned_alloc & free #include <stdint.h> // uintptr_t #include <cstring> // std::memset #include <stdexcept> // std::runtime_error #include "anyode/anyode_blas_lapack.hpp" namespace AnyODE { template<typename T> constexpr std::size_t n_padded(std::size_t n, int alignment_bytes){ return ((n*sizeof(T) + alignment_bytes - 1) & ~(alignment_bytes - 1)) / sizeof(T); } static constexpr int alignment_bytes_ = 64; // L1 cache line template<typename Real_t> class MatrixBase; template<typename Real_t> class MatrixBase { void * m_array_ = nullptr; bool m_own_array_ = false; Real_t * alloc_array_(int n){ m_array_ = aligned_alloc(alignment_bytes_, sizeof(Real_t)*n); m_own_array_ = true; return static_cast<Real_t *>(m_array_); } public: Real_t * m_data; int m_nr, m_nc, m_ld, m_ndata; bool m_own_data; MatrixBase(Real_t * const data, int nr, int nc, int ld, int ndata, bool own_data=false) : m_data(data ? data : alloc_array_(ndata)), m_nr(nr), m_nc(nc), m_ld(ld), m_ndata(ndata), m_own_data(own_data) { if (data == nullptr and own_data) throw std::runtime_error("Cannot own a nullptr"); } MatrixBase(const MatrixBase<Real_t>& ori) : MatrixBase(nullptr, ori.m_nr, ori.m_nc, ori.m_ld, ori.m_ndata) { std::copy(ori.m_data, ori.m_data + m_ndata, m_data); } virtual ~MatrixBase(){ if (m_own_array_ and m_array_) free(m_array_); if (m_own_data and m_data) free(m_data); } virtual Real_t& operator()(int /* ri */, int /* ci */) { throw std::runtime_error("Not implemented."); } const Real_t& operator()(int ri, int ci) const { return (*const_cast<MatrixBase<Real_t>* >(this))(ri, ci); } virtual bool valid_index(const int ri, const int ci) const { return (0 <= ri) and (ri < this->m_nr) and (0 <= ci) and (ci < this->m_nc); } virtual bool guaranteed_zero_index(int /* ri */, int /* ci */) const { throw std::runtime_error("Not implemented."); }; virtual void dot_vec(const Real_t * const, Real_t * const) { throw std::runtime_error("Not implemented."); }; virtual void set_to_eye_plus_scaled_mtx(Real_t, const MatrixBase&) { throw std::runtime_error("Not implemented."); }; void set_to(Real_t value) noexcept { std::memset(m_data, value, m_ndata*sizeof(Real_t)); } }; template<typename Real_t = double> struct DenseMatrix : public MatrixBase<Real_t> { bool m_colmaj; DenseMatrix(Real_t * const data, int nr, int nc, int ld, bool colmaj=true, bool own_data=false) : MatrixBase<Real_t>(data, nr, nc, ld, ld*(colmaj ? nc : nr), own_data), m_colmaj(colmaj) {} DenseMatrix(const DenseMatrix<Real_t>& ori) : MatrixBase<Real_t>(ori), m_colmaj(ori.m_colmaj) {} DenseMatrix(const MatrixBase<Real_t>& source) : MatrixBase<Real_t>(nullptr, source.m_nr, source.m_nc, source.m_nr, source.m_nr*source.m_nc), m_colmaj(true) { for (int imaj = 0; imaj < (m_colmaj ? this->m_nc : this->m_nr); ++imaj){ for (int imin = 0; imin < (m_colmaj ? this->m_nr : this->m_nc); ++imin){ const int ri = m_colmaj ? imin : imaj; const int ci = m_colmaj ? imaj : imin; this->m_data[this->m_ld*imaj + imin] = source(ri, ci); } } } Real_t& operator()(int ri, int ci) noexcept override final { const int imaj = m_colmaj ? ci : ri; const int imin = m_colmaj ? ri : ci; return this->m_data[imaj*this->m_ld + imin]; } virtual bool guaranteed_zero_index(const int /* ri */, const int /* ci */) const override { return false; } void dot_vec(const Real_t * const vec, Real_t * const out) override final { Real_t alpha=1, beta=0; int inc=1; char trans= m_colmaj ? 'N' : 'T'; int sundials_dummy = 0; constexpr gemv_callback<Real_t> gemv{}; gemv(&trans, &(this->m_nr), &(this->m_nc), &alpha, this->m_data, &(this->m_ld), const_cast<Real_t *>(vec), &inc, &beta, out, &inc, sundials_dummy); } void set_to_eye_plus_scaled_mtx(Real_t scale, const MatrixBase<Real_t>& source) override final { for (int imaj = 0; imaj < (m_colmaj ? this->m_nc : this->m_nr); ++imaj){ for (int imin = 0; imin < (m_colmaj ? this->m_nr : this->m_nc); ++imin){ const int ri = m_colmaj ? imin : imaj; const int ci = m_colmaj ? imaj : imin; this->m_data[this->m_ld*imaj + imin] = scale*source(ri, ci) + ((imaj == imin) ? 1 : 0); } } } }; constexpr int banded_padded_ld(int kl, int ku) { return 2*kl+ku+1; } template<typename Real_t = double> struct BandedMatrix : public MatrixBase<Real_t> { int m_kl, m_ku; static constexpr bool m_colmaj = true; // dgbmv takes a trans arg, but not used at the moment. #define LD (ld ? ld : banded_padded_ld(kl, ku)) BandedMatrix(Real_t * const data, int nr, int nc, int kl, int ku, int ld=0, bool own_data=false) : MatrixBase<Real_t>(data, nr, nc, LD, LD*nc, own_data), m_kl(kl), m_ku(ku) {} void read(const MatrixBase<Real_t>& source){ for (int ci = 0; ci < this->m_nc; ++ci){ for (int ri = std::max(0, ci-m_ku); ri < std::min(this->m_nr, ci+m_kl+1); ++ri){ (*this)(ri, ci) = (source.guaranteed_zero_index(ri, ci)) ? 0 : source(ri, ci); } } } BandedMatrix(const MatrixBase<Real_t>& source, int kl, int ku, int ld=0) : MatrixBase<Real_t>(nullptr, source.m_nr, source.m_nc, LD, LD*source.m_nc), m_kl(kl), m_ku(ku) { read(source); } #undef LD BandedMatrix(const BandedMatrix<Real_t>& ori) : MatrixBase<Real_t>(ori), m_kl(ori.m_kl), m_ku(ori.m_ku) {} Real_t& operator()(int ri, int ci) noexcept override final { return this->m_data[m_kl + m_ku + ri - ci + ci*this->m_ld]; // m_kl paddding } virtual bool guaranteed_zero_index(const int ri, const int ci) const override { const int delta = ri - ci; return (this->m_ku < delta) or (delta < -(this->m_kl)); } void dot_vec(const Real_t * const vec, Real_t * const out) override final { Real_t alpha=1, beta=0; int inc=1; const char trans='N'; int sundials_dummy = 0; constexpr gbmv_callback<Real_t> gbmv{}; gbmv(&trans, &(this->m_nr), &(this->m_nc), &(m_kl), &(m_ku), &alpha, this->m_data+m_kl, // m_kl padding &(this->m_ld), const_cast<Real_t *>(vec), &inc, &beta, out, &inc, sundials_dummy); } void set_to_eye_plus_scaled_mtx(Real_t scale, const MatrixBase<Real_t>& source) override final { for (int ci = 0; ci < this->m_nc; ++ci) for (int ri = std::max(0, ci-m_ku); ri < std::min(this->m_nr, ci+m_kl+1); ++ri) (*this)(ri, ci) = scale*source(ri, ci) + ((ri == ci) ? 1 : 0); } }; } <|endoftext|>
<commit_before>/** * \file * \brief ContiguousRange template class header. * * \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef ESTD_CONTIGUOUSRANGE_HPP_ #define ESTD_CONTIGUOUSRANGE_HPP_ #include <array> namespace estd { /** * \brief ContiguousRange template class is a pair of iterators to contiguous sequence of elements in memory * * \tparam T is the type of data in the range */ template<typename T> class ContiguousRange { public: /// value_type type using value_type = T; /// pointer type using pointer = value_type*; /// const_pointer type using const_pointer = const value_type*; /// reference type using reference = value_type&; /// const_reference type using const_reference = const value_type&; /// iterator type using iterator = value_type*; /// const_iterator type using const_iterator = const value_type*; /// size_type type using size_type = std::size_t; /// difference_type type using difference_type = std::ptrdiff_t; /// reverse_iterator type using reverse_iterator = std::reverse_iterator<iterator>; /// const_reverse_iterator type using const_reverse_iterator = std::reverse_iterator<const_iterator>; /** * \brief ContiguousRange's constructor. * * \param [in] beginn is an iterator to first element in the range * \param [in] endd is an iterator to "one past the last" element in the range */ constexpr ContiguousRange(const iterator beginn, const iterator endd) noexcept : begin_{beginn}, end_{endd} { } /** * \brief Empty ContiguousRange's constructor. */ constexpr explicit ContiguousRange() noexcept : ContiguousRange{nullptr, nullptr} { } /** * \brief ContiguousRange's constructor using C-style array. * * \tparam N is the number of elements in the array * * \param [in] array is the array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(T (& array)[N]) noexcept : ContiguousRange{array, array + N} { } /** * \brief ContiguousRange's constructor using std::array. * * \tparam N is the number of elements in the array * * \param [in] array is the array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(std::array<T, N>& array) noexcept : ContiguousRange{array.begin(), array.end()} { } /** * \brief ContiguousRange's constructor using const std::array. * * \tparam N is the number of elements in the array * * \param [in] array is the const array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(const std::array<typename std::remove_const<T>::type, N>& array) noexcept : ContiguousRange{array.begin(), array.end()} { } /** * \brief ContiguousRange's constructor using single value * * \param [in] value is a reference to variable used to initialize the range */ constexpr explicit ContiguousRange(T& value) noexcept : ContiguousRange{&value, &value + 1} { } /** * \brief ContiguousRange's converting constructor * * This constructor is enabled only if \a T is \a const. It can be used to convert non-const range to const range. * * \param [in] other is a reference to source of conversion */ template<typename TT = T, typename = typename std::enable_if<std::is_const<TT>::value == true>::type> constexpr explicit ContiguousRange(const ContiguousRange<typename std::remove_const<TT>::type>& other) noexcept : ContiguousRange{other.begin(), other.end()} { } /** * \brief ContiguousRange's subscript operator * * \param [in] i is the index of element that will be accessed * * \return reference to element at given index */ reference operator[](const size_type i) const noexcept { return begin_[i]; } /** * \return iterator to first element in the range */ constexpr iterator begin() const noexcept { return begin_; } /** * \return const_iterator to first element in the range */ constexpr const_iterator cbegin() const noexcept { return begin(); } /** * \return const_iterator to "one past the last" element in the range */ constexpr const_iterator cend() const noexcept { return end(); } /** * \return const_reverse_iterator to first element in the reversed range (last element of the non-reversed range) */ constexpr const_reverse_iterator crbegin() const noexcept { return rbegin(); } /** * \return const_reverse_iterator to "one past the last" element in the reversed range ("one before the first" * element of the non-reversed range) */ constexpr const_reverse_iterator crend() const noexcept { return rend(); } /** * \return iterator to "one past the last" element in the range */ constexpr iterator end() const noexcept { return end_; } /** * \return reverse_iterator to first element in the reversed range (last element of the non-reversed range) */ constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; } /** * \return reverse_iterator to "one past the last" element in the reversed range ("one before the first" element of * the non-reversed range) */ constexpr reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; } /** * \return number of elements in the range */ constexpr size_type size() const noexcept { return end_ - begin_; } private: /// iterator to first element in the range iterator begin_; /// iterator to "one past the last" element in the range iterator end_; }; } // namespace estd #endif // ESTD_CONTIGUOUSRANGE_HPP_ <commit_msg>Remove "explicit" from default constructor of ContiguousRange<commit_after>/** * \file * \brief ContiguousRange template class header. * * \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef ESTD_CONTIGUOUSRANGE_HPP_ #define ESTD_CONTIGUOUSRANGE_HPP_ #include <array> namespace estd { /** * \brief ContiguousRange template class is a pair of iterators to contiguous sequence of elements in memory * * \tparam T is the type of data in the range */ template<typename T> class ContiguousRange { public: /// value_type type using value_type = T; /// pointer type using pointer = value_type*; /// const_pointer type using const_pointer = const value_type*; /// reference type using reference = value_type&; /// const_reference type using const_reference = const value_type&; /// iterator type using iterator = value_type*; /// const_iterator type using const_iterator = const value_type*; /// size_type type using size_type = std::size_t; /// difference_type type using difference_type = std::ptrdiff_t; /// reverse_iterator type using reverse_iterator = std::reverse_iterator<iterator>; /// const_reverse_iterator type using const_reverse_iterator = std::reverse_iterator<const_iterator>; /** * \brief ContiguousRange's constructor. * * \param [in] beginn is an iterator to first element in the range * \param [in] endd is an iterator to "one past the last" element in the range */ constexpr ContiguousRange(const iterator beginn, const iterator endd) noexcept : begin_{beginn}, end_{endd} { } /** * \brief Empty ContiguousRange's constructor. */ constexpr ContiguousRange() noexcept : ContiguousRange{nullptr, nullptr} { } /** * \brief ContiguousRange's constructor using C-style array. * * \tparam N is the number of elements in the array * * \param [in] array is the array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(T (& array)[N]) noexcept : ContiguousRange{array, array + N} { } /** * \brief ContiguousRange's constructor using std::array. * * \tparam N is the number of elements in the array * * \param [in] array is the array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(std::array<T, N>& array) noexcept : ContiguousRange{array.begin(), array.end()} { } /** * \brief ContiguousRange's constructor using const std::array. * * \tparam N is the number of elements in the array * * \param [in] array is the const array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(const std::array<typename std::remove_const<T>::type, N>& array) noexcept : ContiguousRange{array.begin(), array.end()} { } /** * \brief ContiguousRange's constructor using single value * * \param [in] value is a reference to variable used to initialize the range */ constexpr explicit ContiguousRange(T& value) noexcept : ContiguousRange{&value, &value + 1} { } /** * \brief ContiguousRange's converting constructor * * This constructor is enabled only if \a T is \a const. It can be used to convert non-const range to const range. * * \param [in] other is a reference to source of conversion */ template<typename TT = T, typename = typename std::enable_if<std::is_const<TT>::value == true>::type> constexpr explicit ContiguousRange(const ContiguousRange<typename std::remove_const<TT>::type>& other) noexcept : ContiguousRange{other.begin(), other.end()} { } /** * \brief ContiguousRange's subscript operator * * \param [in] i is the index of element that will be accessed * * \return reference to element at given index */ reference operator[](const size_type i) const noexcept { return begin_[i]; } /** * \return iterator to first element in the range */ constexpr iterator begin() const noexcept { return begin_; } /** * \return const_iterator to first element in the range */ constexpr const_iterator cbegin() const noexcept { return begin(); } /** * \return const_iterator to "one past the last" element in the range */ constexpr const_iterator cend() const noexcept { return end(); } /** * \return const_reverse_iterator to first element in the reversed range (last element of the non-reversed range) */ constexpr const_reverse_iterator crbegin() const noexcept { return rbegin(); } /** * \return const_reverse_iterator to "one past the last" element in the reversed range ("one before the first" * element of the non-reversed range) */ constexpr const_reverse_iterator crend() const noexcept { return rend(); } /** * \return iterator to "one past the last" element in the range */ constexpr iterator end() const noexcept { return end_; } /** * \return reverse_iterator to first element in the reversed range (last element of the non-reversed range) */ constexpr reverse_iterator rbegin() const noexcept { return reverse_iterator{end()}; } /** * \return reverse_iterator to "one past the last" element in the reversed range ("one before the first" element of * the non-reversed range) */ constexpr reverse_iterator rend() const noexcept { return reverse_iterator{begin()}; } /** * \return number of elements in the range */ constexpr size_type size() const noexcept { return end_ - begin_; } private: /// iterator to first element in the range iterator begin_; /// iterator to "one past the last" element in the range iterator end_; }; } // namespace estd #endif // ESTD_CONTIGUOUSRANGE_HPP_ <|endoftext|>
<commit_before>#pragma once #include <memory> #include <type_traits> #include "function_traits.hpp" namespace kgr { namespace detail { using type_id_t = void(*)(); template <typename T> void type_id() {} enum class enabler {}; constexpr enabler null = {}; template <bool b, typename T> using enable_if_t = typename std::enable_if<b, T>::type; template<int ...> struct seq {}; template<int n, int ...S> struct seq_gen : seq_gen<n-1, n-1, S...> {}; template<int ...S> struct seq_gen<0, S...> { using type = seq<S...>; }; template<typename T> struct has_invoke { private: template<typename C> static std::true_type test(typename C::invoke*); template<typename C> static std::false_type test(...); public: constexpr static bool value = decltype(test<T>(nullptr))::value; }; template<typename T> struct has_overrides { private: template<typename C> static std::true_type test(typename C::ParentTypes*); template<typename C> static std::false_type test(...); public: constexpr static bool value = decltype(test<T>(nullptr))::value; }; template<typename T> struct has_next { private: template<typename C> static std::true_type test(typename C::Next*); template<typename C> static std::false_type test(...); public: constexpr static bool value = decltype(test<T>(nullptr))::value; }; } // namespace detail template<typename T> using ServiceType = detail::function_result_t<decltype(&T::forward)>; } // namespace kgr <commit_msg>using void_t for sfinae<commit_after>#pragma once #include <memory> #include <type_traits> #include "function_traits.hpp" namespace kgr { namespace detail { template<typename...> using void_t = void; using type_id_t = void(*)(); template <typename T> void type_id() {} enum class enabler {}; constexpr enabler null = {}; template <bool b, typename T> using enable_if_t = typename std::enable_if<b, T>::type; template<int ...> struct seq {}; template<int n, int ...S> struct seq_gen : seq_gen<n-1, n-1, S...> {}; template<int ...S> struct seq_gen<0, S...> { using type = seq<S...>; }; template<typename T, typename = void> struct has_invoke : std::false_type {}; template<typename T> struct has_invoke<T, void_t<typename T::invoke>> : std::true_type {}; template<typename T, typename = void> struct has_overrides : std::false_type {}; template<typename T> struct has_overrides<T, void_t<typename T::Next>> : std::true_type {}; template<typename T, typename = void> struct has_next : std::false_type {}; template<typename T> struct has_next<T, void_t<typename T::Next>> : std::true_type {}; } // namespace detail template<typename T> using ServiceType = detail::function_result_t<decltype(&T::forward)>; } // namespace kgr <|endoftext|>
<commit_before>/* Copyright (c) 2006-2013, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_FILE_POOL_HPP #define TORRENT_FILE_POOL_HPP #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/intrusive_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include <map> #include "libtorrent/file.hpp" #include "libtorrent/ptime.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/file_storage.hpp" namespace libtorrent { // this is an internal cache of open file handles. It's primarily used by // storage_interface implementations. It provides semi weak guarantees of // not opening more file handles than specified. Given multiple threads, // each with the ability to lock a file handle (via smart pointer), there // may be windows where more file handles are open. struct TORRENT_EXPORT file_pool : boost::noncopyable { // ``size`` specifies the number of allowed files handles // to hold open at any given time. file_pool(int size = 40); ~file_pool(); // return an open file handle to file at ``file_index`` in the // file_storage ``fs`` opened at save path ``p``. ``m`` is the // file open mode (see file::open_mode_t). boost::intrusive_ptr<file> open_file(void* st, std::string const& p , int file_index, file_storage const& fs, int m, error_code& ec); // release all files belonging to the specified storage_interface (``st``) // the overload that takes ``file_index`` releases only the file with // that index in storage ``st``. void release(void* st); void release(void* st, int file_index); // update the allowed number of open file handles to ``size``. void resize(int size); // returns the current limit of number of allowed open file handles held // by the file_pool. int size_limit() const { return m_size; } // internal void set_low_prio_io(bool b) { m_low_prio_io = b; } private: void remove_oldest(); int m_size; bool m_low_prio_io; struct lru_file_entry { lru_file_entry(): key(0), last_use(time_now()), mode(0) {} mutable boost::intrusive_ptr<file> file_ptr; void* key; ptime last_use; int mode; }; // maps storage pointer, file index pairs to the // lru entry for the file typedef std::map<std::pair<void*, int>, lru_file_entry> file_set; file_set m_files; mutex m_mutex; #ifdef TORRENT_DEBUG int m_in_use; #endif #if TORRENT_CLOSE_MAY_BLOCK void closer_thread_fun(); mutex m_closer_mutex; std::vector<boost::intrusive_ptr<file> > m_queued_for_close; bool m_stop_thread; // used to close files thread m_closer_thread; #endif }; } #endif <commit_msg>fix release asserts build<commit_after>/* Copyright (c) 2006-2013, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_FILE_POOL_HPP #define TORRENT_FILE_POOL_HPP #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/intrusive_ptr.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include <map> #include "libtorrent/file.hpp" #include "libtorrent/ptime.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/file_storage.hpp" namespace libtorrent { // this is an internal cache of open file handles. It's primarily used by // storage_interface implementations. It provides semi weak guarantees of // not opening more file handles than specified. Given multiple threads, // each with the ability to lock a file handle (via smart pointer), there // may be windows where more file handles are open. struct TORRENT_EXPORT file_pool : boost::noncopyable { // ``size`` specifies the number of allowed files handles // to hold open at any given time. file_pool(int size = 40); ~file_pool(); // return an open file handle to file at ``file_index`` in the // file_storage ``fs`` opened at save path ``p``. ``m`` is the // file open mode (see file::open_mode_t). boost::intrusive_ptr<file> open_file(void* st, std::string const& p , int file_index, file_storage const& fs, int m, error_code& ec); // release all files belonging to the specified storage_interface (``st``) // the overload that takes ``file_index`` releases only the file with // that index in storage ``st``. void release(void* st); void release(void* st, int file_index); // update the allowed number of open file handles to ``size``. void resize(int size); // returns the current limit of number of allowed open file handles held // by the file_pool. int size_limit() const { return m_size; } // internal void set_low_prio_io(bool b) { m_low_prio_io = b; } private: void remove_oldest(); int m_size; bool m_low_prio_io; struct lru_file_entry { lru_file_entry(): key(0), last_use(time_now()), mode(0) {} mutable boost::intrusive_ptr<file> file_ptr; void* key; ptime last_use; int mode; }; // maps storage pointer, file index pairs to the // lru entry for the file typedef std::map<std::pair<void*, int>, lru_file_entry> file_set; file_set m_files; mutex m_mutex; #if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS int m_in_use; #endif #if TORRENT_CLOSE_MAY_BLOCK void closer_thread_fun(); mutex m_closer_mutex; std::vector<boost::intrusive_ptr<file> > m_queued_for_close; bool m_stop_thread; // used to close files thread m_closer_thread; #endif }; } #endif <|endoftext|>
<commit_before>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_XML_PARSE_HPP #define TORRENT_XML_PARSE_HPP #include <cctype> namespace libtorrent { enum { xml_start_tag, xml_end_tag, xml_empty_tag, xml_declaration_tag, xml_string, xml_attribute, xml_comment, xml_parse_error }; // callback(int type, char const* name, char const* val) // str2 is only used for attributes. name is element or attribute // name and val is attribute value template <class CallbackType> void xml_parse(char* p, char* end, CallbackType callback) { for(;p != end; ++p) { char const* start = p; char const* val_start = 0; int token; // look for tag start for(; *p != '<' && p != end; ++p); if (p != start) { if (p != end) { TORRENT_ASSERT(*p == '<'); *p = 0; } token = xml_string; callback(token, start, val_start); if (p != end) *p = '<'; } if (p == end) break; // skip '<' ++p; // parse the name of the tag. for (start = p; p != end && *p != '>' && !std::isspace(*p); ++p); char* tag_name_end = p; // skip the attributes for now for (; p != end && *p != '>'; ++p); // parse error if (p == end) { token = xml_parse_error; start = "unexpected end of file"; callback(token, start, val_start); break; } TORRENT_ASSERT(*p == '>'); // save the character that terminated the tag name // it could be both '>' and ' '. char save = *tag_name_end; *tag_name_end = 0; char* tag_end = p; if (*start == '/') { ++start; token = xml_end_tag; callback(token, start, val_start); } else if (*(p-1) == '/') { *(p-1) = 0; token = xml_empty_tag; callback(token, start, val_start); *(p-1) = '/'; tag_end = p - 1; } else if (*start == '?' && *(p-1) == '?') { *(p-1) = 0; ++start; token = xml_declaration_tag; callback(token, start, val_start); *(p-1) = '?'; tag_end = p - 1; } else if (start + 5 < p && std::memcmp(start, "!--", 3) == 0 && std::memcmp(p-2, "--", 2) == 0) { start += 3; *(p-2) = 0; token = xml_comment; callback(token, start, val_start); *(p-2) = '-'; tag_end = p - 2; } else { token = xml_start_tag; callback(token, start, val_start); } *tag_name_end = save; // parse attributes for (char* i = tag_name_end; i < tag_end; ++i) { // find start of attribute name for (; i != tag_end && std::isspace(*i); ++i); if (i == tag_end) break; start = i; // find end of attribute name for (; i != tag_end && *i != '=' && !std::isspace(*i); ++i); char* name_end = i; // look for equality sign for (; i != tag_end && *i != '='; ++i); if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "garbage inside element brackets"; callback(token, start, val_start); break; } ++i; for (; i != tag_end && std::isspace(*i); ++i); // check for parse error (values must be quoted) if (i == tag_end || (*i != '\'' && *i != '\"')) { token = xml_parse_error; val_start = 0; start = "unquoted attribute value"; callback(token, start, val_start); break; } char quote = *i; ++i; val_start = i; for (; i != tag_end && *i != quote; ++i); // parse error (missing end quote) if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "missing end quote on attribute"; callback(token, start, val_start); break; } save = *i; *i = 0; *name_end = 0; token = xml_attribute; callback(token, start, val_start); *name_end = '='; *i = save; } } } } #endif <commit_msg>replaced dependency on locale dependent isspace<commit_after>/* Copyright (c) 2007, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_XML_PARSE_HPP #define TORRENT_XML_PARSE_HPP #include <cctype> #include <cstring> namespace libtorrent { enum { xml_start_tag, xml_end_tag, xml_empty_tag, xml_declaration_tag, xml_string, xml_attribute, xml_comment, xml_parse_error }; inline bool isspace(char c) { const static char* ws = " \t\n\r\f\v"; return std::strchr(ws, c); } // callback(int type, char const* name, char const* val) // str2 is only used for attributes. name is element or attribute // name and val is attribute value template <class CallbackType> void xml_parse(char* p, char* end, CallbackType callback) { for(;p != end; ++p) { char const* start = p; char const* val_start = 0; int token; // look for tag start for(; *p != '<' && p != end; ++p); if (p != start) { if (p != end) { TORRENT_ASSERT(*p == '<'); *p = 0; } token = xml_string; callback(token, start, val_start); if (p != end) *p = '<'; } if (p == end) break; // skip '<' ++p; // parse the name of the tag. for (start = p; p != end && *p != '>' && !isspace(*p); ++p); char* tag_name_end = p; // skip the attributes for now for (; p != end && *p != '>'; ++p); // parse error if (p == end) { token = xml_parse_error; start = "unexpected end of file"; callback(token, start, val_start); break; } TORRENT_ASSERT(*p == '>'); // save the character that terminated the tag name // it could be both '>' and ' '. char save = *tag_name_end; *tag_name_end = 0; char* tag_end = p; if (*start == '/') { ++start; token = xml_end_tag; callback(token, start, val_start); } else if (*(p-1) == '/') { *(p-1) = 0; token = xml_empty_tag; callback(token, start, val_start); *(p-1) = '/'; tag_end = p - 1; } else if (*start == '?' && *(p-1) == '?') { *(p-1) = 0; ++start; token = xml_declaration_tag; callback(token, start, val_start); *(p-1) = '?'; tag_end = p - 1; } else if (start + 5 < p && std::memcmp(start, "!--", 3) == 0 && std::memcmp(p-2, "--", 2) == 0) { start += 3; *(p-2) = 0; token = xml_comment; callback(token, start, val_start); *(p-2) = '-'; tag_end = p - 2; } else { token = xml_start_tag; callback(token, start, val_start); } *tag_name_end = save; // parse attributes for (char* i = tag_name_end; i < tag_end; ++i) { // find start of attribute name for (; i != tag_end && isspace(*i); ++i); if (i == tag_end) break; start = i; // find end of attribute name for (; i != tag_end && *i != '=' && !isspace(*i); ++i); char* name_end = i; // look for equality sign for (; i != tag_end && *i != '='; ++i); if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "garbage inside element brackets"; callback(token, start, val_start); break; } ++i; for (; i != tag_end && isspace(*i); ++i); // check for parse error (values must be quoted) if (i == tag_end || (*i != '\'' && *i != '\"')) { token = xml_parse_error; val_start = 0; start = "unquoted attribute value"; callback(token, start, val_start); break; } char quote = *i; ++i; val_start = i; for (; i != tag_end && *i != quote; ++i); // parse error (missing end quote) if (i == tag_end) { token = xml_parse_error; val_start = 0; start = "missing end quote on attribute"; callback(token, start, val_start); break; } save = *i; *i = 0; *name_end = 0; token = xml_attribute; callback(token, start, val_start); *name_end = '='; *i = save; } } } } #endif <|endoftext|>
<commit_before>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com> #pragma once #include <vector> #include <cassert> #include <utility> #include <type_traits> #include "hadesmem/detail/warning_disable_prefix.hpp" #include <boost/preprocessor.hpp> #include "hadesmem/detail/warning_disable_suffix.hpp" #include <windows.h> #include "hadesmem/config.hpp" #include "hadesmem/detail/func_args.hpp" #include "hadesmem/detail/func_arity.hpp" #include "hadesmem/detail/union_cast.hpp" #include "hadesmem/detail/func_result.hpp" #include "hadesmem/detail/static_assert.hpp" namespace hadesmem { class Process; enum class CallConv { kDefault, kWinApi, kCdecl, kStdCall, kThisCall, kFastCall, kX64 }; template <typename T> class CallResult { public: HADESMEM_STATIC_ASSERT(std::is_integral<T>::value || std::is_pointer<T>::value || std::is_same<float, typename std::remove_cv<T>::type>::value || std::is_same<double, typename std::remove_cv<T>::type>::value); CallResult(T const& result, DWORD last_error) HADESMEM_NOEXCEPT : result_(result), last_error_(last_error) { } T GetReturnValue() const HADESMEM_NOEXCEPT { return result_; } DWORD GetLastError() const HADESMEM_NOEXCEPT { return last_error_; } private: T result_; DWORD last_error_; }; template <> class CallResult<void> { public: CallResult(DWORD last_error) HADESMEM_NOEXCEPT : last_error_(last_error) { } DWORD GetLastError() const HADESMEM_NOEXCEPT { return last_error_; } private: DWORD last_error_; }; class CallResultRaw { public: CallResultRaw(DWORD_PTR return_int_ptr, DWORD32 return_int_32, DWORD64 return_int_64, float return_float, double return_double, DWORD last_error) HADESMEM_NOEXCEPT; DWORD_PTR GetReturnValueIntPtr() const HADESMEM_NOEXCEPT; DWORD32 GetReturnValueInt32() const HADESMEM_NOEXCEPT; DWORD64 GetReturnValueInt64() const HADESMEM_NOEXCEPT; float GetReturnValueFloat() const HADESMEM_NOEXCEPT; double GetReturnValueDouble() const HADESMEM_NOEXCEPT; DWORD GetLastError() const HADESMEM_NOEXCEPT; template <typename T> T GetReturnValue() const HADESMEM_NOEXCEPT { HADESMEM_STATIC_ASSERT(std::is_integral<T>::value || std::is_pointer<T>::value || std::is_same<float, typename std::remove_cv<T>::type>::value || std::is_same<double, typename std::remove_cv<T>::type>::value); return GetReturnValueImpl(T()); } private: template <typename T> T GetReturnValueIntImpl(std::true_type) const HADESMEM_NOEXCEPT { return detail::UnionCast<T>(GetReturnValueInt64()); } template <typename T> T GetReturnValueIntImpl(std::false_type) const HADESMEM_NOEXCEPT { return detail::UnionCast<T>(GetReturnValueInt32()); } template <typename T> T GetReturnValueImpl(T /*t*/) const HADESMEM_NOEXCEPT { return GetReturnValueIntImpl<T>(std::integral_constant<bool, (sizeof(T) == sizeof(DWORD64))>()); } float GetReturnValueImpl(float /*t*/) const HADESMEM_NOEXCEPT { return GetReturnValueFloat(); } double GetReturnValueImpl(double /*t*/) const HADESMEM_NOEXCEPT { return GetReturnValueDouble(); } DWORD_PTR int_ptr_; DWORD32 int_32_; DWORD64 int_64_; float float_; double double_; DWORD last_error_; }; class CallArg { public: template <typename T> explicit CallArg(T t) HADESMEM_NOEXCEPT : arg_(), type_(ArgType::kInvalidType) { HADESMEM_STATIC_ASSERT(std::is_integral<T>::value || std::is_pointer<T>::value || std::is_same<float, typename std::remove_cv<T>::type>::value || std::is_same<double, typename std::remove_cv<T>::type>::value); Initialize(t); } template <typename V> void Visit(V* v) const { switch (type_) { case ArgType::kInvalidType: assert("Invalid type." && false); break; case ArgType::kInt32Type: (*v)(arg_.i32); break; case ArgType::kInt64Type: (*v)(arg_.i64); break; case ArgType::kFloatType: (*v)(arg_.f); break; case ArgType::kDoubleType: (*v)(arg_.d); break; } } private: template <typename T> void InitializeIntegralImpl(T t, std::false_type) HADESMEM_NOEXCEPT { type_ = ArgType::kInt32Type; arg_.i32 = detail::UnionCast<DWORD32>(t); } template <typename T> void InitializeIntegralImpl(T t, std::true_type) HADESMEM_NOEXCEPT { type_ = ArgType::kInt64Type; arg_.i64 = detail::UnionCast<DWORD64>(t); } template <typename T> void Initialize(T t) HADESMEM_NOEXCEPT { InitializeIntegralImpl(t, std::integral_constant<bool, (sizeof(T) == sizeof(DWORD64))>()); } void Initialize(float t) HADESMEM_NOEXCEPT { type_ = ArgType::kFloatType; arg_.f = t; } void Initialize(double t) HADESMEM_NOEXCEPT { type_ = ArgType::kDoubleType; arg_.d = t; } enum class ArgType { kInvalidType, kInt32Type, kInt64Type, kFloatType, kDoubleType }; union Arg { DWORD32 i32; DWORD64 i64; float f; double d; }; Arg arg_; ArgType type_; }; CallResultRaw Call(Process const& process, LPCVOID address, CallConv call_conv, std::vector<CallArg> const& args); std::vector<CallResultRaw> CallMulti(Process const& process, std::vector<LPCVOID> const& addresses, std::vector<CallConv> const& call_convs, std::vector<std::vector<CallArg>> const& args_full); namespace detail { template <typename T> CallResult<T> CallResultRawToCallResult(CallResultRaw const& result) HADESMEM_NOEXCEPT { return CallResult<T>(result.GetReturnValue<T>(), result.GetLastError()); } template <> inline CallResult<void> CallResultRawToCallResult(CallResultRaw const& result) HADESMEM_NOEXCEPT { return CallResult<void>(result.GetLastError()); } #if defined(HADESMEM_MSVC) #pragma warning(push) #pragma warning(disable: 4100) #endif // #if defined(HADESMEM_MSVC) template <typename FuncT, int N, typename T> void AddCallArg(std::vector<CallArg>* call_args, T&& arg) { typedef typename detail::FuncArgs<FuncT>::type FuncArgs; typedef typename std::tuple_element<N, FuncArgs>::type RealT; HADESMEM_STATIC_ASSERT(std::is_convertible<T, RealT>::value); RealT const real_arg(std::forward<T>(arg)); call_args->emplace_back(std::move(real_arg)); } #if defined(HADESMEM_MSVC) #pragma warning(pop) #endif // #if defined(HADESMEM_MSVC) } #ifndef HADESMEM_NO_VARIADIC_TEMPLATES namespace detail { template <typename FuncT, int N> inline void BuildCallArgs(std::vector<CallArg>* /*call_args*/) HADESMEM_NOEXCEPT { return; } template <typename FuncT, int N, typename T, typename... Args> void BuildCallArgs(std::vector<CallArg>* call_args, T&& arg, Args&&... args) { AddCallArg<FuncT, N>(call_args, std::forward<T>(arg)); return BuildCallArgs<FuncT, N + 1>(call_args, std::forward<Args>(args)...); } } template <typename FuncT, typename... Args> CallResult<typename detail::FuncResult<FuncT>::type> Call( Process const& process, LPCVOID address, CallConv call_conv, Args&&... args) { HADESMEM_STATIC_ASSERT(detail::FuncArity<FuncT>::value == sizeof...(args)); std::vector<CallArg> call_args; call_args.reserve(sizeof...(args)); detail::BuildCallArgs<FuncT, 0>(&call_args, args...); CallResultRaw const ret = Call(process, address, call_conv, call_args); typedef typename detail::FuncResult<FuncT>::type ResultT; return detail::CallResultRawToCallResult<ResultT>(ret); } #else // #ifndef HADESMEM_NO_VARIADIC_TEMPLATES #ifndef HADESMEM_CALL_MAX_ARGS #define HADESMEM_CALL_MAX_ARGS 10 #endif // #ifndef HADESMEM_CALL_MAX_ARGS HADESMEM_STATIC_ASSERT(HADESMEM_CALL_MAX_ARGS < BOOST_PP_LIMIT_REPEAT); HADESMEM_STATIC_ASSERT(HADESMEM_CALL_MAX_ARGS < BOOST_PP_LIMIT_ITERATION); #define HADESMEM_CALL_ADD_ARG(z, n, unused) \ detail::AddCallArg<FuncT, n>(&args, std::forward<T##n>(t##n)); #define BOOST_PP_LOCAL_MACRO(n)\ template <typename FuncT BOOST_PP_ENUM_TRAILING_PARAMS(n, typename T)>\ CallResult<typename detail::FuncResult<FuncT>::type> \ Call(Process const& process, LPCVOID address, CallConv call_conv \ BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n, T, && t))\ {\ HADESMEM_STATIC_ASSERT(detail::FuncArity<FuncT>::value == n);\ std::vector<CallArg> args;\ args.reserve(n);\ BOOST_PP_REPEAT(n, HADESMEM_CALL_ADD_ARG, ~)\ CallResultRaw const ret = Call(process, address, call_conv, args);\ typedef typename detail::FuncResult<FuncT>::type ResultT;\ return detail::CallResultRawToCallResult<ResultT>(ret);\ }\ #define BOOST_PP_LOCAL_LIMITS (0, HADESMEM_CALL_MAX_ARGS) #include BOOST_PP_LOCAL_ITERATE() #endif // #ifndef HADESMEM_NO_VARIADIC_TEMPLATES class MultiCall { public: explicit MultiCall(Process const* process); MultiCall(MultiCall const& other); MultiCall& operator=(MultiCall const& other); MultiCall(MultiCall&& other) HADESMEM_NOEXCEPT; MultiCall& operator=(MultiCall&& other) HADESMEM_NOEXCEPT; #ifndef HADESMEM_NO_VARIADIC_TEMPLATES template <typename FuncT, typename... Args> void Add(LPCVOID address, CallConv call_conv, Args&&... args) { HADESMEM_STATIC_ASSERT(detail::FuncArity<FuncT>::value == sizeof...(args)); std::vector<CallArg> call_args; call_args.reserve(sizeof...(args)); detail::BuildCallArgs<FuncT, 0>(&call_args, args...); addresses_.push_back(address); call_convs_.push_back(call_conv); args_.push_back(call_args); } #else // #ifndef HADESMEM_NO_VARIADIC_TEMPLATES #define BOOST_PP_LOCAL_MACRO(n)\ template <typename FuncT BOOST_PP_ENUM_TRAILING_PARAMS(n, typename T)>\ void Add(LPCVOID address, CallConv call_conv \ BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n, T, && t))\ {\ HADESMEM_STATIC_ASSERT(detail::FuncArity<FuncT>::value == n);\ std::vector<CallArg> args;\ args.reserve(n);\ BOOST_PP_REPEAT(n, HADESMEM_CALL_ADD_ARG, ~)\ addresses_.push_back(address);\ call_convs_.push_back(call_conv);\ args_.push_back(args);\ }\ #define BOOST_PP_LOCAL_LIMITS (0, HADESMEM_CALL_MAX_ARGS) #include BOOST_PP_LOCAL_ITERATE() #undef HADESMEM_CALL_ADD_ARG #endif // #ifndef HADESMEM_NO_VARIADIC_TEMPLATES std::vector<CallResultRaw> Call() const; private: Process const* process_; std::vector<LPCVOID> addresses_; std::vector<CallConv> call_convs_; std::vector<std::vector<CallArg>> args_; }; } <commit_msg>* Style fix.<commit_after>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <raptorfactor@raptorfactor.com> #pragma once #include <vector> #include <cassert> #include <utility> #include <type_traits> #include "hadesmem/detail/warning_disable_prefix.hpp" #include <boost/preprocessor.hpp> #include "hadesmem/detail/warning_disable_suffix.hpp" #include <windows.h> #include "hadesmem/config.hpp" #include "hadesmem/detail/func_args.hpp" #include "hadesmem/detail/func_arity.hpp" #include "hadesmem/detail/union_cast.hpp" #include "hadesmem/detail/func_result.hpp" #include "hadesmem/detail/static_assert.hpp" namespace hadesmem { class Process; enum class CallConv { kDefault, kWinApi, kCdecl, kStdCall, kThisCall, kFastCall, kX64 }; template <typename T> class CallResult { public: HADESMEM_STATIC_ASSERT(std::is_integral<T>::value || std::is_pointer<T>::value || std::is_same<float, typename std::remove_cv<T>::type>::value || std::is_same<double, typename std::remove_cv<T>::type>::value); CallResult(T const& result, DWORD last_error) HADESMEM_NOEXCEPT : result_(result), last_error_(last_error) { } T GetReturnValue() const HADESMEM_NOEXCEPT { return result_; } DWORD GetLastError() const HADESMEM_NOEXCEPT { return last_error_; } private: T result_; DWORD last_error_; }; template <> class CallResult<void> { public: CallResult(DWORD last_error) HADESMEM_NOEXCEPT : last_error_(last_error) { } DWORD GetLastError() const HADESMEM_NOEXCEPT { return last_error_; } private: DWORD last_error_; }; class CallResultRaw { public: CallResultRaw(DWORD_PTR return_int_ptr, DWORD32 return_int_32, DWORD64 return_int_64, float return_float, double return_double, DWORD last_error) HADESMEM_NOEXCEPT; DWORD_PTR GetReturnValueIntPtr() const HADESMEM_NOEXCEPT; DWORD32 GetReturnValueInt32() const HADESMEM_NOEXCEPT; DWORD64 GetReturnValueInt64() const HADESMEM_NOEXCEPT; float GetReturnValueFloat() const HADESMEM_NOEXCEPT; double GetReturnValueDouble() const HADESMEM_NOEXCEPT; DWORD GetLastError() const HADESMEM_NOEXCEPT; template <typename T> T GetReturnValue() const HADESMEM_NOEXCEPT { HADESMEM_STATIC_ASSERT(std::is_integral<T>::value || std::is_pointer<T>::value || std::is_same<float, typename std::remove_cv<T>::type>::value || std::is_same<double, typename std::remove_cv<T>::type>::value); return GetReturnValueImpl(T()); } private: template <typename T> T GetReturnValueIntImpl(std::true_type) const HADESMEM_NOEXCEPT { return detail::UnionCast<T>(GetReturnValueInt64()); } template <typename T> T GetReturnValueIntImpl(std::false_type) const HADESMEM_NOEXCEPT { return detail::UnionCast<T>(GetReturnValueInt32()); } template <typename T> T GetReturnValueImpl(T /*t*/) const HADESMEM_NOEXCEPT { return GetReturnValueIntImpl<T>(std::integral_constant<bool, (sizeof(T) == sizeof(DWORD64))>()); } float GetReturnValueImpl(float /*t*/) const HADESMEM_NOEXCEPT { return GetReturnValueFloat(); } double GetReturnValueImpl(double /*t*/) const HADESMEM_NOEXCEPT { return GetReturnValueDouble(); } DWORD_PTR int_ptr_; DWORD32 int_32_; DWORD64 int_64_; float float_; double double_; DWORD last_error_; }; class CallArg { public: template <typename T> explicit CallArg(T t) HADESMEM_NOEXCEPT : arg_(), type_(ArgType::kInvalidType) { HADESMEM_STATIC_ASSERT(std::is_integral<T>::value || std::is_pointer<T>::value || std::is_same<float, typename std::remove_cv<T>::type>::value || std::is_same<double, typename std::remove_cv<T>::type>::value); Initialize(t); } template <typename V> void Visit(V* v) const { switch (type_) { case ArgType::kInvalidType: assert("Invalid type." && false); break; case ArgType::kInt32Type: (*v)(arg_.i32); break; case ArgType::kInt64Type: (*v)(arg_.i64); break; case ArgType::kFloatType: (*v)(arg_.f); break; case ArgType::kDoubleType: (*v)(arg_.d); break; } } private: template <typename T> void InitializeIntegralImpl(T t, std::false_type) HADESMEM_NOEXCEPT { type_ = ArgType::kInt32Type; arg_.i32 = detail::UnionCast<DWORD32>(t); } template <typename T> void InitializeIntegralImpl(T t, std::true_type) HADESMEM_NOEXCEPT { type_ = ArgType::kInt64Type; arg_.i64 = detail::UnionCast<DWORD64>(t); } template <typename T> void Initialize(T t) HADESMEM_NOEXCEPT { InitializeIntegralImpl(t, std::integral_constant<bool, (sizeof(T) == sizeof(DWORD64))>()); } void Initialize(float t) HADESMEM_NOEXCEPT { type_ = ArgType::kFloatType; arg_.f = t; } void Initialize(double t) HADESMEM_NOEXCEPT { type_ = ArgType::kDoubleType; arg_.d = t; } enum class ArgType { kInvalidType, kInt32Type, kInt64Type, kFloatType, kDoubleType }; union Arg { DWORD32 i32; DWORD64 i64; float f; double d; }; Arg arg_; ArgType type_; }; CallResultRaw Call(Process const& process, LPCVOID address, CallConv call_conv, std::vector<CallArg> const& args); std::vector<CallResultRaw> CallMulti(Process const& process, std::vector<LPCVOID> const& addresses, std::vector<CallConv> const& call_convs, std::vector<std::vector<CallArg>> const& args_full); namespace detail { template <typename T> CallResult<T> CallResultRawToCallResult(CallResultRaw const& result) HADESMEM_NOEXCEPT { return CallResult<T>(result.GetReturnValue<T>(), result.GetLastError()); } template <> inline CallResult<void> CallResultRawToCallResult(CallResultRaw const& result) HADESMEM_NOEXCEPT { return CallResult<void>(result.GetLastError()); } #if defined(HADESMEM_MSVC) #pragma warning(push) #pragma warning(disable: 4100) #endif // #if defined(HADESMEM_MSVC) template <typename FuncT, int N, typename T> void AddCallArg(std::vector<CallArg>* call_args, T&& arg) { typedef typename detail::FuncArgs<FuncT>::type FuncArgs; typedef typename std::tuple_element<N, FuncArgs>::type RealT; HADESMEM_STATIC_ASSERT(std::is_convertible<T, RealT>::value); RealT const real_arg(std::forward<T>(arg)); call_args->emplace_back(std::move(real_arg)); } #if defined(HADESMEM_MSVC) #pragma warning(pop) #endif // #if defined(HADESMEM_MSVC) } #ifndef HADESMEM_NO_VARIADIC_TEMPLATES namespace detail { template <typename FuncT, int N> inline void BuildCallArgs(std::vector<CallArg>* /*call_args*/) HADESMEM_NOEXCEPT { return; } template <typename FuncT, int N, typename T, typename... Args> void BuildCallArgs(std::vector<CallArg>* call_args, T&& arg, Args&&... args) { AddCallArg<FuncT, N>(call_args, std::forward<T>(arg)); return BuildCallArgs<FuncT, N + 1>(call_args, std::forward<Args>(args)...); } } template <typename FuncT, typename... Args> CallResult<typename detail::FuncResult<FuncT>::type> Call( Process const& process, LPCVOID address, CallConv call_conv, Args&&... args) { HADESMEM_STATIC_ASSERT(detail::FuncArity<FuncT>::value == sizeof...(args)); std::vector<CallArg> call_args; call_args.reserve(sizeof...(args)); detail::BuildCallArgs<FuncT, 0>(&call_args, args...); CallResultRaw const ret = Call(process, address, call_conv, call_args); typedef typename detail::FuncResult<FuncT>::type ResultT; return detail::CallResultRawToCallResult<ResultT>(ret); } #else // #ifndef HADESMEM_NO_VARIADIC_TEMPLATES #ifndef HADESMEM_CALL_MAX_ARGS #define HADESMEM_CALL_MAX_ARGS 10 #endif // #ifndef HADESMEM_CALL_MAX_ARGS HADESMEM_STATIC_ASSERT(HADESMEM_CALL_MAX_ARGS < BOOST_PP_LIMIT_REPEAT); HADESMEM_STATIC_ASSERT(HADESMEM_CALL_MAX_ARGS < BOOST_PP_LIMIT_ITERATION); #define HADESMEM_CALL_ADD_ARG(z, n, unused) \ detail::AddCallArg<FuncT, n>(&args, std::forward<T##n>(t##n)); #define BOOST_PP_LOCAL_MACRO(n)\ template <typename FuncT BOOST_PP_ENUM_TRAILING_PARAMS(n, typename T)>\ CallResult<typename detail::FuncResult<FuncT>::type> \ Call(Process const& process, LPCVOID address, CallConv call_conv \ BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n, T, && t))\ {\ HADESMEM_STATIC_ASSERT(detail::FuncArity<FuncT>::value == n);\ std::vector<CallArg> args;\ args.reserve(n);\ BOOST_PP_REPEAT(n, HADESMEM_CALL_ADD_ARG, ~)\ CallResultRaw const ret = Call(process, address, call_conv, args);\ typedef typename detail::FuncResult<FuncT>::type ResultT;\ return detail::CallResultRawToCallResult<ResultT>(ret);\ }\ #define BOOST_PP_LOCAL_LIMITS (0, HADESMEM_CALL_MAX_ARGS) #include BOOST_PP_LOCAL_ITERATE() #endif // #ifndef HADESMEM_NO_VARIADIC_TEMPLATES class MultiCall { public: explicit MultiCall(Process const* process); MultiCall(MultiCall const& other); MultiCall& operator=(MultiCall const& other); MultiCall(MultiCall&& other) HADESMEM_NOEXCEPT; MultiCall& operator=(MultiCall&& other) HADESMEM_NOEXCEPT; #ifndef HADESMEM_NO_VARIADIC_TEMPLATES template <typename FuncT, typename... Args> void Add(LPCVOID address, CallConv call_conv, Args&&... args) { HADESMEM_STATIC_ASSERT(detail::FuncArity<FuncT>::value == sizeof...(args)); std::vector<CallArg> call_args; call_args.reserve(sizeof...(args)); detail::BuildCallArgs<FuncT, 0>(&call_args, args...); addresses_.push_back(address); call_convs_.push_back(call_conv); args_.push_back(call_args); } #else // #ifndef HADESMEM_NO_VARIADIC_TEMPLATES #define BOOST_PP_LOCAL_MACRO(n)\ template <typename FuncT BOOST_PP_ENUM_TRAILING_PARAMS(n, typename T)>\ void Add(LPCVOID address, CallConv call_conv \ BOOST_PP_ENUM_TRAILING_BINARY_PARAMS(n, T, && t))\ {\ HADESMEM_STATIC_ASSERT(detail::FuncArity<FuncT>::value == n);\ std::vector<CallArg> args;\ args.reserve(n);\ BOOST_PP_REPEAT(n, HADESMEM_CALL_ADD_ARG, ~)\ addresses_.push_back(address);\ call_convs_.push_back(call_conv);\ args_.push_back(args);\ }\ #define BOOST_PP_LOCAL_LIMITS (0, HADESMEM_CALL_MAX_ARGS) #include BOOST_PP_LOCAL_ITERATE() #undef HADESMEM_CALL_ADD_ARG #endif // #ifndef HADESMEM_NO_VARIADIC_TEMPLATES std::vector<CallResultRaw> Call() const; private: Process const* process_; std::vector<LPCVOID> addresses_; std::vector<CallConv> call_convs_; std::vector<std::vector<CallArg>> args_; }; } <|endoftext|>
<commit_before>#pragma once #ifndef OPENGM_ICM_HXX #define OPENGM_ICM_HXX #include <vector> #include <string> #include <iostream> #include "opengm/opengm.hxx" //#include "opengm/inference/visitors/visitor.hxx" #include "opengm/inference/inference.hxx" #include "opengm/inference/movemaker.hxx" #include "opengm/datastructures/buffer_vector.hxx" #include "opengm/inference/visitors/visitors.hxx" namespace opengm { /// \brief Iterated Conditional Modes Algorithm\n\n /// J. E. Besag, "On the Statistical Analysis of Dirty Pictures", Journal of the Royal Statistical Society, Series B 48(3):259-302, 1986 /// \ingroup inference template<class GM, class ACC> class ICM : public Inference<GM, ACC> { public: enum MoveType { SINGLE_VARIABLE = 0, FACTOR = 1 }; typedef ACC AccumulationType; typedef GM GraphicalModelType; OPENGM_GM_TYPE_TYPEDEFS; typedef Movemaker<GraphicalModelType> MovemakerType; typedef opengm::visitors::VerboseVisitor<ICM<GM,ACC> > VerboseVisitorType; typedef opengm::visitors::EmptyVisitor<ICM<GM,ACC> > EmptyVisitorType; typedef opengm::visitors::TimingVisitor<ICM<GM,ACC> > TimingVisitorType; class Parameter { public: Parameter( const std::vector<LabelType>& startPoint ) : moveType_(SINGLE_VARIABLE), startPoint_(startPoint) {} Parameter( MoveType moveType, const std::vector<LabelType>& startPoint ) : moveType_(moveType), startPoint_(startPoint) {} Parameter( MoveType moveType = SINGLE_VARIABLE ) : moveType_(moveType), startPoint_() {} MoveType moveType_; std::vector<LabelType> startPoint_; }; ICM(const GraphicalModelType&); ICM(const GraphicalModelType&, const Parameter&); std::string name() const; const GraphicalModelType& graphicalModel() const; InferenceTermination infer(); void reset(); template<class VisitorType> InferenceTermination infer(VisitorType&); void setStartingPoint(typename std::vector<LabelType>::const_iterator); virtual InferenceTermination arg(std::vector<LabelType>&, const size_t = 1) const ; virtual ValueType value()const{return movemaker_.value();} size_t currentMoveType() const; private: const GraphicalModelType& gm_; MovemakerType movemaker_; Parameter param_; MoveType currentMoveType_; }; template<class GM, class ACC> inline size_t ICM<GM, ACC>::currentMoveType()const{ return currentMoveType_==SINGLE_VARIABLE?0:1; } template<class GM, class ACC> inline ICM<GM, ACC>::ICM ( const GraphicalModelType& gm ) : gm_(gm), movemaker_(gm), param_(Parameter()), currentMoveType_(SINGLE_VARIABLE) { } template<class GM, class ACC> ICM<GM, ACC>::ICM ( const GraphicalModelType& gm, const Parameter& parameter ) : gm_(gm), movemaker_(gm), param_(parameter), currentMoveType_(SINGLE_VARIABLE) { if(parameter.startPoint_.size() == gm.numberOfVariables()) { movemaker_.initialize(parameter.startPoint_.begin() ); } else if(parameter.startPoint_.size() != 0) { throw RuntimeError("unsuitable starting point"); } } template<class GM, class ACC> inline void ICM<GM, ACC>::reset() { if(param_.startPoint_.size() == gm_.numberOfVariables()) { movemaker_.initialize(param_.startPoint_.begin() ); } else if(param_.startPoint_.size() != 0) { throw RuntimeError("unsuitable starting point"); } else{ movemaker_.reset(); } } template<class GM, class ACC> inline void ICM<GM,ACC>::setStartingPoint ( typename std::vector<typename ICM<GM,ACC>::LabelType>::const_iterator begin ) { movemaker_.initialize(begin); } template<class GM, class ACC> inline std::string ICM<GM, ACC>::name() const { return "ICM"; } template<class GM, class ACC> inline const typename ICM<GM, ACC>::GraphicalModelType& ICM<GM, ACC>::graphicalModel() const { return gm_; } template<class GM, class ACC> inline InferenceTermination ICM<GM,ACC>::infer() { EmptyVisitorType v; return infer(v); } template<class GM, class ACC> template<class VisitorType> InferenceTermination ICM<GM,ACC>::infer ( VisitorType& visitor ) { bool exitInf=false; visitor.begin(*this); if(param_.moveType_==SINGLE_VARIABLE ||param_.moveType_==FACTOR) { bool updates = true; std::vector<bool> isLocalOptimal(gm_.numberOfVariables()); std::vector<opengm::RandomAccessSet<IndexType> >variableAdjacencyList; gm_.variableAdjacencyList(variableAdjacencyList); size_t v=0,s=0,n=0; while(updates && exitInf==false) { updates = false; for(v=0; v<gm_.numberOfVariables() && exitInf==false; ++v) { if(isLocalOptimal[v]==false) { for(s=0; s<gm_.numberOfLabels(v); ++s) { if(s != movemaker_.state(v)) { if(AccumulationType::bop(movemaker_.valueAfterMove(&v, &v+1, &s), movemaker_.value())) { movemaker_.move(&v, &v+1, &s); for(n=0;n<variableAdjacencyList[v].size();++n) { isLocalOptimal[variableAdjacencyList[v][n]]=false; } updates = true; if( visitor(*this) != visitors::VisitorReturnFlag::ContinueInf ){ exitInf=true; break; } } } } isLocalOptimal[v]=true; } } } } if(param_.moveType_==FACTOR) { currentMoveType_=FACTOR; //visitor(*this, movemaker_.value(),movemaker_.value()); bool updates = true; std::vector<bool> isLocalOptimal(gm_.numberOfFactors(),false); //std::vector<opengm::RandomAccessSet<size_t> >variableAdjacencyList; opengm::BufferVector<LabelType> stateBuffer; stateBuffer.reserve(10); //gm_.factorAdjacencyList(variableAdjacencyList); size_t f=0,ff=0,v=0; while(updates && exitInf==false) { updates = false; for(f=0; f<gm_.numberOfFactors() && exitInf==false; ++f) { if(isLocalOptimal[f]==false && gm_[f].numberOfVariables()>1) { stateBuffer.clear(); stateBuffer.resize(gm_[f].numberOfVariables()); for(v=0;v<gm_[f].numberOfVariables();++v) { stateBuffer[v]=movemaker_.state(gm_[f].variableIndex(v)); } ValueType oldValue=movemaker_.value(); ValueType newValue=movemaker_. template moveOptimally<ACC>(gm_[f].variableIndicesBegin(),gm_[f].variableIndicesEnd()); if(ACC::bop(newValue,oldValue)) { updates = true ; if( visitor(*this) != visitors::VisitorReturnFlag::ContinueInf ){ exitInf=true; break; } for(v=0;v<gm_[f].numberOfVariables();++v) { const size_t varIndex=gm_[f].variableIndex(v); if(stateBuffer[v]!=movemaker_.state(varIndex)) { for(ff=0;ff<gm_.numberOfFactors(varIndex);++ff) { isLocalOptimal[gm_.factorOfVariable(varIndex,ff)]=false; } } } } isLocalOptimal[f]=true; } } } } visitor.end(*this); return NORMAL; } template<class GM, class ACC> inline InferenceTermination ICM<GM,ACC>::arg ( std::vector<LabelType>& x, const size_t N ) const { if(N==1) { x.resize(gm_.numberOfVariables()); for(size_t j=0; j<x.size(); ++j) { x[j] = movemaker_.state(j); } return NORMAL; } else { return UNKNOWN; } } } // namespace opengm #endif // #ifndef OPENGM_ICM_HXX <commit_msg>changed visitos to new interface (not yet all)<commit_after>#pragma once #ifndef OPENGM_ICM_HXX #define OPENGM_ICM_HXX #include <vector> #include <string> #include <iostream> #include "opengm/opengm.hxx" //#include "opengm/inference/visitors/visitor.hxx" #include "opengm/inference/inference.hxx" #include "opengm/inference/movemaker.hxx" #include "opengm/datastructures/buffer_vector.hxx" #include "opengm/inference/visitors/visitors.hxx" namespace opengm { /// \brief Iterated Conditional Modes Algorithm\n\n /// J. E. Besag, "On the Statistical Analysis of Dirty Pictures", Journal of the Royal Statistical Society, Series B 48(3):259-302, 1986 /// \ingroup inference template<class GM, class ACC> class ICM : public Inference<GM, ACC> { public: enum MoveType { SINGLE_VARIABLE = 0, FACTOR = 1 }; typedef ACC AccumulationType; typedef GM GraphicalModelType; OPENGM_GM_TYPE_TYPEDEFS; typedef Movemaker<GraphicalModelType> MovemakerType; typedef opengm::visitors::VerboseVisitor<ICM<GM,ACC> > VerboseVisitorType; typedef opengm::visitors::EmptyVisitor<ICM<GM,ACC> > EmptyVisitorType; typedef opengm::visitors::TimingVisitor<ICM<GM,ACC> > TimingVisitorType; class Parameter { public: Parameter( const std::vector<LabelType>& startPoint ) : moveType_(SINGLE_VARIABLE), startPoint_(startPoint) {} Parameter( MoveType moveType, const std::vector<LabelType>& startPoint ) : moveType_(moveType), startPoint_(startPoint) {} Parameter( MoveType moveType = SINGLE_VARIABLE ) : moveType_(moveType), startPoint_() {} MoveType moveType_; std::vector<LabelType> startPoint_; }; ICM(const GraphicalModelType&); ICM(const GraphicalModelType&, const Parameter&); std::string name() const; const GraphicalModelType& graphicalModel() const; InferenceTermination infer(); void reset(); template<class VisitorType> InferenceTermination infer(VisitorType&); void setStartingPoint(typename std::vector<LabelType>::const_iterator); virtual InferenceTermination arg(std::vector<LabelType>&, const size_t = 1) const ; virtual ValueType value()const{return movemaker_.value();} size_t currentMoveType() const; private: const GraphicalModelType& gm_; MovemakerType movemaker_; Parameter param_; MoveType currentMoveType_; }; template<class GM, class ACC> inline size_t ICM<GM, ACC>::currentMoveType()const{ return currentMoveType_==SINGLE_VARIABLE?0:1; } template<class GM, class ACC> inline ICM<GM, ACC>::ICM ( const GraphicalModelType& gm ) : gm_(gm), movemaker_(gm), param_(Parameter()), currentMoveType_(SINGLE_VARIABLE) { } template<class GM, class ACC> ICM<GM, ACC>::ICM ( const GraphicalModelType& gm, const Parameter& parameter ) : gm_(gm), movemaker_(gm), param_(parameter), currentMoveType_(SINGLE_VARIABLE) { if(parameter.startPoint_.size() == gm.numberOfVariables()) { movemaker_.initialize(parameter.startPoint_.begin() ); } else if(parameter.startPoint_.size() != 0) { throw RuntimeError("unsuitable starting point"); } } template<class GM, class ACC> inline void ICM<GM, ACC>::reset() { if(param_.startPoint_.size() == gm_.numberOfVariables()) { movemaker_.initialize(param_.startPoint_.begin() ); } else if(param_.startPoint_.size() != 0) { throw RuntimeError("unsuitable starting point"); } else{ movemaker_.reset(); } } template<class GM, class ACC> inline void ICM<GM,ACC>::setStartingPoint ( typename std::vector<typename ICM<GM,ACC>::LabelType>::const_iterator begin ) { movemaker_.initialize(begin); } template<class GM, class ACC> inline std::string ICM<GM, ACC>::name() const { return "ICM"; } template<class GM, class ACC> inline const typename ICM<GM, ACC>::GraphicalModelType& ICM<GM, ACC>::graphicalModel() const { return gm_; } template<class GM, class ACC> inline InferenceTermination ICM<GM,ACC>::infer() { EmptyVisitorType v; return infer(v); } template<class GM, class ACC> template<class VisitorType> InferenceTermination ICM<GM,ACC>::infer ( VisitorType& visitor ) { bool exitInf=false; visitor.begin(*this); if(param_.moveType_==SINGLE_VARIABLE ||param_.moveType_==FACTOR) { bool updates = true; std::vector<bool> isLocalOptimal(gm_.numberOfVariables()); std::vector<opengm::RandomAccessSet<IndexType> >variableAdjacencyList; gm_.variableAdjacencyList(variableAdjacencyList); size_t v=0,s=0,n=0; while(updates && exitInf==false) { updates = false; for(v=0; v<gm_.numberOfVariables() && exitInf==false; ++v) { if(isLocalOptimal[v]==false) { for(s=0; s<gm_.numberOfLabels(v); ++s) { if(s != movemaker_.state(v)) { if(AccumulationType::bop(movemaker_.valueAfterMove(&v, &v+1, &s), movemaker_.value())) { movemaker_.move(&v, &v+1, &s); for(n=0;n<variableAdjacencyList[v].size();++n) { isLocalOptimal[variableAdjacencyList[v][n]]=false; } updates = true; if( visitor(*this) != visitors::VisitorReturnFlag::ContinueInf ){ exitInf=true; break; } } } } isLocalOptimal[v]=true; } } } } if(param_.moveType_==FACTOR) { currentMoveType_=FACTOR; //visitor(*this, movemaker_.value(),movemaker_.value()); bool updates = true; std::vector<bool> isLocalOptimal(gm_.numberOfFactors(),false); //std::vector<opengm::RandomAccessSet<size_t> >variableAdjacencyList; opengm::BufferVector<LabelType> stateBuffer; stateBuffer.reserve(10); //gm_.factorAdjacencyList(variableAdjacencyList); size_t f=0,ff=0,v=0; while(updates && exitInf==false) { updates = false; for(f=0; f<gm_.numberOfFactors() && exitInf==false; ++f) { if(isLocalOptimal[f]==false && gm_[f].numberOfVariables()>1) { stateBuffer.clear(); stateBuffer.resize(gm_[f].numberOfVariables()); for(v=0;v<gm_[f].numberOfVariables();++v) { stateBuffer[v]=movemaker_.state(gm_[f].variableIndex(v)); } ValueType oldValue=movemaker_.value(); ValueType newValue=movemaker_. template moveOptimally<ACC>(gm_[f].variableIndicesBegin(),gm_[f].variableIndicesEnd()); if(ACC::bop(newValue,oldValue)) { updates = true ; if( visitor(*this) != visitors::VisitorReturnFlag::ContinueInf ){ exitInf=true; break; } for(v=0;v<gm_[f].numberOfVariables();++v) { const size_t varIndex=gm_[f].variableIndex(v); if(stateBuffer[v]!=movemaker_.state(varIndex)) { for(ff=0;ff<gm_.numberOfFactors(varIndex);++ff) { isLocalOptimal[gm_.factorOfVariable(varIndex,ff)]=false; } } } } isLocalOptimal[f]=true; } } } } visitor.end(*this); return NORMAL; } template<class GM, class ACC> inline InferenceTermination ICM<GM,ACC>::arg ( std::vector<LabelType>& x, const size_t N ) const { if(N==1) { x.resize(gm_.numberOfVariables()); for(size_t j=0; j<x.size(); ++j) { x[j] = movemaker_.state(j); } return NORMAL; } else { return UNKNOWN; } } } // namespace opengm #endif // #ifndef OPENGM_ICM_HXX <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2013 libwallet developers (see AUTHORS) * * This file is part of libwallet. * * libwallet 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/>. */ #ifndef LIBWALLET_DETERMINISTIC_WALLET_HPP #define LIBWALLET_DETERMINISTIC_WALLET_HPP #include <bitcoin/types.hpp> #include <bitcoin/utility/elliptic_curve_key.hpp> #include <wallet/define.hpp> namespace libwallet { using namespace libbitcoin; /** * Electrum compatible deterministic wallet. */ class deterministic_wallet { public: static constexpr size_t seed_size = 32; /** * Generate a new seed. * * @code * deterministic_wallet wallet; * wallet.new_seed(); * log_info() << "new seed: " << wallet.seed(); * @endcode */ BCW_API void new_seed(); /** * Restore wallet from seed. * * @code * if (!wallet.set_seed("...")) * // Error... * @endcode */ BCW_API bool set_seed(std::string seed); /** * Return the wallet seed. The seed should always be * deterministic_wallet::seed_size in length. * * @return Wallet seed. Empty string if not existant. */ BCW_API const std::string& seed() const; BCW_API bool set_master_public_key(const data_chunk& mpk); BCW_API const data_chunk& master_public_key() const; /** * Generate the n'th public key. A seed or master_public_key must be set. * * @code * payment_address addr; * set_public_key(addr, wallet.generate_public_key(2)); * btc_address = addr.encoded(); * @endcode */ BCW_API data_chunk generate_public_key( size_t n, bool for_change=false) const; /** * Generate the n'th secret. A seed must be set. * * The secret can be used to get the corresponding private key, * and also the public key. If just the public key is desired then * use generate_public_key() instead. * * @code * elliptic_curve_key privkey; * privkey.set_secret(wallet.generate_secret(2)); * @endcode */ BCW_API secret_parameter generate_secret( size_t n, bool for_change=false) const; private: hash_digest get_sequence(size_t n, bool for_change) const; std::string seed_; secret_parameter stretched_seed_; data_chunk master_public_key_; }; } // namespace libwallet #endif <commit_msg>deprecate old electrum detwallet class<commit_after>/* * Copyright (c) 2011-2013 libwallet developers (see AUTHORS) * * This file is part of libwallet. * * libwallet 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/>. */ #ifndef LIBWALLET_DETERMINISTIC_WALLET_HPP #define LIBWALLET_DETERMINISTIC_WALLET_HPP #include <bitcoin/types.hpp> #include <bitcoin/utility/elliptic_curve_key.hpp> #include <wallet/define.hpp> namespace libwallet { using namespace libbitcoin; /** * Electrum compatible deterministic wallet. */ class BC_DEPRECATED deterministic_wallet { public: static constexpr size_t seed_size = 32; /** * Generate a new seed. * * @code * deterministic_wallet wallet; * wallet.new_seed(); * log_info() << "new seed: " << wallet.seed(); * @endcode */ BCW_API void new_seed(); /** * Restore wallet from seed. * * @code * if (!wallet.set_seed("...")) * // Error... * @endcode */ BCW_API bool set_seed(std::string seed); /** * Return the wallet seed. The seed should always be * deterministic_wallet::seed_size in length. * * @return Wallet seed. Empty string if not existant. */ BCW_API const std::string& seed() const; BCW_API bool set_master_public_key(const data_chunk& mpk); BCW_API const data_chunk& master_public_key() const; /** * Generate the n'th public key. A seed or master_public_key must be set. * * @code * payment_address addr; * set_public_key(addr, wallet.generate_public_key(2)); * btc_address = addr.encoded(); * @endcode */ BCW_API data_chunk generate_public_key( size_t n, bool for_change=false) const; /** * Generate the n'th secret. A seed must be set. * * The secret can be used to get the corresponding private key, * and also the public key. If just the public key is desired then * use generate_public_key() instead. * * @code * elliptic_curve_key privkey; * privkey.set_secret(wallet.generate_secret(2)); * @endcode */ BCW_API secret_parameter generate_secret( size_t n, bool for_change=false) const; private: hash_digest get_sequence(size_t n, bool for_change) const; std::string seed_; secret_parameter stretched_seed_; data_chunk master_public_key_; }; } // namespace libwallet #endif <|endoftext|>
<commit_before>/** * @file llnamelistctrl.cpp * @brief A list of names, automatically refreshed from name cache. * * $LicenseInfo:firstyear=2003&license=viewergpl$ * * Copyright (c) 2003-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llnamelistctrl.h" #include <boost/tokenizer.hpp> #include "llcachename.h" #include "llfloaterreg.h" #include "llinventory.h" #include "llscrolllistitem.h" #include "llscrolllistcell.h" #include "llscrolllistcolumn.h" #include "llsdparam.h" #include "lltooltip.h" static LLDefaultChildRegistry::Register<LLNameListCtrl> r("name_list"); void LLNameListCtrl::NameTypeNames::declareValues() { declare("INDIVIDUAL", LLNameListCtrl::INDIVIDUAL); declare("GROUP", LLNameListCtrl::GROUP); declare("SPECIAL", LLNameListCtrl::SPECIAL); } LLNameListCtrl::Params::Params() : name_column(""), allow_calling_card_drop("allow_calling_card_drop", false) { name = "name_list"; } LLNameListCtrl::LLNameListCtrl(const LLNameListCtrl::Params& p) : LLScrollListCtrl(p), mNameColumnIndex(p.name_column.column_index), mNameColumn(p.name_column.column_name), mAllowCallingCardDrop(p.allow_calling_card_drop) {} // public void LLNameListCtrl::addNameItem(const LLUUID& agent_id, EAddPosition pos, BOOL enabled, std::string& suffix) { //llinfos << "LLNameListCtrl::addNameItem " << agent_id << llendl; NameItem item; item.value = agent_id; item.enabled = enabled; item.target = INDIVIDUAL; addNameItemRow(item, pos); } // virtual, public BOOL LLNameListCtrl::handleDragAndDrop( S32 x, S32 y, MASK mask, BOOL drop, EDragAndDropType cargo_type, void *cargo_data, EAcceptance *accept, std::string& tooltip_msg) { if (!mAllowCallingCardDrop) { return FALSE; } BOOL handled = FALSE; if (cargo_type == DAD_CALLINGCARD) { if (drop) { LLInventoryItem* item = (LLInventoryItem *)cargo_data; addNameItem(item->getCreatorUUID()); } *accept = ACCEPT_YES_MULTI; } else { *accept = ACCEPT_NO; if (tooltip_msg.empty()) { if (!getToolTip().empty()) { tooltip_msg = getToolTip(); } else { // backwards compatable English tooltip (should be overridden in xml) tooltip_msg.assign("Drag a calling card here\nto add a resident."); } } } handled = TRUE; lldebugst(LLERR_USER_INPUT) << "dragAndDrop handled by LLNameListCtrl " << getName() << llendl; return handled; } void LLNameListCtrl::showInspector(const LLUUID& avatar_id, bool is_group) { if (is_group) LLFloaterReg::showInstance("inspect_group", LLSD().with("group_id", avatar_id)); else LLFloaterReg::showInstance("inspect_avatar", LLSD().with("avatar_id", avatar_id)); } //virtual BOOL LLNameListCtrl::handleToolTip(S32 x, S32 y, MASK mask) { BOOL handled = FALSE; S32 column_index = getColumnIndexFromOffset(x); LLScrollListItem* hit_item = hitItem(x, y); if (hit_item && column_index == mNameColumnIndex) { // ...this is the column with the avatar name LLUUID avatar_id = hit_item->getUUID(); if (avatar_id.notNull()) { // ...valid avatar id LLScrollListCell* hit_cell = hit_item->getColumn(column_index); if (hit_cell) { S32 row_index = getItemIndex(hit_item); LLRect cell_rect = getCellRect(row_index, column_index); // Convert rect local to screen coordinates LLRect sticky_rect; localRectToScreen(cell_rect, &sticky_rect); // Spawn at right side of cell LLCoordGL pos( sticky_rect.mRight - 16, sticky_rect.mTop ); LLPointer<LLUIImage> icon = LLUI::getUIImage("Info_Small"); // Should we show a group or an avatar inspector? bool is_group = hit_item->getValue()["is_group"].asBoolean(); LLToolTip::Params params; params.background_visible( false ); params.click_callback( boost::bind(&LLNameListCtrl::showInspector, this, avatar_id, is_group) ); params.delay_time(0.0f); // spawn instantly on hover params.image( icon ); params.message(""); params.padding(0); params.pos(pos); params.sticky_rect(sticky_rect); LLToolTipMgr::getInstance()->show(params); handled = TRUE; } } } if (!handled) { handled = LLScrollListCtrl::handleToolTip(x, y, mask); } return handled; } // public void LLNameListCtrl::addGroupNameItem(const LLUUID& group_id, EAddPosition pos, BOOL enabled) { NameItem item; item.value = group_id; item.enabled = enabled; item.target = GROUP; addNameItemRow(item, pos); } // public void LLNameListCtrl::addGroupNameItem(LLNameListCtrl::NameItem& item, EAddPosition pos) { item.target = GROUP; addNameItemRow(item, pos); } void LLNameListCtrl::addNameItem(LLNameListCtrl::NameItem& item, EAddPosition pos) { item.target = INDIVIDUAL; addNameItemRow(item, pos); } LLScrollListItem* LLNameListCtrl::addElement(const LLSD& element, EAddPosition pos, void* userdata) { LLNameListCtrl::NameItem item_params; LLParamSDParser::instance().readSD(element, item_params); item_params.userdata = userdata; return addNameItemRow(item_params, pos); } LLScrollListItem* LLNameListCtrl::addNameItemRow( const LLNameListCtrl::NameItem& name_item, EAddPosition pos, std::string& suffix) { LLUUID id = name_item.value().asUUID(); LLNameListItem* item = NULL; // Store item type so that we can invoke the proper inspector. // *TODO Vadim: Is there a more proper way of storing additional item data? { LLNameListCtrl::NameItem item_p(name_item); item_p.value = LLSD().with("uuid", id).with("is_group", name_item.target() == GROUP); item = new LLNameListItem(item_p); LLScrollListCtrl::addRow(item, item_p, pos); } if (!item) return NULL; // use supplied name by default std::string fullname = name_item.name; switch(name_item.target) { case GROUP: gCacheName->getGroupName(id, fullname); // fullname will be "nobody" if group not found break; case SPECIAL: // just use supplied name break; case INDIVIDUAL: { std::string name; if (gCacheName->getFullName(id, name)) { fullname = name; } break; } default: break; } // Append optional suffix. if (!suffix.empty()) { fullname.append(suffix); } LLScrollListCell* cell = item->getColumn(mNameColumnIndex); if (cell) { cell->setValue(fullname); } dirtyColumns(); // this column is resizable LLScrollListColumn* columnp = getColumn(mNameColumnIndex); if (columnp && columnp->mHeader) { columnp->mHeader->setHasResizableElement(TRUE); } return item; } // public void LLNameListCtrl::removeNameItem(const LLUUID& agent_id) { // Find the item specified with agent_id. S32 idx = -1; for (item_list::iterator it = getItemList().begin(); it != getItemList().end(); it++) { LLScrollListItem* item = *it; if (item->getUUID() == agent_id) { idx = getItemIndex(item); break; } } // Remove it. if (idx >= 0) { selectNthItem(idx); // not sure whether this is needed, taken from previous implementation deleteSingleItem(idx); } } // public void LLNameListCtrl::refresh(const LLUUID& id, const std::string& first, const std::string& last, BOOL is_group) { //llinfos << "LLNameListCtrl::refresh " << id << " '" << first << " " // << last << "'" << llendl; std::string fullname; if (!is_group) { fullname = first + " " + last; } else { fullname = first; } // TODO: scan items for that ID, fix if necessary item_list::iterator iter; for (iter = getItemList().begin(); iter != getItemList().end(); iter++) { LLScrollListItem* item = *iter; if (item->getUUID() == id) { LLScrollListCell* cell = (LLScrollListCell*)item->getColumn(0); cell = item->getColumn(mNameColumnIndex); if (cell) { cell->setValue(fullname); } } } dirtyColumns(); } // static void LLNameListCtrl::refreshAll(const LLUUID& id, const std::string& first, const std::string& last, BOOL is_group) { LLInstanceTracker<LLNameListCtrl>::instance_iter it; for (it = beginInstances(); it != endInstances(); ++it) { LLNameListCtrl& ctrl = *it; ctrl.refresh(id, first, last, is_group); } } void LLNameListCtrl::updateColumns() { LLScrollListCtrl::updateColumns(); if (!mNameColumn.empty()) { LLScrollListColumn* name_column = getColumn(mNameColumn); if (name_column) { mNameColumnIndex = name_column->mIndex; } } } <commit_msg>fix low EXT-3807 ABOUT LAND/OBJECTS: (i) icon is badly positioned<commit_after>/** * @file llnamelistctrl.cpp * @brief A list of names, automatically refreshed from name cache. * * $LicenseInfo:firstyear=2003&license=viewergpl$ * * Copyright (c) 2003-2009, Linden Research, Inc. * * Second Life Viewer Source Code * The source code in this file ("Source Code") is provided by Linden Lab * to you under the terms of the GNU General Public License, version 2.0 * ("GPL"), unless you have obtained a separate licensing agreement * ("Other License"), formally executed by you and Linden Lab. Terms of * the GPL can be found in doc/GPL-license.txt in this distribution, or * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2 * * There are special exceptions to the terms and conditions of the GPL as * it is applied to this Source Code. View the full text of the exception * in the file doc/FLOSS-exception.txt in this software distribution, or * online at * http://secondlifegrid.net/programs/open_source/licensing/flossexception * * By copying, modifying or distributing this software, you acknowledge * that you have read and understood your obligations described above, * and agree to abide by those obligations. * * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY, * COMPLETENESS OR PERFORMANCE. * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llnamelistctrl.h" #include <boost/tokenizer.hpp> #include "llcachename.h" #include "llfloaterreg.h" #include "llinventory.h" #include "llscrolllistitem.h" #include "llscrolllistcell.h" #include "llscrolllistcolumn.h" #include "llsdparam.h" #include "lltooltip.h" static LLDefaultChildRegistry::Register<LLNameListCtrl> r("name_list"); void LLNameListCtrl::NameTypeNames::declareValues() { declare("INDIVIDUAL", LLNameListCtrl::INDIVIDUAL); declare("GROUP", LLNameListCtrl::GROUP); declare("SPECIAL", LLNameListCtrl::SPECIAL); } LLNameListCtrl::Params::Params() : name_column(""), allow_calling_card_drop("allow_calling_card_drop", false) { name = "name_list"; } LLNameListCtrl::LLNameListCtrl(const LLNameListCtrl::Params& p) : LLScrollListCtrl(p), mNameColumnIndex(p.name_column.column_index), mNameColumn(p.name_column.column_name), mAllowCallingCardDrop(p.allow_calling_card_drop) {} // public void LLNameListCtrl::addNameItem(const LLUUID& agent_id, EAddPosition pos, BOOL enabled, std::string& suffix) { //llinfos << "LLNameListCtrl::addNameItem " << agent_id << llendl; NameItem item; item.value = agent_id; item.enabled = enabled; item.target = INDIVIDUAL; addNameItemRow(item, pos); } // virtual, public BOOL LLNameListCtrl::handleDragAndDrop( S32 x, S32 y, MASK mask, BOOL drop, EDragAndDropType cargo_type, void *cargo_data, EAcceptance *accept, std::string& tooltip_msg) { if (!mAllowCallingCardDrop) { return FALSE; } BOOL handled = FALSE; if (cargo_type == DAD_CALLINGCARD) { if (drop) { LLInventoryItem* item = (LLInventoryItem *)cargo_data; addNameItem(item->getCreatorUUID()); } *accept = ACCEPT_YES_MULTI; } else { *accept = ACCEPT_NO; if (tooltip_msg.empty()) { if (!getToolTip().empty()) { tooltip_msg = getToolTip(); } else { // backwards compatable English tooltip (should be overridden in xml) tooltip_msg.assign("Drag a calling card here\nto add a resident."); } } } handled = TRUE; lldebugst(LLERR_USER_INPUT) << "dragAndDrop handled by LLNameListCtrl " << getName() << llendl; return handled; } void LLNameListCtrl::showInspector(const LLUUID& avatar_id, bool is_group) { if (is_group) LLFloaterReg::showInstance("inspect_group", LLSD().with("group_id", avatar_id)); else LLFloaterReg::showInstance("inspect_avatar", LLSD().with("avatar_id", avatar_id)); } //virtual BOOL LLNameListCtrl::handleToolTip(S32 x, S32 y, MASK mask) { BOOL handled = FALSE; S32 column_index = getColumnIndexFromOffset(x); LLScrollListItem* hit_item = hitItem(x, y); if (hit_item && column_index == mNameColumnIndex) { // ...this is the column with the avatar name LLUUID avatar_id = hit_item->getUUID(); if (avatar_id.notNull()) { // ...valid avatar id LLScrollListCell* hit_cell = hit_item->getColumn(column_index); if (hit_cell) { S32 row_index = getItemIndex(hit_item); LLRect cell_rect = getCellRect(row_index, column_index); // Convert rect local to screen coordinates LLRect sticky_rect; localRectToScreen(cell_rect, &sticky_rect); // Spawn at right side of cell LLCoordGL pos( sticky_rect.mRight - 16, sticky_rect.mTop + (sticky_rect.getHeight()-16)/2 ); LLPointer<LLUIImage> icon = LLUI::getUIImage("Info_Small"); // Should we show a group or an avatar inspector? bool is_group = hit_item->getValue()["is_group"].asBoolean(); LLToolTip::Params params; params.background_visible( false ); params.click_callback( boost::bind(&LLNameListCtrl::showInspector, this, avatar_id, is_group) ); params.delay_time(0.0f); // spawn instantly on hover params.image( icon ); params.message(""); params.padding(0); params.pos(pos); params.sticky_rect(sticky_rect); LLToolTipMgr::getInstance()->show(params); handled = TRUE; } } } if (!handled) { handled = LLScrollListCtrl::handleToolTip(x, y, mask); } return handled; } // public void LLNameListCtrl::addGroupNameItem(const LLUUID& group_id, EAddPosition pos, BOOL enabled) { NameItem item; item.value = group_id; item.enabled = enabled; item.target = GROUP; addNameItemRow(item, pos); } // public void LLNameListCtrl::addGroupNameItem(LLNameListCtrl::NameItem& item, EAddPosition pos) { item.target = GROUP; addNameItemRow(item, pos); } void LLNameListCtrl::addNameItem(LLNameListCtrl::NameItem& item, EAddPosition pos) { item.target = INDIVIDUAL; addNameItemRow(item, pos); } LLScrollListItem* LLNameListCtrl::addElement(const LLSD& element, EAddPosition pos, void* userdata) { LLNameListCtrl::NameItem item_params; LLParamSDParser::instance().readSD(element, item_params); item_params.userdata = userdata; return addNameItemRow(item_params, pos); } LLScrollListItem* LLNameListCtrl::addNameItemRow( const LLNameListCtrl::NameItem& name_item, EAddPosition pos, std::string& suffix) { LLUUID id = name_item.value().asUUID(); LLNameListItem* item = NULL; // Store item type so that we can invoke the proper inspector. // *TODO Vadim: Is there a more proper way of storing additional item data? { LLNameListCtrl::NameItem item_p(name_item); item_p.value = LLSD().with("uuid", id).with("is_group", name_item.target() == GROUP); item = new LLNameListItem(item_p); LLScrollListCtrl::addRow(item, item_p, pos); } if (!item) return NULL; // use supplied name by default std::string fullname = name_item.name; switch(name_item.target) { case GROUP: gCacheName->getGroupName(id, fullname); // fullname will be "nobody" if group not found break; case SPECIAL: // just use supplied name break; case INDIVIDUAL: { std::string name; if (gCacheName->getFullName(id, name)) { fullname = name; } break; } default: break; } // Append optional suffix. if (!suffix.empty()) { fullname.append(suffix); } LLScrollListCell* cell = item->getColumn(mNameColumnIndex); if (cell) { cell->setValue(fullname); } dirtyColumns(); // this column is resizable LLScrollListColumn* columnp = getColumn(mNameColumnIndex); if (columnp && columnp->mHeader) { columnp->mHeader->setHasResizableElement(TRUE); } return item; } // public void LLNameListCtrl::removeNameItem(const LLUUID& agent_id) { // Find the item specified with agent_id. S32 idx = -1; for (item_list::iterator it = getItemList().begin(); it != getItemList().end(); it++) { LLScrollListItem* item = *it; if (item->getUUID() == agent_id) { idx = getItemIndex(item); break; } } // Remove it. if (idx >= 0) { selectNthItem(idx); // not sure whether this is needed, taken from previous implementation deleteSingleItem(idx); } } // public void LLNameListCtrl::refresh(const LLUUID& id, const std::string& first, const std::string& last, BOOL is_group) { //llinfos << "LLNameListCtrl::refresh " << id << " '" << first << " " // << last << "'" << llendl; std::string fullname; if (!is_group) { fullname = first + " " + last; } else { fullname = first; } // TODO: scan items for that ID, fix if necessary item_list::iterator iter; for (iter = getItemList().begin(); iter != getItemList().end(); iter++) { LLScrollListItem* item = *iter; if (item->getUUID() == id) { LLScrollListCell* cell = (LLScrollListCell*)item->getColumn(0); cell = item->getColumn(mNameColumnIndex); if (cell) { cell->setValue(fullname); } } } dirtyColumns(); } // static void LLNameListCtrl::refreshAll(const LLUUID& id, const std::string& first, const std::string& last, BOOL is_group) { LLInstanceTracker<LLNameListCtrl>::instance_iter it; for (it = beginInstances(); it != endInstances(); ++it) { LLNameListCtrl& ctrl = *it; ctrl.refresh(id, first, last, is_group); } } void LLNameListCtrl::updateColumns() { LLScrollListCtrl::updateColumns(); if (!mNameColumn.empty()) { LLScrollListColumn* name_column = getColumn(mNameColumn); if (name_column) { mNameColumnIndex = name_column->mIndex; } } } <|endoftext|>
<commit_before>/* * Fadecandy device interface * * Copyright (c) 2013 Micah Elizabeth Scott * * 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 "fcdevice.h" #include <math.h> #include <iostream> #include <sstream> #include <stdio.h> FCDevice::Transfer::Transfer(FCDevice *device, void *buffer, int length) : transfer(libusb_alloc_transfer(0)), device(device) { libusb_fill_bulk_transfer(transfer, device->mHandle, OUT_ENDPOINT, (uint8_t*) buffer, length, FCDevice::completeTransfer, this, 2000); } FCDevice::Transfer::~Transfer() { libusb_free_transfer(transfer); } FCDevice::FCDevice(libusb_device *device, bool verbose) : USBDevice(device, verbose), mConfigMap(0) { mSerial[0] = '\0'; memset(&mFirmwareConfig, 0, sizeof mFirmwareConfig); mFirmwareConfig.control = TYPE_CONFIG; // Framebuffer headers memset(mFramebuffer, 0, sizeof mFramebuffer); for (unsigned i = 0; i < FRAMEBUFFER_PACKETS; ++i) { mFramebuffer[i].control = TYPE_FRAMEBUFFER | i; } mFramebuffer[FRAMEBUFFER_PACKETS - 1].control |= FINAL; // Color LUT headers memset(mColorLUT, 0, sizeof mColorLUT); for (unsigned i = 0; i < LUT_PACKETS; ++i) { mColorLUT[i].control = TYPE_LUT | i; } mColorLUT[LUT_PACKETS - 1].control |= FINAL; } FCDevice::~FCDevice() { /* * If we have pending transfers, cancel them and jettison them * from the FCDevice. The Transfer objects themselves will be freed * once libusb completes them. */ for (std::set<Transfer*>::iterator i = mPending.begin(), e = mPending.end(); i != e; ++i) { Transfer *fct = *i; libusb_cancel_transfer(fct->transfer); fct->device = 0; } } bool FCDevice::probe(libusb_device *device) { libusb_device_descriptor dd; if (libusb_get_device_descriptor(device, &dd) < 0) { // Can't access descriptor? return false; } return dd.idVendor == 0x1d50 && dd.idProduct == 0x607a; } int FCDevice::open() { int r = libusb_get_device_descriptor(mDevice, &mDD); if (r < 0) { return r; } r = libusb_open(mDevice, &mHandle); if (r < 0) { return r; } r = libusb_claim_interface(mHandle, 0); if (r < 0) { return r; } return libusb_get_string_descriptor_ascii(mHandle, mDD.iSerialNumber, (uint8_t*)mSerial, sizeof mSerial); } bool FCDevice::matchConfiguration(const Value &config) { if (matchConfigurationWithTypeAndSerial(config, "fadecandy", mSerial)) { mConfigMap = findConfigMap(config); configureDevice(config); return true; } return false; } void FCDevice::configureDevice(const Value &config) { /* * Send a device configuration settings packet, using the default values in our * JSON config file. This can be overridden over OPC later on. */ const Value &led = config["led"]; if (!(led.IsTrue() || led.IsFalse() || led.IsNull())) { std::clog << "LED configuration must be true (always on), false (always off), or null (default).\n"; } mFirmwareConfig.data[0] = (led.IsNull() ? 0 : CFLAG_NO_ACTIVITY_LED) | (led.IsTrue() ? CFLAG_LED_CONTROL : 0) ; writeFirmwareConfiguration(); } void FCDevice::submitTransfer(Transfer *fct) { /* * Submit a new USB transfer. The Transfer object is guaranteed to be freed eventually. * On error, it's freed right away. */ int r = libusb_submit_transfer(fct->transfer); if (r < 0) { if (mVerbose && r != LIBUSB_ERROR_PIPE) { std::clog << "Error submitting USB transfer: " << libusb_strerror(libusb_error(r)) << "\n"; } delete fct; } else { mPending.insert(fct); } } void FCDevice::completeTransfer(struct libusb_transfer *transfer) { /* * Transfer complete. The FCDevice may or may not still exist; if the device was unplugged, * fct->device will be set to 0 by ~FCDevice(). */ FCDevice::Transfer *fct = static_cast<FCDevice::Transfer*>(transfer->user_data); FCDevice *self = fct->device; if (self) { self->mPending.erase(fct); } delete fct; } void FCDevice::writeColorCorrection(const Value &color) { /* * Populate the color correction table based on a JSON configuration object, * and send the new color LUT out over USB. * * 'color' may be 'null' to load an identity-mapped LUT, or it may be * a dictionary of options including 'gamma' and 'whitepoint'. */ // Default color LUT parameters double gamma = 1.0; double whitepoint[3] = {1.0, 1.0, 1.0}; /* * Parse the JSON object */ if (color.IsObject()) { const Value &vGamma = color["gamma"]; const Value &vWhitepoint = color["whitepoint"]; if (vGamma.IsNumber()) { gamma = vGamma.GetDouble(); } else if (!vGamma.IsNull() && mVerbose) { std::clog << "Gamma value must be a number.\n"; } if (vWhitepoint.IsArray() && vWhitepoint.Size() == 3 && vWhitepoint[0u].IsNumber() && vWhitepoint[1].IsNumber() && vWhitepoint[2].IsNumber()) { whitepoint[0] = vWhitepoint[0u].GetDouble(); whitepoint[1] = vWhitepoint[1].GetDouble(); whitepoint[2] = vWhitepoint[2].GetDouble(); } else if (!vWhitepoint.IsNull() && mVerbose) { std::clog << "Whitepoint value must be a list of 3 numbers.\n"; } } else if (!color.IsNull() && mVerbose) { std::clog << "Color correction value must be a JSON dictionary object.\n"; } /* * Calculate the color LUT, stowing the result in an array of USB packets. */ Packet *packet = mColorLUT; const unsigned firstByteOffset = 1; // Skip padding byte unsigned byteOffset = firstByteOffset; for (unsigned channel = 0; channel < 3; channel++) { for (unsigned entry = 0; entry < LUT_ENTRIES; entry++) { /* * Normalized input value corresponding to this LUT entry. * Ranges from 0 to slightly higher than 1. (The last LUT entry * can't quite be reached.) */ double input = (entry << 8) / 65535.0; // Color conversion double output = pow(input * whitepoint[channel], gamma); // Round to the nearest integer, and clamp. Overflow-safe. int64_t longValue = (output * 0xFFFF) + 0.5; int intValue = std::max<int64_t>(0, std::min<int64_t>(0xFFFF, longValue)); // Store LUT entry, little-endian order. packet->data[byteOffset++] = uint8_t(intValue); packet->data[byteOffset++] = uint8_t(intValue >> 8); if (byteOffset >= sizeof packet->data) { byteOffset = firstByteOffset; packet++; } } } // Start asynchronously sending the LUT. submitTransfer(new Transfer(this, &mColorLUT, sizeof mColorLUT)); } void FCDevice::writeFramebuffer() { /* * Asynchronously write the current framebuffer. * Note that the OS will copy our framebuffer at submit-time. * * XXX: To-do, flow control. If more than one frame is pending, we need to be able to * tell clients that we're going too fast, *or* we need to drop frames. */ submitTransfer(new Transfer(this, &mFramebuffer, sizeof mFramebuffer)); } void FCDevice::writeMessage(const OPCSink::Message &msg) { /* * Dispatch an incoming OPC command */ switch (msg.command) { case OPCSink::SetPixelColors: opcSetPixelColors(msg); writeFramebuffer(); return; case OPCSink::SystemExclusive: opcSysEx(msg); return; } if (mVerbose) { std::clog << "Unsupported OPC command: " << unsigned(msg.command) << "\n"; } } void FCDevice::opcSysEx(const OPCSink::Message &msg) { if (msg.length() < 4) { if (mVerbose) { std::clog << "SysEx message too short!\n"; } return; } unsigned id = (unsigned(msg.data[0]) << 24) | (unsigned(msg.data[1]) << 16) | (unsigned(msg.data[2]) << 8) | unsigned(msg.data[3]) ; switch (id) { case OPCSink::FCSetGlobalColorCorrection: return opcSetGlobalColorCorrection(msg); case OPCSink::FCSetFirmwareConfiguration: return opcSetFirmwareConfiguration(msg); } // Quietly ignore unhandled SysEx messages. } void FCDevice::opcSetPixelColors(const OPCSink::Message &msg) { /* * Parse through our device's mapping, and store any relevant portions of 'msg' * in the framebuffer. */ if (!mConfigMap) { // No mapping defined yet. This device is inactive. return; } const Value &map = *mConfigMap; for (unsigned i = 0, e = map.Size(); i != e; i++) { opcMapPixelColors(msg, map[i]); } } void FCDevice::opcMapPixelColors(const OPCSink::Message &msg, const Value &inst) { /* * Parse one JSON mapping instruction, and copy any relevant parts of 'msg' * into our framebuffer. This looks for any mapping instructions that we * recognize: * * [ OPC Channel, First OPC Pixel, First output pixel, pixel count ] */ unsigned msgPixelCount = msg.length() / 3; if (inst.IsArray() && inst.Size() == 4) { // Map a range from an OPC channel to our framebuffer const Value &vChannel = inst[0u]; const Value &vFirstOPC = inst[1]; const Value &vFirstOut = inst[2]; const Value &vCount = inst[3]; if (vChannel.IsUint() && vFirstOPC.IsUint() && vFirstOut.IsUint() && vCount.IsUint()) { unsigned channel = vChannel.GetUint(); unsigned firstOPC = vFirstOPC.GetUint(); unsigned firstOut = vFirstOut.GetUint(); unsigned count = vCount.GetUint(); if (channel != msg.channel) { return; } // Clamping, overflow-safe firstOPC = std::min<unsigned>(firstOPC, msgPixelCount); firstOut = std::min<unsigned>(firstOut, unsigned(NUM_PIXELS)); count = std::min<unsigned>(count, msgPixelCount - firstOPC); count = std::min<unsigned>(count, NUM_PIXELS - firstOut); // Copy pixels const uint8_t *inPtr = msg.data + (firstOPC * 3); unsigned outIndex = firstOut; while (count--) { uint8_t *outPtr = fbPixel(outIndex++); outPtr[0] = inPtr[0]; outPtr[1] = inPtr[1]; outPtr[2] = inPtr[2]; inPtr += 3; } return; } } // Still haven't found a match? if (mVerbose) { std::clog << "Unsupported JSON mapping instruction\n"; } } void FCDevice::opcSetGlobalColorCorrection(const OPCSink::Message &msg) { /* * Parse the message as JSON text, and if successful, write new * color correction data to the device. */ // Mutable NUL-terminated copy of the message string std::string text((char*)msg.data + 4, msg.length() - 4); if (mVerbose) { std::clog << "New global color correction settings: " << text << "\n"; } // Parse it in-place rapidjson::Document doc; doc.ParseInsitu<0>(&text[0]); if (doc.HasParseError()) { if (mVerbose) { std::clog << "Parse error in color correction JSON at character " << doc.GetErrorOffset() << ": " << doc.GetParseError() << "\n"; } return; } /* * Successfully parsed the JSON. From here, it's handled identically to * objects that come through the config file. */ writeColorCorrection(doc); } void FCDevice::opcSetFirmwareConfiguration(const OPCSink::Message &msg) { /* * Raw firmware configuration packet */ memcpy(mFirmwareConfig.data, msg.data + 4, std::min<size_t>(sizeof mFirmwareConfig.data, msg.length() - 4)); writeFirmwareConfiguration(); } void FCDevice::writeFirmwareConfiguration() { // Write mFirmwareConfig to the device submitTransfer(new Transfer(this, &mFirmwareConfig, sizeof mFirmwareConfig)); } std::string FCDevice::getName() { std::ostringstream s; s << "Fadecandy"; if (mSerial[0]) { unsigned major = mDD.bcdDevice >> 8; unsigned minor = mDD.bcdDevice & 0xFF; char version[10]; snprintf(version, sizeof version, "%x.%02x", major, minor); s << " (Serial# " << mSerial << ", Version " << version << ")"; } return s.str(); } <commit_msg>Remove "new global color correction settings" log message<commit_after>/* * Fadecandy device interface * * Copyright (c) 2013 Micah Elizabeth Scott * * 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 "fcdevice.h" #include <math.h> #include <iostream> #include <sstream> #include <stdio.h> FCDevice::Transfer::Transfer(FCDevice *device, void *buffer, int length) : transfer(libusb_alloc_transfer(0)), device(device) { libusb_fill_bulk_transfer(transfer, device->mHandle, OUT_ENDPOINT, (uint8_t*) buffer, length, FCDevice::completeTransfer, this, 2000); } FCDevice::Transfer::~Transfer() { libusb_free_transfer(transfer); } FCDevice::FCDevice(libusb_device *device, bool verbose) : USBDevice(device, verbose), mConfigMap(0) { mSerial[0] = '\0'; memset(&mFirmwareConfig, 0, sizeof mFirmwareConfig); mFirmwareConfig.control = TYPE_CONFIG; // Framebuffer headers memset(mFramebuffer, 0, sizeof mFramebuffer); for (unsigned i = 0; i < FRAMEBUFFER_PACKETS; ++i) { mFramebuffer[i].control = TYPE_FRAMEBUFFER | i; } mFramebuffer[FRAMEBUFFER_PACKETS - 1].control |= FINAL; // Color LUT headers memset(mColorLUT, 0, sizeof mColorLUT); for (unsigned i = 0; i < LUT_PACKETS; ++i) { mColorLUT[i].control = TYPE_LUT | i; } mColorLUT[LUT_PACKETS - 1].control |= FINAL; } FCDevice::~FCDevice() { /* * If we have pending transfers, cancel them and jettison them * from the FCDevice. The Transfer objects themselves will be freed * once libusb completes them. */ for (std::set<Transfer*>::iterator i = mPending.begin(), e = mPending.end(); i != e; ++i) { Transfer *fct = *i; libusb_cancel_transfer(fct->transfer); fct->device = 0; } } bool FCDevice::probe(libusb_device *device) { libusb_device_descriptor dd; if (libusb_get_device_descriptor(device, &dd) < 0) { // Can't access descriptor? return false; } return dd.idVendor == 0x1d50 && dd.idProduct == 0x607a; } int FCDevice::open() { int r = libusb_get_device_descriptor(mDevice, &mDD); if (r < 0) { return r; } r = libusb_open(mDevice, &mHandle); if (r < 0) { return r; } r = libusb_claim_interface(mHandle, 0); if (r < 0) { return r; } return libusb_get_string_descriptor_ascii(mHandle, mDD.iSerialNumber, (uint8_t*)mSerial, sizeof mSerial); } bool FCDevice::matchConfiguration(const Value &config) { if (matchConfigurationWithTypeAndSerial(config, "fadecandy", mSerial)) { mConfigMap = findConfigMap(config); configureDevice(config); return true; } return false; } void FCDevice::configureDevice(const Value &config) { /* * Send a device configuration settings packet, using the default values in our * JSON config file. This can be overridden over OPC later on. */ const Value &led = config["led"]; if (!(led.IsTrue() || led.IsFalse() || led.IsNull())) { std::clog << "LED configuration must be true (always on), false (always off), or null (default).\n"; } mFirmwareConfig.data[0] = (led.IsNull() ? 0 : CFLAG_NO_ACTIVITY_LED) | (led.IsTrue() ? CFLAG_LED_CONTROL : 0) ; writeFirmwareConfiguration(); } void FCDevice::submitTransfer(Transfer *fct) { /* * Submit a new USB transfer. The Transfer object is guaranteed to be freed eventually. * On error, it's freed right away. */ int r = libusb_submit_transfer(fct->transfer); if (r < 0) { if (mVerbose && r != LIBUSB_ERROR_PIPE) { std::clog << "Error submitting USB transfer: " << libusb_strerror(libusb_error(r)) << "\n"; } delete fct; } else { mPending.insert(fct); } } void FCDevice::completeTransfer(struct libusb_transfer *transfer) { /* * Transfer complete. The FCDevice may or may not still exist; if the device was unplugged, * fct->device will be set to 0 by ~FCDevice(). */ FCDevice::Transfer *fct = static_cast<FCDevice::Transfer*>(transfer->user_data); FCDevice *self = fct->device; if (self) { self->mPending.erase(fct); } delete fct; } void FCDevice::writeColorCorrection(const Value &color) { /* * Populate the color correction table based on a JSON configuration object, * and send the new color LUT out over USB. * * 'color' may be 'null' to load an identity-mapped LUT, or it may be * a dictionary of options including 'gamma' and 'whitepoint'. */ // Default color LUT parameters double gamma = 1.0; double whitepoint[3] = {1.0, 1.0, 1.0}; /* * Parse the JSON object */ if (color.IsObject()) { const Value &vGamma = color["gamma"]; const Value &vWhitepoint = color["whitepoint"]; if (vGamma.IsNumber()) { gamma = vGamma.GetDouble(); } else if (!vGamma.IsNull() && mVerbose) { std::clog << "Gamma value must be a number.\n"; } if (vWhitepoint.IsArray() && vWhitepoint.Size() == 3 && vWhitepoint[0u].IsNumber() && vWhitepoint[1].IsNumber() && vWhitepoint[2].IsNumber()) { whitepoint[0] = vWhitepoint[0u].GetDouble(); whitepoint[1] = vWhitepoint[1].GetDouble(); whitepoint[2] = vWhitepoint[2].GetDouble(); } else if (!vWhitepoint.IsNull() && mVerbose) { std::clog << "Whitepoint value must be a list of 3 numbers.\n"; } } else if (!color.IsNull() && mVerbose) { std::clog << "Color correction value must be a JSON dictionary object.\n"; } /* * Calculate the color LUT, stowing the result in an array of USB packets. */ Packet *packet = mColorLUT; const unsigned firstByteOffset = 1; // Skip padding byte unsigned byteOffset = firstByteOffset; for (unsigned channel = 0; channel < 3; channel++) { for (unsigned entry = 0; entry < LUT_ENTRIES; entry++) { /* * Normalized input value corresponding to this LUT entry. * Ranges from 0 to slightly higher than 1. (The last LUT entry * can't quite be reached.) */ double input = (entry << 8) / 65535.0; // Color conversion double output = pow(input * whitepoint[channel], gamma); // Round to the nearest integer, and clamp. Overflow-safe. int64_t longValue = (output * 0xFFFF) + 0.5; int intValue = std::max<int64_t>(0, std::min<int64_t>(0xFFFF, longValue)); // Store LUT entry, little-endian order. packet->data[byteOffset++] = uint8_t(intValue); packet->data[byteOffset++] = uint8_t(intValue >> 8); if (byteOffset >= sizeof packet->data) { byteOffset = firstByteOffset; packet++; } } } // Start asynchronously sending the LUT. submitTransfer(new Transfer(this, &mColorLUT, sizeof mColorLUT)); } void FCDevice::writeFramebuffer() { /* * Asynchronously write the current framebuffer. * Note that the OS will copy our framebuffer at submit-time. * * XXX: To-do, flow control. If more than one frame is pending, we need to be able to * tell clients that we're going too fast, *or* we need to drop frames. */ submitTransfer(new Transfer(this, &mFramebuffer, sizeof mFramebuffer)); } void FCDevice::writeMessage(const OPCSink::Message &msg) { /* * Dispatch an incoming OPC command */ switch (msg.command) { case OPCSink::SetPixelColors: opcSetPixelColors(msg); writeFramebuffer(); return; case OPCSink::SystemExclusive: opcSysEx(msg); return; } if (mVerbose) { std::clog << "Unsupported OPC command: " << unsigned(msg.command) << "\n"; } } void FCDevice::opcSysEx(const OPCSink::Message &msg) { if (msg.length() < 4) { if (mVerbose) { std::clog << "SysEx message too short!\n"; } return; } unsigned id = (unsigned(msg.data[0]) << 24) | (unsigned(msg.data[1]) << 16) | (unsigned(msg.data[2]) << 8) | unsigned(msg.data[3]) ; switch (id) { case OPCSink::FCSetGlobalColorCorrection: return opcSetGlobalColorCorrection(msg); case OPCSink::FCSetFirmwareConfiguration: return opcSetFirmwareConfiguration(msg); } // Quietly ignore unhandled SysEx messages. } void FCDevice::opcSetPixelColors(const OPCSink::Message &msg) { /* * Parse through our device's mapping, and store any relevant portions of 'msg' * in the framebuffer. */ if (!mConfigMap) { // No mapping defined yet. This device is inactive. return; } const Value &map = *mConfigMap; for (unsigned i = 0, e = map.Size(); i != e; i++) { opcMapPixelColors(msg, map[i]); } } void FCDevice::opcMapPixelColors(const OPCSink::Message &msg, const Value &inst) { /* * Parse one JSON mapping instruction, and copy any relevant parts of 'msg' * into our framebuffer. This looks for any mapping instructions that we * recognize: * * [ OPC Channel, First OPC Pixel, First output pixel, pixel count ] */ unsigned msgPixelCount = msg.length() / 3; if (inst.IsArray() && inst.Size() == 4) { // Map a range from an OPC channel to our framebuffer const Value &vChannel = inst[0u]; const Value &vFirstOPC = inst[1]; const Value &vFirstOut = inst[2]; const Value &vCount = inst[3]; if (vChannel.IsUint() && vFirstOPC.IsUint() && vFirstOut.IsUint() && vCount.IsUint()) { unsigned channel = vChannel.GetUint(); unsigned firstOPC = vFirstOPC.GetUint(); unsigned firstOut = vFirstOut.GetUint(); unsigned count = vCount.GetUint(); if (channel != msg.channel) { return; } // Clamping, overflow-safe firstOPC = std::min<unsigned>(firstOPC, msgPixelCount); firstOut = std::min<unsigned>(firstOut, unsigned(NUM_PIXELS)); count = std::min<unsigned>(count, msgPixelCount - firstOPC); count = std::min<unsigned>(count, NUM_PIXELS - firstOut); // Copy pixels const uint8_t *inPtr = msg.data + (firstOPC * 3); unsigned outIndex = firstOut; while (count--) { uint8_t *outPtr = fbPixel(outIndex++); outPtr[0] = inPtr[0]; outPtr[1] = inPtr[1]; outPtr[2] = inPtr[2]; inPtr += 3; } return; } } // Still haven't found a match? if (mVerbose) { std::clog << "Unsupported JSON mapping instruction\n"; } } void FCDevice::opcSetGlobalColorCorrection(const OPCSink::Message &msg) { /* * Parse the message as JSON text, and if successful, write new * color correction data to the device. */ // Mutable NUL-terminated copy of the message string std::string text((char*)msg.data + 4, msg.length() - 4); // Parse it in-place rapidjson::Document doc; doc.ParseInsitu<0>(&text[0]); if (doc.HasParseError()) { if (mVerbose) { std::clog << "Parse error in color correction JSON at character " << doc.GetErrorOffset() << ": " << doc.GetParseError() << "\n"; } return; } /* * Successfully parsed the JSON. From here, it's handled identically to * objects that come through the config file. */ writeColorCorrection(doc); } void FCDevice::opcSetFirmwareConfiguration(const OPCSink::Message &msg) { /* * Raw firmware configuration packet */ memcpy(mFirmwareConfig.data, msg.data + 4, std::min<size_t>(sizeof mFirmwareConfig.data, msg.length() - 4)); writeFirmwareConfiguration(); } void FCDevice::writeFirmwareConfiguration() { // Write mFirmwareConfig to the device submitTransfer(new Transfer(this, &mFirmwareConfig, sizeof mFirmwareConfig)); } std::string FCDevice::getName() { std::ostringstream s; s << "Fadecandy"; if (mSerial[0]) { unsigned major = mDD.bcdDevice >> 8; unsigned minor = mDD.bcdDevice & 0xFF; char version[10]; snprintf(version, sizeof version, "%x.%02x", major, minor); s << " (Serial# " << mSerial << ", Version " << version << ")"; } return s.str(); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Components project. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Nokia Corporation and its Subsidiary(-ies) 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." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qtmenu.h" #include "qdebug.h" #include <qapplication.h> #include <qmenubar.h> #include <qabstractitemmodel.h> #include "qtoplevelwindow.h" QtMenu::QtMenu(QObject *parent) : QtMenuBase(parent), dummy(0), m_selectedIndex(0), m_highlightedIndex(0), m_hasNativeModel(false) { m_qmenu = new QMenu(0); connect(m_qmenu, SIGNAL(aboutToHide()), this, SIGNAL(menuClosed())); } QtMenu::~QtMenu() { delete m_qmenu; } void QtMenu::setText(const QString &text) { m_qmenu->setTitle(text); } QString QtMenu::text() const { return m_qmenu->title(); } void QtMenu::setSelectedIndex(int index) { m_selectedIndex = index; QList<QAction *> actionList = m_qmenu->actions(); if (m_selectedIndex >= 0 && m_selectedIndex < actionList.size()) m_qmenu->setActiveAction(actionList[m_selectedIndex]); emit selectedIndexChanged(); } void QtMenu::setHoveredIndex(int index) { m_highlightedIndex = index; QList<QAction *> actionList = m_qmenu->actions(); if (m_highlightedIndex >= 0 && m_highlightedIndex < actionList.size()) m_qmenu->setActiveAction(actionList[m_highlightedIndex]); emit hoveredIndexChanged(); } QDeclarativeListProperty<QtMenuBase> QtMenu::menuItems() { return QDeclarativeListProperty<QtMenuBase>(this, 0, &QtMenu::append_qmenuItem); } void QtMenu::showPopup(qreal x, qreal y, int atActionIndex) { if (m_qmenu->isVisible()) return; // If atActionIndex is valid, x and y is specified from the // the position of the corresponding QAction: QAction *atAction = 0; if (atActionIndex >= 0 && atActionIndex < m_qmenu->actions().size()) atAction = m_qmenu->actions()[atActionIndex]; // x,y are in view coordinates, QMenu expects screen coordinates // ### activeWindow hack int menuBarHeight = 0; QWidget *window = QApplication::activeWindow(); QTopLevelWindow *tw = qobject_cast<QTopLevelWindow*>(window); if (tw) { QMenuBar *menuBar = tw->menuBar(); menuBarHeight = menuBar->height(); } QPoint screenPosition = window->mapToGlobal(QPoint(x, y+menuBarHeight)); setHoveredIndex(m_selectedIndex); m_qmenu->popup(screenPosition, atAction); } void QtMenu::hidePopup() { m_qmenu->close(); } QAction* QtMenu::action() { return m_qmenu->menuAction(); } Q_INVOKABLE void QtMenu::clearMenuItems() { m_qmenu->clear(); foreach (QtMenuBase *item, m_qmenuItems) { delete item; } m_qmenuItems.clear(); } void QtMenu::addMenuItem(const QString &text) { QtMenuItem *menuItem = new QtMenuItem(this); menuItem->setText(text); m_qmenuItems.append(menuItem); m_qmenu->addAction(menuItem->action()); connect(menuItem->action(), SIGNAL(triggered()), this, SLOT(emitSelected())); connect(menuItem->action(), SIGNAL(hovered()), this, SLOT(emitHovered())); if (m_qmenu->actions().size() == 1) // Inform QML that the selected action (0) now has changed contents: emit selectedIndexChanged(); } void QtMenu::emitSelected() { QAction *act = qobject_cast<QAction *>(sender()); if (!act) return; m_selectedIndex = m_qmenu->actions().indexOf(act); emit selectedIndexChanged(); } void QtMenu::emitHovered() { QAction *act = qobject_cast<QAction *>(sender()); if (!act) return; m_highlightedIndex = m_qmenu->actions().indexOf(act); emit hoveredIndexChanged(); } QString QtMenu::itemTextAt(int index) const { QList<QAction *> actionList = m_qmenu->actions(); if (index >= 0 && index < actionList.size()) return actionList[index]->text(); else return ""; } QString QtMenu::modelTextAt(int index) const { if (QAbstractItemModel *model = qobject_cast<QAbstractItemModel*>(m_model.value<QObject*>())) { return model->data(model->index(index, 0)).toString(); } else if (m_model.canConvert(QVariant::StringList)) { return m_model.toStringList().at(index); } return ""; } int QtMenu::modelCount() const { if (QAbstractItemModel *model = qobject_cast<QAbstractItemModel*>(m_model.value<QObject*>())) { return model->rowCount(); } else if (m_model.canConvert(QVariant::StringList)) { return m_model.toStringList().count(); } return -1; } void QtMenu::append_qmenuItem(QDeclarativeListProperty<QtMenuBase> *list, QtMenuBase *menuItem) { QtMenu *menu = qobject_cast<QtMenu *>(list->object); if (menu) { menuItem->setParent(menu); menu->m_qmenuItems.append(menuItem); menu->qmenu()->addAction(menuItem->action()); } } void QtMenu::setModel(const QVariant &newModel) { if (m_model != newModel) { // Clean up any existing connections if (QAbstractItemModel *oldModel = qobject_cast<QAbstractItemModel*>(m_model.value<QObject*>())) { disconnect(oldModel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SIGNAL(rebuildMenu())); } m_hasNativeModel = false; m_model = newModel; if (QAbstractItemModel *model = qobject_cast<QAbstractItemModel*>(newModel.value<QObject*>())) { m_hasNativeModel = true; connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SIGNAL(rebuildMenu())); } else if (newModel.canConvert(QVariant::StringList)) { m_hasNativeModel = true; } emit modelChanged(m_model); } } <commit_msg>Fix QMenu coordinates when showing popup<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Components project. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "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 Nokia Corporation and its Subsidiary(-ies) 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." ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qtmenu.h" #include "qdebug.h" #include <qapplication.h> #include <qmenubar.h> #include <qabstractitemmodel.h> #include "qtoplevelwindow.h" QtMenu::QtMenu(QObject *parent) : QtMenuBase(parent), dummy(0), m_selectedIndex(0), m_highlightedIndex(0), m_hasNativeModel(false) { m_qmenu = new QMenu(0); connect(m_qmenu, SIGNAL(aboutToHide()), this, SIGNAL(menuClosed())); } QtMenu::~QtMenu() { delete m_qmenu; } void QtMenu::setText(const QString &text) { m_qmenu->setTitle(text); } QString QtMenu::text() const { return m_qmenu->title(); } void QtMenu::setSelectedIndex(int index) { m_selectedIndex = index; QList<QAction *> actionList = m_qmenu->actions(); if (m_selectedIndex >= 0 && m_selectedIndex < actionList.size()) m_qmenu->setActiveAction(actionList[m_selectedIndex]); emit selectedIndexChanged(); } void QtMenu::setHoveredIndex(int index) { m_highlightedIndex = index; QList<QAction *> actionList = m_qmenu->actions(); if (m_highlightedIndex >= 0 && m_highlightedIndex < actionList.size()) m_qmenu->setActiveAction(actionList[m_highlightedIndex]); emit hoveredIndexChanged(); } QDeclarativeListProperty<QtMenuBase> QtMenu::menuItems() { return QDeclarativeListProperty<QtMenuBase>(this, 0, &QtMenu::append_qmenuItem); } void QtMenu::showPopup(qreal x, qreal y, int atActionIndex) { if (m_qmenu->isVisible()) return; // If atActionIndex is valid, x and y is specified from the // the position of the corresponding QAction: QAction *atAction = 0; if (atActionIndex >= 0 && atActionIndex < m_qmenu->actions().size()) atAction = m_qmenu->actions()[atActionIndex]; // x,y are in view coordinates, QMenu expects screen coordinates // map coordinates from focusWidget rather than activeWindow since // QML items are commonly presented through a QWidget-derived view // still a hack QWidget *focusedWidget = QApplication::focusWidget(); QPoint screenPosition = focusedWidget->mapToGlobal(QPoint(x, y)); setHoveredIndex(m_selectedIndex); m_qmenu->popup(screenPosition, atAction); } void QtMenu::hidePopup() { m_qmenu->close(); } QAction* QtMenu::action() { return m_qmenu->menuAction(); } Q_INVOKABLE void QtMenu::clearMenuItems() { m_qmenu->clear(); foreach (QtMenuBase *item, m_qmenuItems) { delete item; } m_qmenuItems.clear(); } void QtMenu::addMenuItem(const QString &text) { QtMenuItem *menuItem = new QtMenuItem(this); menuItem->setText(text); m_qmenuItems.append(menuItem); m_qmenu->addAction(menuItem->action()); connect(menuItem->action(), SIGNAL(triggered()), this, SLOT(emitSelected())); connect(menuItem->action(), SIGNAL(hovered()), this, SLOT(emitHovered())); if (m_qmenu->actions().size() == 1) // Inform QML that the selected action (0) now has changed contents: emit selectedIndexChanged(); } void QtMenu::emitSelected() { QAction *act = qobject_cast<QAction *>(sender()); if (!act) return; m_selectedIndex = m_qmenu->actions().indexOf(act); emit selectedIndexChanged(); } void QtMenu::emitHovered() { QAction *act = qobject_cast<QAction *>(sender()); if (!act) return; m_highlightedIndex = m_qmenu->actions().indexOf(act); emit hoveredIndexChanged(); } QString QtMenu::itemTextAt(int index) const { QList<QAction *> actionList = m_qmenu->actions(); if (index >= 0 && index < actionList.size()) return actionList[index]->text(); else return ""; } QString QtMenu::modelTextAt(int index) const { if (QAbstractItemModel *model = qobject_cast<QAbstractItemModel*>(m_model.value<QObject*>())) { return model->data(model->index(index, 0)).toString(); } else if (m_model.canConvert(QVariant::StringList)) { return m_model.toStringList().at(index); } return ""; } int QtMenu::modelCount() const { if (QAbstractItemModel *model = qobject_cast<QAbstractItemModel*>(m_model.value<QObject*>())) { return model->rowCount(); } else if (m_model.canConvert(QVariant::StringList)) { return m_model.toStringList().count(); } return -1; } void QtMenu::append_qmenuItem(QDeclarativeListProperty<QtMenuBase> *list, QtMenuBase *menuItem) { QtMenu *menu = qobject_cast<QtMenu *>(list->object); if (menu) { menuItem->setParent(menu); menu->m_qmenuItems.append(menuItem); menu->qmenu()->addAction(menuItem->action()); } } void QtMenu::setModel(const QVariant &newModel) { if (m_model != newModel) { // Clean up any existing connections if (QAbstractItemModel *oldModel = qobject_cast<QAbstractItemModel*>(m_model.value<QObject*>())) { disconnect(oldModel, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SIGNAL(rebuildMenu())); } m_hasNativeModel = false; m_model = newModel; if (QAbstractItemModel *model = qobject_cast<QAbstractItemModel*>(newModel.value<QObject*>())) { m_hasNativeModel = true; connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SIGNAL(rebuildMenu())); } else if (newModel.canConvert(QVariant::StringList)) { m_hasNativeModel = true; } emit modelChanged(m_model); } } <|endoftext|>
<commit_before>// Filename: thread.cxx // Created by: drose (08Aug02) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://etc.cmu.edu/panda3d/docs/license/ . // // To contact the maintainers of this program write to // panda3d-general@lists.sourceforge.net . // //////////////////////////////////////////////////////////////////// #include "thread.h" #include "mainThread.h" #include "externalThread.h" #include "config_pipeline.h" Thread *Thread::_main_thread; Thread *Thread::_external_thread; TypeHandle Thread::_type_handle; //////////////////////////////////////////////////////////////////// // Function: Thread::Destructor // Access: Published, Virtual // Description: //////////////////////////////////////////////////////////////////// Thread:: ~Thread() { #ifdef DEBUG_THREADS nassertv(_blocked_on_mutex == NULL); #endif } //////////////////////////////////////////////////////////////////// // Function: Thread::bind_thread // Access: Published, Static // Description: Returns a new Panda Thread object associated with the // current thread (which has been created externally). // This can be used to bind a unique Panda Thread object // with an external thread, such as a new Python thread. // // It is particularly useful to bind a Panda Thread // object to an external thread for the purposes of // PStats monitoring. Without this call, each external // thread will be assigned the same global // ExternalThread object, which means they will all // appear in the same PStats graph. // // It is the caller's responsibility to save the // returned Thread pointer for the lifetime of the // external thread. It is an error for the Thread // pointer to destruct while the external thread is // still in the system. // // It is also an error to call this method from the main // thread, or twice within a given thread, unless it is // given the same name each time (in which case the same // pointer will be returned each time). //////////////////////////////////////////////////////////////////// PT(Thread) Thread:: bind_thread(const string &name, const string &sync_name) { Thread *current_thread = get_current_thread(); if (current_thread != get_external_thread()) { // This thread already has an associated thread. nassertr(current_thread->get_name() == name && current_thread->get_sync_name() == sync_name, current_thread); return current_thread; } PT(Thread) thread = new ExternalThread(name, sync_name); ThreadImpl::bind_thread(thread); return thread; } //////////////////////////////////////////////////////////////////// // Function: Thread::set_pipeline_stage // Access: Published // Description: Specifies the Pipeline stage number associated with // this thread. The default stage is 0 if no stage is // specified otherwise. // // This must be a value in the range [0 // .. pipeline->get_num_stages() - 1]. It specifies the // values that this thread observes for all pipelined // data. Typically, an application thread will leave // this at 0, but a render thread may set it to 1 or 2 // (to operate on the previous frame's data, or the // second previous frame's data). //////////////////////////////////////////////////////////////////// void Thread:: set_pipeline_stage(int pipeline_stage) { #ifdef THREADED_PIPELINE _pipeline_stage = pipeline_stage; #else if (pipeline_stage != 0) { pipeline_cat.warning() << "Requested pipeline stage " << pipeline_stage << " but multithreaded render pipelines not enabled in build.\n"; } _pipeline_stage = 0; #endif } //////////////////////////////////////////////////////////////////// // Function: Thread::output // Access: Published, Virtual // Description: //////////////////////////////////////////////////////////////////// void Thread:: output(ostream &out) const { out << get_type() << " " << get_name(); } //////////////////////////////////////////////////////////////////// // Function: Thread::write_status // Access: Published, Static // Description: //////////////////////////////////////////////////////////////////// void Thread:: write_status(ostream &out) { #ifdef SIMPLE_THREADS ThreadImpl::write_status(out); #endif } //////////////////////////////////////////////////////////////////// // Function: Thread::start // Access: Public // Description: Starts the thread executing. It is only valid to // call this once. // // The thread will begin executing its thread_main() // function, and will terminate when thread_main() // returns. // // priority is intended as a hint to the relative // importance of this thread. This may be ignored by // the thread implementation. // // joinable should be set true if you intend to call // join() to wait for the thread to terminate, or false // if you don't care and you will never call join(). // // The return value is true if the thread is // successfully started, false otherwise. //////////////////////////////////////////////////////////////////// bool Thread:: start(ThreadPriority priority, bool joinable) { nassertr(!_started, false); if (!support_threads) { thread_cat.warning() << *this << " could not be started: support-threads is false.\n"; return false; } _started = _impl.start(priority, joinable); if (!_started) { thread_cat.warning() << *this << " could not be started!\n"; } return _started; } //////////////////////////////////////////////////////////////////// // Function: Thread::init_main_thread // Access: Private, Static // Description: Creates the Thread object that represents the main // thread. //////////////////////////////////////////////////////////////////// void Thread:: init_main_thread() { // There is a chance of mutual recursion at startup. The count // variable here attempts to protect against that. static int count = 0; ++count; if (count == 1 && _main_thread == (Thread *)NULL) { _main_thread = new MainThread; _main_thread->ref(); } } //////////////////////////////////////////////////////////////////// // Function: Thread::init_external_thread // Access: Private, Static // Description: Creates the Thread object that represents all of the // external threads. //////////////////////////////////////////////////////////////////// void Thread:: init_external_thread() { if (_external_thread == (Thread *)NULL) { _external_thread = new ExternalThread; _external_thread->ref(); } } //////////////////////////////////////////////////////////////////// // Function: Thread::PStatsCallback::Destructor // Access: Public, Virtual // Description: Since this class is just an interface definition, // there is no need to have a destructor. However, we // must have one anyway to stop gcc's annoying warning. //////////////////////////////////////////////////////////////////// Thread::PStatsCallback:: ~PStatsCallback() { } //////////////////////////////////////////////////////////////////// // Function: Thread::PStatsCallback::deactivate_hook // Access: Public, Virtual // Description: Called when the thread is deactivated (swapped for // another running thread). This is intended to provide // a callback hook for PStats to assign time to // individual threads properly, particularly in the // SIMPLE_THREADS case. //////////////////////////////////////////////////////////////////// void Thread::PStatsCallback:: deactivate_hook(Thread *) { } //////////////////////////////////////////////////////////////////// // Function: Thread::PStatsCallback::activate_hook // Access: Public, Virtual // Description: Called when the thread is activated (resumes // execution). This is intended to provide a callback // hook for PStats to assign time to individual threads // properly, particularly in the SIMPLE_THREADS case. //////////////////////////////////////////////////////////////////// void Thread::PStatsCallback:: activate_hook(Thread *) { } <commit_msg>oops, compile when not HAVE_THREADS<commit_after>// Filename: thread.cxx // Created by: drose (08Aug02) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved // // All use of this software is subject to the terms of the Panda 3d // Software license. You should have received a copy of this license // along with this source code; you will also find a current copy of // the license at http://etc.cmu.edu/panda3d/docs/license/ . // // To contact the maintainers of this program write to // panda3d-general@lists.sourceforge.net . // //////////////////////////////////////////////////////////////////// #include "thread.h" #include "mainThread.h" #include "externalThread.h" #include "config_pipeline.h" Thread *Thread::_main_thread; Thread *Thread::_external_thread; TypeHandle Thread::_type_handle; //////////////////////////////////////////////////////////////////// // Function: Thread::Destructor // Access: Published, Virtual // Description: //////////////////////////////////////////////////////////////////// Thread:: ~Thread() { #ifdef DEBUG_THREADS nassertv(_blocked_on_mutex == NULL); #endif } //////////////////////////////////////////////////////////////////// // Function: Thread::bind_thread // Access: Published, Static // Description: Returns a new Panda Thread object associated with the // current thread (which has been created externally). // This can be used to bind a unique Panda Thread object // with an external thread, such as a new Python thread. // // It is particularly useful to bind a Panda Thread // object to an external thread for the purposes of // PStats monitoring. Without this call, each external // thread will be assigned the same global // ExternalThread object, which means they will all // appear in the same PStats graph. // // It is the caller's responsibility to save the // returned Thread pointer for the lifetime of the // external thread. It is an error for the Thread // pointer to destruct while the external thread is // still in the system. // // It is also an error to call this method from the main // thread, or twice within a given thread, unless it is // given the same name each time (in which case the same // pointer will be returned each time). //////////////////////////////////////////////////////////////////// PT(Thread) Thread:: bind_thread(const string &name, const string &sync_name) { Thread *current_thread = get_current_thread(); if (current_thread != get_external_thread()) { // This thread already has an associated thread. nassertr(current_thread->get_name() == name && current_thread->get_sync_name() == sync_name, current_thread); return current_thread; } PT(Thread) thread = new ExternalThread(name, sync_name); ThreadImpl::bind_thread(thread); return thread; } //////////////////////////////////////////////////////////////////// // Function: Thread::set_pipeline_stage // Access: Published // Description: Specifies the Pipeline stage number associated with // this thread. The default stage is 0 if no stage is // specified otherwise. // // This must be a value in the range [0 // .. pipeline->get_num_stages() - 1]. It specifies the // values that this thread observes for all pipelined // data. Typically, an application thread will leave // this at 0, but a render thread may set it to 1 or 2 // (to operate on the previous frame's data, or the // second previous frame's data). //////////////////////////////////////////////////////////////////// void Thread:: set_pipeline_stage(int pipeline_stage) { #ifdef THREADED_PIPELINE _pipeline_stage = pipeline_stage; #else if (pipeline_stage != 0) { pipeline_cat.warning() << "Requested pipeline stage " << pipeline_stage << " but multithreaded render pipelines not enabled in build.\n"; } _pipeline_stage = 0; #endif } //////////////////////////////////////////////////////////////////// // Function: Thread::output // Access: Published, Virtual // Description: //////////////////////////////////////////////////////////////////// void Thread:: output(ostream &out) const { out << get_type() << " " << get_name(); } //////////////////////////////////////////////////////////////////// // Function: Thread::write_status // Access: Published, Static // Description: //////////////////////////////////////////////////////////////////// void Thread:: write_status(ostream &out) { #if defined(HAVE_THREADS) && defined(SIMPLE_THREADS) ThreadImpl::write_status(out); #endif } //////////////////////////////////////////////////////////////////// // Function: Thread::start // Access: Public // Description: Starts the thread executing. It is only valid to // call this once. // // The thread will begin executing its thread_main() // function, and will terminate when thread_main() // returns. // // priority is intended as a hint to the relative // importance of this thread. This may be ignored by // the thread implementation. // // joinable should be set true if you intend to call // join() to wait for the thread to terminate, or false // if you don't care and you will never call join(). // // The return value is true if the thread is // successfully started, false otherwise. //////////////////////////////////////////////////////////////////// bool Thread:: start(ThreadPriority priority, bool joinable) { nassertr(!_started, false); if (!support_threads) { thread_cat.warning() << *this << " could not be started: support-threads is false.\n"; return false; } _started = _impl.start(priority, joinable); if (!_started) { thread_cat.warning() << *this << " could not be started!\n"; } return _started; } //////////////////////////////////////////////////////////////////// // Function: Thread::init_main_thread // Access: Private, Static // Description: Creates the Thread object that represents the main // thread. //////////////////////////////////////////////////////////////////// void Thread:: init_main_thread() { // There is a chance of mutual recursion at startup. The count // variable here attempts to protect against that. static int count = 0; ++count; if (count == 1 && _main_thread == (Thread *)NULL) { _main_thread = new MainThread; _main_thread->ref(); } } //////////////////////////////////////////////////////////////////// // Function: Thread::init_external_thread // Access: Private, Static // Description: Creates the Thread object that represents all of the // external threads. //////////////////////////////////////////////////////////////////// void Thread:: init_external_thread() { if (_external_thread == (Thread *)NULL) { _external_thread = new ExternalThread; _external_thread->ref(); } } //////////////////////////////////////////////////////////////////// // Function: Thread::PStatsCallback::Destructor // Access: Public, Virtual // Description: Since this class is just an interface definition, // there is no need to have a destructor. However, we // must have one anyway to stop gcc's annoying warning. //////////////////////////////////////////////////////////////////// Thread::PStatsCallback:: ~PStatsCallback() { } //////////////////////////////////////////////////////////////////// // Function: Thread::PStatsCallback::deactivate_hook // Access: Public, Virtual // Description: Called when the thread is deactivated (swapped for // another running thread). This is intended to provide // a callback hook for PStats to assign time to // individual threads properly, particularly in the // SIMPLE_THREADS case. //////////////////////////////////////////////////////////////////// void Thread::PStatsCallback:: deactivate_hook(Thread *) { } //////////////////////////////////////////////////////////////////// // Function: Thread::PStatsCallback::activate_hook // Access: Public, Virtual // Description: Called when the thread is activated (resumes // execution). This is intended to provide a callback // hook for PStats to assign time to individual threads // properly, particularly in the SIMPLE_THREADS case. //////////////////////////////////////////////////////////////////// void Thread::PStatsCallback:: activate_hook(Thread *) { } <|endoftext|>
<commit_before>/* * Result set */ #include "result.h" /* Col: 0, name: boolean_val, type: boolean Col: 1, name: char_val, type: char Col: 2, name: character_val, type: char Col: 3, name: date_val, type: date Col: 4, name: datetime_val, type: datetime Col: 5, name: dec_val, type: decimal Col: 6, name: decimal_val, type: decimal Col: 7, name: double_val, type: float Col: 8, name: float_val, type: float Col: 9, name: int_val, type: integer Col: 10, name: int8_val, type: int8 Col: 11, name: integer_val, type: integer Col: 12, name: interval_ds_val, type: interval Col: 13, name: interval_ym_val, type: interval Col: 14, name: lvarchar_val, type: lvarchar Col: 15, name: numeric_val, type: decimal Col: 16, name: money_val, type: money Col: 17, name: real_val, type: smallfloat Col: 18, name: serial_val, type: serial Col: 19, name: smallfloat_val, type: smallfloat Col: 20, name: smallint_val, type: smallint Col: 21, name: text_val, type: text Col: 22, name: byte_val, type: byte Col: 23, name: varchar_val, type: varchar Col: 24, name: large_object_val, type: blob Col: 25, name: large_text_val, type: clob Col: 26, name: cnstr_val, type: cnstr_type Col: 27, name: setof_base_val, type: SET(integer not null) Col: 28, name: setof_cnstr, type: SET(cnstr_type not null) Col: 29, name: boolean_null, type: boolean Col: 30, name: char_null, type: char Col: 31, name: character_null, type: char Col: 32, name: date_null, type: date Col: 33, name: datetime_null, type: datetime Col: 34, name: dec_null, type: decimal Col: 35, name: decimal_null, type: decimal Col: 36, name: double_null, type: float Col: 37, name: float_null, type: float Col: 38, name: int_null, type: integer Col: 39, name: int8_null, type: int8 Col: 40, name: integer_null, type: integer Col: 41, name: interval_ds_null, type: interval Col: 42, name: interval_ym_null, type: interval Col: 43, name: lvarchar_null, type: lvarchar Col: 44, name: numeric_null, type: decimal Col: 45, name: money_null, type: money Col: 46, name: real_null, type: smallfloat Col: 47, name: smallfloat_null, type: smallfloat Col: 48, name: smallint_null, type: smallint Col: 49, name: text_null, type: text Col: 50, name: varchar_null, type: varchar */ /* * \n column name * \ti ITTypeInfo of the column */ nodejs_db_informix::Result::Column::Column( const std::string n, const ITTypeInfo *ti) throw (nodejs_db::Exception&) { if (ti == NULL) { throw nodejs_db::Exception("Null column type"); } this->name = n; // assume its not binary for now this->binary = 0; this->typeName = std::string(ti->Name().Data()); if (this->typeName == "blob") { this->binary = 0; this->type = BLOB; } else if (this->typeName == "boolean") { this->binary = 0; this->type = BOOL; } else if (this->typeName == "byte") { this->binary = 0; this->type = INT; } else if (this->typeName == "char") { this->binary = 0; this->type = STRING; } else if (this->typeName == "clob") { this->binary = 0; this->type = TEXT; } else if (this->typeName == "date") { this->binary = 0; this->type = DATE; } else if (this->typeName == "datetime") { this->binary = 0; this->type = DATETIME; } else if (this->typeName == "decimal") { this->binary = 0; this->type = NUMBER; } else if (this->typeName == "float") { this->binary = 0; this->type = NUMBER; } else if (this->typeName == "int8") { this->binary = 0; this->type = INT; } else if (this->typeName == "integer") { this->binary = 0; this->type = INT; } else if (this->typeName == "interval") { this->binary = 0; this->type = INTERVAL; } else if (this->typeName == "lvarchar") { this->binary = 0; this->type = STRING; } else if (this->typeName == "money") { this->binary = 0; this->type = MONEY; } else if (this->typeName == "serial") { this->binary = 0; this->type = INT; } else if (this->typeName == "smallfloat") { this->binary = 0; this->type = NUMBER; } else if (this->typeName == "smallint") { this->binary = 0; this->type = NUMBER; } else if (this->typeName == "text") { this->binary = 0; this->type = TEXT; } else if (this->typeName == "varchar") { this->binary = 0; this->type = STRING; } else { // sub-columns if (ti->IsRow()) { this->typeName = "row"; this->type = ROW; this->binary = 0; } else if (ti->IsCollection()) { this->typeName = "collection"; this->type = COLLECTION; this->binary = 0; } else if (ti->IsConstructed()) { this->typeName = "constructed"; this->type = CONSTRUCTED; this->binary = 0; } } } nodejs_db_informix::Result::Column::~Column() { } bool nodejs_db_informix::Result::Column::isBinary() const { return this->binary; } std::string nodejs_db_informix::Result::Column::getName() const { return this->name; } nodejs_db::Result::Column::type_t nodejs_db_informix::Result::Column::getType() const { return this->type; } std::string nodejs_db_informix::Result::Column::getTypeName() const { return this->typeName; } nodejs_db_informix::Result::Result(ITBool b, long re) throw (nodejs_db::Exception&) : columns(), columnNames(), totalColumns(0), rowNumber(0), rowsAffected(re), empty(true), previousRow(NULL), nextRow(NULL) { empty = bool(b); } /** * * \rs Record set of type ITSet* * \cti Column Type Information of type ITTypeInfo */ nodejs_db_informix::Result::Result(ITSet* rs, const ITTypeInfo *cti, long re) throw(nodejs_db::Exception&) : columns(), columnNames(), totalColumns(0), rowNumber(0), rowsAffected(re), empty(true), previousRow(NULL), nextRow(NULL) { // check the column info and populate column data-structure if (rs == NULL || cti == NULL) { throw nodejs_db::Exception("Could not retreive column information"); } columns.clear(); columnNames.clear(); this->resultSet = rs; this->totalColumns = static_cast<uint16_t>(cti->ColumnCount()); if (this->totalColumns > 0) { // populate the Columns for (uint16_t c = 0; c < this->totalColumns; ++c) { std::string n = cti->ColumnName(c).Data(); Column *col = new Column(n, cti->ColumnType(c)); this->columns.push_back(col); this->columnNames.push_back(n); } this->empty = false; } this->nextRow = this->row(); } /** * * */ nodejs_db_informix::Result::Result(ITSet* rs, long re) throw(nodejs_db::Exception&) : columns(), columnNames(), totalColumns(0), rowNumber(0), rowsAffected(re), empty(true), previousRow(NULL), nextRow(NULL) { if (rs == NULL) { throw nodejs_db::Exception("Null ResultSet"); } columns.clear(); columnNames.clear(); // construct the column name, values from first row this->empty = false; this->resultSet = rs; this->nextRow = this->row(); } nodejs_db_informix::Result::~Result() { this->free(); } void nodejs_db_informix::Result::free() throw() { this->release(); } void nodejs_db_informix::Result::release() throw() { this->columns.clear(); this->columnNames.clear(); } bool nodejs_db_informix::Result::hasNext() const throw() { return (this->nextRow != NULL); } std::vector<std::string>* nodejs_db_informix::Result::next() throw(nodejs_db::Exception&) { if (this->nextRow == NULL) { return NULL; } this->rowNumber++; this->previousRow = this->nextRow; this->nextRow = this->row(); return this->previousRow; } unsigned long* nodejs_db_informix::Result::columnLengths() throw(nodejs_db::Exception&) { return this->colLengths; } std::vector<std::string>* nodejs_db_informix::Result::row() throw(nodejs_db::Exception&) { std::vector<std::string> *row = new std::vector<std::string>(); ITValue *v = this->resultSet->Fetch(); if (v == NULL) { // throw nodejs_db::Exception("Cannot fetch ITValue for next row"); return NULL; } ITRow *r; //ITRow is an abstract class if (v->QueryInterface(ITRowIID, (void**) &r) == IT_QUERYINTERFACE_FAILED) { throw nodejs_db::Exception("Couldn't fetch ITRow for next row"); } else { long nc = r->NumColumns(); // number of columns // TODO: amitkr@ don't we need to free this up at some point? this->colLengths = new unsigned long[nc]; for (long i = 0; i < nc; ++i) { ITValue *cv = r->Column(i); // column value if (cv->IsNull()) { // append null row->push_back(std::string("null")); this->colLengths[i] = std::string("null").length(); } else { row->push_back(std::string(cv->Printable().Data())); this->colLengths[i] = cv->Printable().Length(); } } } return row; } uint64_t nodejs_db_informix::Result::index() const throw(std::out_of_range&) { if (this->rowNumber == 0) { throw std::out_of_range("Not standing on a row"); } return (this->rowNumber - 1); } nodejs_db_informix::Result::Column* nodejs_db_informix::Result::column(uint16_t i) const throw(std::out_of_range&) { if (i >= this->totalColumns) { throw std::out_of_range("Wrong column index"); } #ifdef DEV std::cout << *(this->columns[i]) << std::endl; #endif return this->columns[i]; } uint64_t nodejs_db_informix::Result::insertId() const throw() { return 0; } uint64_t nodejs_db_informix::Result::affectedCount() const throw() { return rowsAffected; } uint16_t nodejs_db_informix::Result::warningCount() const throw() { return 0; } uint16_t nodejs_db_informix::Result::columnCount() const throw() { return this->totalColumns; } uint64_t nodejs_db_informix::Result::count() const throw(nodejs_db::Exception&) { if (!this->isBuffered()) { throw nodejs_db::Exception("Result is not buffered"); } return 0; } bool nodejs_db_informix::Result::isBuffered() const throw() { return true; } bool nodejs_db_informix::Result::isEmpty() const throw() { return this->empty; } <commit_msg>fix function spacing<commit_after>/* * Result set */ #include "result.h" /* Col: 0, name: boolean_val, type: boolean Col: 1, name: char_val, type: char Col: 2, name: character_val, type: char Col: 3, name: date_val, type: date Col: 4, name: datetime_val, type: datetime Col: 5, name: dec_val, type: decimal Col: 6, name: decimal_val, type: decimal Col: 7, name: double_val, type: float Col: 8, name: float_val, type: float Col: 9, name: int_val, type: integer Col: 10, name: int8_val, type: int8 Col: 11, name: integer_val, type: integer Col: 12, name: interval_ds_val, type: interval Col: 13, name: interval_ym_val, type: interval Col: 14, name: lvarchar_val, type: lvarchar Col: 15, name: numeric_val, type: decimal Col: 16, name: money_val, type: money Col: 17, name: real_val, type: smallfloat Col: 18, name: serial_val, type: serial Col: 19, name: smallfloat_val, type: smallfloat Col: 20, name: smallint_val, type: smallint Col: 21, name: text_val, type: text Col: 22, name: byte_val, type: byte Col: 23, name: varchar_val, type: varchar Col: 24, name: large_object_val, type: blob Col: 25, name: large_text_val, type: clob Col: 26, name: cnstr_val, type: cnstr_type Col: 27, name: setof_base_val, type: SET(integer not null) Col: 28, name: setof_cnstr, type: SET(cnstr_type not null) Col: 29, name: boolean_null, type: boolean Col: 30, name: char_null, type: char Col: 31, name: character_null, type: char Col: 32, name: date_null, type: date Col: 33, name: datetime_null, type: datetime Col: 34, name: dec_null, type: decimal Col: 35, name: decimal_null, type: decimal Col: 36, name: double_null, type: float Col: 37, name: float_null, type: float Col: 38, name: int_null, type: integer Col: 39, name: int8_null, type: int8 Col: 40, name: integer_null, type: integer Col: 41, name: interval_ds_null, type: interval Col: 42, name: interval_ym_null, type: interval Col: 43, name: lvarchar_null, type: lvarchar Col: 44, name: numeric_null, type: decimal Col: 45, name: money_null, type: money Col: 46, name: real_null, type: smallfloat Col: 47, name: smallfloat_null, type: smallfloat Col: 48, name: smallint_null, type: smallint Col: 49, name: text_null, type: text Col: 50, name: varchar_null, type: varchar */ /* * \n column name * \ti ITTypeInfo of the column */ nodejs_db_informix::Result::Column::Column( const std::string n, const ITTypeInfo *ti) throw (nodejs_db::Exception&) { if (ti == NULL) { throw nodejs_db::Exception("Null column type"); } this->name = n; // assume its not binary for now this->binary = 0; this->typeName = std::string(ti->Name().Data()); if (this->typeName == "blob") { this->binary = 0; this->type = BLOB; } else if (this->typeName == "boolean") { this->binary = 0; this->type = BOOL; } else if (this->typeName == "byte") { this->binary = 0; this->type = INT; } else if (this->typeName == "char") { this->binary = 0; this->type = STRING; } else if (this->typeName == "clob") { this->binary = 0; this->type = TEXT; } else if (this->typeName == "date") { this->binary = 0; this->type = DATE; } else if (this->typeName == "datetime") { this->binary = 0; this->type = DATETIME; } else if (this->typeName == "decimal") { this->binary = 0; this->type = NUMBER; } else if (this->typeName == "float") { this->binary = 0; this->type = NUMBER; } else if (this->typeName == "int8") { this->binary = 0; this->type = INT; } else if (this->typeName == "integer") { this->binary = 0; this->type = INT; } else if (this->typeName == "interval") { this->binary = 0; this->type = INTERVAL; } else if (this->typeName == "lvarchar") { this->binary = 0; this->type = STRING; } else if (this->typeName == "money") { this->binary = 0; this->type = MONEY; } else if (this->typeName == "serial") { this->binary = 0; this->type = INT; } else if (this->typeName == "smallfloat") { this->binary = 0; this->type = NUMBER; } else if (this->typeName == "smallint") { this->binary = 0; this->type = NUMBER; } else if (this->typeName == "text") { this->binary = 0; this->type = TEXT; } else if (this->typeName == "varchar") { this->binary = 0; this->type = STRING; } else { // sub-columns if (ti->IsRow()) { this->typeName = "row"; this->type = ROW; this->binary = 0; } else if (ti->IsCollection()) { this->typeName = "collection"; this->type = COLLECTION; this->binary = 0; } else if (ti->IsConstructed()) { this->typeName = "constructed"; this->type = CONSTRUCTED; this->binary = 0; } } } nodejs_db_informix::Result::Column::~Column() { } bool nodejs_db_informix::Result::Column::isBinary() const { return this->binary; } std::string nodejs_db_informix::Result::Column::getName() const { return this->name; } nodejs_db::Result::Column::type_t nodejs_db_informix::Result::Column::getType() const { return this->type; } std::string nodejs_db_informix::Result::Column::getTypeName() const { return this->typeName; } nodejs_db_informix::Result::Result(ITBool b, long re) throw (nodejs_db::Exception&) : columns(), columnNames(), totalColumns(0), rowNumber(0), rowsAffected(re), empty(true), previousRow(NULL), nextRow(NULL) { empty = bool(b); } /** * * \rs Record set of type ITSet* * \cti Column Type Information of type ITTypeInfo */ nodejs_db_informix::Result::Result(ITSet* rs, const ITTypeInfo *cti, long re) throw(nodejs_db::Exception&) : columns(), columnNames(), totalColumns(0), rowNumber(0), rowsAffected(re), empty(true), previousRow(NULL), nextRow(NULL) { // check the column info and populate column data-structure if (rs == NULL || cti == NULL) { throw nodejs_db::Exception("Could not retreive column information"); } columns.clear(); columnNames.clear(); this->resultSet = rs; this->totalColumns = static_cast<uint16_t>(cti->ColumnCount()); if (this->totalColumns > 0) { // populate the Columns for (uint16_t c = 0; c < this->totalColumns; ++c) { std::string n = cti->ColumnName(c).Data(); Column *col = new Column(n, cti->ColumnType(c)); this->columns.push_back(col); this->columnNames.push_back(n); } this->empty = false; } this->nextRow = this->row(); } /** * * */ nodejs_db_informix::Result::Result(ITSet* rs, long re) throw(nodejs_db::Exception&) : columns(), columnNames(), totalColumns(0), rowNumber(0), rowsAffected(re), empty(true), previousRow(NULL), nextRow(NULL) { if (rs == NULL) { throw nodejs_db::Exception("Null ResultSet"); } columns.clear(); columnNames.clear(); // construct the column name, values from first row this->empty = false; this->resultSet = rs; this->nextRow = this->row(); } nodejs_db_informix::Result::~Result() { this->free(); } void nodejs_db_informix::Result::free() throw() { this->release(); } void nodejs_db_informix::Result::release() throw() { this->columns.clear(); this->columnNames.clear(); } bool nodejs_db_informix::Result::hasNext() const throw() { return (this->nextRow != NULL); } std::vector<std::string>* nodejs_db_informix::Result::next() throw(nodejs_db::Exception&) { if (this->nextRow == NULL) { return NULL; } this->rowNumber++; this->previousRow = this->nextRow; this->nextRow = this->row(); return this->previousRow; } unsigned long* nodejs_db_informix::Result::columnLengths() throw(nodejs_db::Exception&) { return this->colLengths; } std::vector<std::string>* nodejs_db_informix::Result::row() throw(nodejs_db::Exception&) { std::vector<std::string> *row = new std::vector<std::string>(); ITValue *v = this->resultSet->Fetch(); if (v == NULL) { // throw nodejs_db::Exception("Cannot fetch ITValue for next row"); return NULL; } ITRow *r; //ITRow is an abstract class if (v->QueryInterface(ITRowIID, (void**) &r) == IT_QUERYINTERFACE_FAILED) { throw nodejs_db::Exception("Couldn't fetch ITRow for next row"); } else { long nc = r->NumColumns(); // number of columns // TODO: amitkr@ don't we need to free this up at some point? this->colLengths = new unsigned long[nc]; for (long i = 0; i < nc; ++i) { ITValue *cv = r->Column(i); // column value if (cv->IsNull()) { // append null row->push_back(std::string("null")); this->colLengths[i] = std::string("null").length(); } else { row->push_back(std::string(cv->Printable().Data())); this->colLengths[i] = cv->Printable().Length(); } } } return row; } uint64_t nodejs_db_informix::Result::index() const throw(std::out_of_range&) { if (this->rowNumber == 0) { throw std::out_of_range("Not standing on a row"); } return (this->rowNumber - 1); } nodejs_db_informix::Result::Column* nodejs_db_informix::Result::column(uint16_t i) const throw(std::out_of_range&) { if (i >= this->totalColumns) { throw std::out_of_range("Wrong column index"); } #ifdef DEV std::cout << *(this->columns[i]) << std::endl; #endif return this->columns[i]; } uint64_t nodejs_db_informix::Result::insertId() const throw() { return 0; } uint64_t nodejs_db_informix::Result::affectedCount() const throw() { return rowsAffected; } uint16_t nodejs_db_informix::Result::warningCount() const throw() { return 0; } uint16_t nodejs_db_informix::Result::columnCount() const throw() { return this->totalColumns; } uint64_t nodejs_db_informix::Result::count() const throw(nodejs_db::Exception&) { if (!this->isBuffered()) { throw nodejs_db::Exception("Result is not buffered"); } return 0; } bool nodejs_db_informix::Result::isBuffered() const throw() { return true; } bool nodejs_db_informix::Result::isEmpty() const throw() { return this->empty; } <|endoftext|>
<commit_before>// // Copyright (c) 2014 CNRS // Authors: Florent Lamiraux // // This file is part of hpp-core // hpp-core is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-core is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #include <algorithm> #include <hpp/util/debug.hh> #include <hpp/core/connected-component.hh> #include <hpp/core/edge.hh> #include <hpp/core/node.hh> #include <hpp/core/path.hh> #include <hpp/core/roadmap.hh> #include <hpp/core/k-d-tree.hh> namespace hpp { namespace core { std::string displayConfig (ConfigurationIn_t q) { std::ostringstream oss; for (size_type i=0; i < q.size (); ++i) { oss << q [i] << ","; } return oss.str (); } RoadmapPtr_t Roadmap::create (const DistancePtr_t& distance, const DevicePtr_t& robot) { Roadmap* ptr = new Roadmap (distance, robot); return RoadmapPtr_t (ptr); } Roadmap::Roadmap (const DistancePtr_t& distance, const DevicePtr_t& robot) : distance_ (distance), connectedComponents_ (), nodes_ (), edges_ (), initNode_ (), goalNodes_ (), kdTree_(robot, distance, 30) { } Roadmap::~Roadmap () { clear (); } const ConnectedComponents_t& Roadmap::connectedComponents () const { return connectedComponents_; } void Roadmap::clear () { connectedComponents_.clear (); for (Nodes_t::iterator it = nodes_.begin (); it != nodes_.end (); it++) { delete *it; } nodes_.clear (); for (Edges_t::iterator it = edges_.begin (); it != edges_.end (); it++) { delete *it; } edges_.clear (); goalNodes_.clear (); initNode_ = 0x0; kdTree_.clear(); } NodePtr_t Roadmap::addNode (const ConfigurationPtr_t& configuration) { value_type distance; if (nodes_.size () != 0) { NodePtr_t nearest = nearestNode (configuration, distance); if (*(nearest->configuration ()) == *configuration) { return nearest; } if (distance < 1e-4) { throw std::runtime_error ("distance to nearest node too small"); } } NodePtr_t node = new Node (configuration); hppDout (info, "Added node: " << displayConfig (*configuration)); nodes_.push_back (node); // Node constructor creates a new connected component. This new // connected component needs to be added in the roadmap and the // new node needs to be registered in the connected component. addConnectedComponent (node); return node; } NodePtr_t Roadmap::addNode (const ConfigurationPtr_t& configuration, ConnectedComponentPtr_t connectedComponent) { assert (connectedComponent); value_type distance; if (nodes_.size () != 0) { NodePtr_t nearest = nearestNode (configuration, connectedComponent, distance); if (*(nearest->configuration ()) == *configuration) { return nearest; } if (distance < 1e-4) { throw std::runtime_error ("distance to nearest node too small"); } } NodePtr_t node = new Node (configuration, connectedComponent); hppDout (info, "Added node: " << displayConfig (*configuration)); nodes_.push_back (node); // The new node needs to be registered in the connected // component. connectedComponent->addNode (node); kdTree_.addNode(node); return node; } void Roadmap::addEdges (const NodePtr_t from, const NodePtr_t& to, const PathPtr_t& path) { EdgePtr_t edge = new Edge (from, to, path); from->addOutEdge (edge); to->addInEdge (edge); edges_.push_back (edge); edge = new Edge (to, from, path->reverse ()); from->addInEdge (edge); to->addOutEdge (edge); edges_.push_back (edge); } NodePtr_t Roadmap::addNodeAndEdges (const NodePtr_t from, const ConfigurationPtr_t& to, const PathPtr_t path) { NodePtr_t nodeTo = addNode (to, from->connectedComponent ()); addEdges (from, nodeTo, path); return nodeTo; } NodePtr_t Roadmap::nearestNode (const ConfigurationPtr_t& configuration, value_type& minDistance) { NodePtr_t closest = 0x0; minDistance = std::numeric_limits<value_type>::infinity (); for (ConnectedComponents_t::const_iterator itcc = connectedComponents_.begin (); itcc != connectedComponents_.end (); itcc++) { value_type distance; NodePtr_t node; node = kdTree_.search(configuration, *itcc, distance); if (distance < minDistance) { minDistance = distance; closest = node; } } return closest; } NodePtr_t Roadmap::nearestNode (const ConfigurationPtr_t& configuration, const ConnectedComponentPtr_t& connectedComponent, value_type& minDistance) { assert (connectedComponent); return kdTree_.search(configuration, connectedComponent, minDistance); } void Roadmap::addGoalNode (const ConfigurationPtr_t& config) { NodePtr_t node = addNode (config); goalNodes_.push_back (node); } const DistancePtr_t& Roadmap::distance () const { return distance_; } EdgePtr_t Roadmap::addEdge (const NodePtr_t& n1, const NodePtr_t& n2, const PathPtr_t& path) { EdgePtr_t edge = new Edge (n1, n2, path); n1->addOutEdge (edge); n2->addInEdge (edge); edges_.push_back (edge); hppDout (info, "Added edge between: " << displayConfig (*(n1->configuration ()))); hppDout (info, " and: " << displayConfig (*(n2->configuration ()))); ConnectedComponentPtr_t cc1 = n1->connectedComponent (); ConnectedComponentPtr_t cc2 = n2->connectedComponent (); connect (cc1, cc2); return edge; } void Roadmap::addConnectedComponent (const NodePtr_t& node) { connectedComponents_.insert (node->connectedComponent ()); node->connectedComponent ()->addNode (node); kdTree_.addNode(node); } void Roadmap::connect (const ConnectedComponentPtr_t& cc1, const ConnectedComponentPtr_t& cc2) { if (cc1->canReach (cc2)) return; ConnectedComponents_t cc2Tocc1; if (cc2->canReach (cc1, cc2Tocc1)) { merge (cc1, cc2Tocc1); } else { cc1->reachableTo_.insert (cc2); cc2->reachableFrom_.insert (cc1); } } void Roadmap::merge (const ConnectedComponentPtr_t& cc1, ConnectedComponents_t& ccs) { for (ConnectedComponents_t::iterator itcc = ccs.begin (); itcc != ccs.end (); ++itcc) { if (*itcc != cc1) { cc1->merge (*itcc); #ifndef NDEBUG std::size_t nb = #endif connectedComponents_.erase (*itcc); assert (nb == 1); } } } bool Roadmap::pathExists () const { const ConnectedComponentPtr_t ccInit = initNode ()->connectedComponent (); for (Nodes_t::const_iterator itGoal = goalNodes_.begin (); itGoal != goalNodes_.end (); itGoal++) { if (ccInit->canReach ((*itGoal)->connectedComponent ())) { return true; } } return false; } } // namespace core } // namespace hpp std::ostream& operator<< (std::ostream& os, const hpp::core::Roadmap& r) { using hpp::core::Nodes_t; using hpp::core::NodePtr_t; using hpp::core::Edges_t; using hpp::core::EdgePtr_t; using hpp::core::ConnectedComponents_t; using hpp::core::ConnectedComponentPtr_t; using hpp::core::size_type; // Enumerate nodes and connected components std::map <NodePtr_t, size_type> nodeId; std::map <ConnectedComponentPtr_t, size_type> ccId; std::map <ConnectedComponentPtr_t, size_type> sccId; size_type count = 0; for (Nodes_t::const_iterator it = r.nodes ().begin (); it != r.nodes ().end (); ++it) { nodeId [*it] = count; ++count; } count = 0; for (ConnectedComponents_t::const_iterator it = r.connectedComponents ().begin (); it != r.connectedComponents ().end (); ++it) { ccId [*it] = count; ++count; } // Display list of nodes os << "----------------------------------------------------------------------" << std::endl; os << "Roadmap" << std::endl; os << "----------------------------------------------------------------------" << std::endl; os << "----------------------------------------------------------------------" << std::endl; os << "Nodes" << std::endl; os << "----------------------------------------------------------------------" << std::endl; for (Nodes_t::const_iterator it = r.nodes ().begin (); it != r.nodes ().end (); ++it) { const NodePtr_t node = *it; os << "Node " << nodeId [node] << ": " << *node << std::endl; } os << "----------------------------------------------------------------------" << std::endl; os << "Edges" << std::endl; os << "----------------------------------------------------------------------" << std::endl; for (Edges_t::const_iterator it = r.edges ().begin (); it != r.edges ().end (); ++it) { const EdgePtr_t edge = *it; os << "Edge: " << nodeId [edge->from ()] << " -> " << nodeId [edge->to ()] << std::endl; } os << "----------------------------------------------------------------------" << std::endl; os << "Connected components" << std::endl; os << "----------------------------------------------------------------------" << std::endl; for (ConnectedComponents_t::const_iterator it = r.connectedComponents ().begin (); it != r.connectedComponents ().end (); ++it) { const ConnectedComponentPtr_t cc = *it; os << "Connected component " << ccId [cc] << std::endl; os << "Nodes : "; for (Nodes_t::const_iterator itNode = cc->nodes ().begin (); itNode != cc->nodes ().end (); ++itNode) { os << nodeId [*itNode] << ", "; } os << std::endl; os << "Reachable to :"; for (ConnectedComponents_t::const_iterator itTo = cc->reachableTo ().begin (); itTo != cc->reachableTo ().end (); ++itTo) { os << ccId [*itTo] << ", "; } os << std::endl; os << "Reachable from :"; for (ConnectedComponents_t::const_iterator itFrom = cc->reachableFrom ().begin (); itFrom != cc->reachableFrom ().end (); ++itFrom) { os << ccId [*itFrom] << ", "; } os << std::endl; } os << std::endl; os << "----------------" << std::endl; return os; } <commit_msg>Assert that connected component has at least one node.<commit_after>// // Copyright (c) 2014 CNRS // Authors: Florent Lamiraux // // This file is part of hpp-core // hpp-core is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-core is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #include <algorithm> #include <hpp/util/debug.hh> #include <hpp/core/connected-component.hh> #include <hpp/core/edge.hh> #include <hpp/core/node.hh> #include <hpp/core/path.hh> #include <hpp/core/roadmap.hh> #include <hpp/core/k-d-tree.hh> namespace hpp { namespace core { std::string displayConfig (ConfigurationIn_t q) { std::ostringstream oss; for (size_type i=0; i < q.size (); ++i) { oss << q [i] << ","; } return oss.str (); } RoadmapPtr_t Roadmap::create (const DistancePtr_t& distance, const DevicePtr_t& robot) { Roadmap* ptr = new Roadmap (distance, robot); return RoadmapPtr_t (ptr); } Roadmap::Roadmap (const DistancePtr_t& distance, const DevicePtr_t& robot) : distance_ (distance), connectedComponents_ (), nodes_ (), edges_ (), initNode_ (), goalNodes_ (), kdTree_(robot, distance, 30) { } Roadmap::~Roadmap () { clear (); } const ConnectedComponents_t& Roadmap::connectedComponents () const { return connectedComponents_; } void Roadmap::clear () { connectedComponents_.clear (); for (Nodes_t::iterator it = nodes_.begin (); it != nodes_.end (); it++) { delete *it; } nodes_.clear (); for (Edges_t::iterator it = edges_.begin (); it != edges_.end (); it++) { delete *it; } edges_.clear (); goalNodes_.clear (); initNode_ = 0x0; kdTree_.clear(); } NodePtr_t Roadmap::addNode (const ConfigurationPtr_t& configuration) { value_type distance; if (nodes_.size () != 0) { NodePtr_t nearest = nearestNode (configuration, distance); if (*(nearest->configuration ()) == *configuration) { return nearest; } if (distance < 1e-4) { throw std::runtime_error ("distance to nearest node too small"); } } NodePtr_t node = new Node (configuration); hppDout (info, "Added node: " << displayConfig (*configuration)); nodes_.push_back (node); // Node constructor creates a new connected component. This new // connected component needs to be added in the roadmap and the // new node needs to be registered in the connected component. addConnectedComponent (node); return node; } NodePtr_t Roadmap::addNode (const ConfigurationPtr_t& configuration, ConnectedComponentPtr_t connectedComponent) { assert (connectedComponent); value_type distance; if (nodes_.size () != 0) { NodePtr_t nearest = nearestNode (configuration, connectedComponent, distance); if (*(nearest->configuration ()) == *configuration) { return nearest; } if (distance < 1e-4) { throw std::runtime_error ("distance to nearest node too small"); } } NodePtr_t node = new Node (configuration, connectedComponent); hppDout (info, "Added node: " << displayConfig (*configuration)); nodes_.push_back (node); // The new node needs to be registered in the connected // component. connectedComponent->addNode (node); kdTree_.addNode(node); return node; } void Roadmap::addEdges (const NodePtr_t from, const NodePtr_t& to, const PathPtr_t& path) { EdgePtr_t edge = new Edge (from, to, path); from->addOutEdge (edge); to->addInEdge (edge); edges_.push_back (edge); edge = new Edge (to, from, path->reverse ()); from->addInEdge (edge); to->addOutEdge (edge); edges_.push_back (edge); } NodePtr_t Roadmap::addNodeAndEdges (const NodePtr_t from, const ConfigurationPtr_t& to, const PathPtr_t path) { NodePtr_t nodeTo = addNode (to, from->connectedComponent ()); addEdges (from, nodeTo, path); return nodeTo; } NodePtr_t Roadmap::nearestNode (const ConfigurationPtr_t& configuration, value_type& minDistance) { NodePtr_t closest = 0x0; minDistance = std::numeric_limits<value_type>::infinity (); for (ConnectedComponents_t::const_iterator itcc = connectedComponents_.begin (); itcc != connectedComponents_.end (); itcc++) { value_type distance; NodePtr_t node; node = kdTree_.search(configuration, *itcc, distance); if (distance < minDistance) { minDistance = distance; closest = node; } } return closest; } NodePtr_t Roadmap::nearestNode (const ConfigurationPtr_t& configuration, const ConnectedComponentPtr_t& connectedComponent, value_type& minDistance) { assert (connectedComponent); assert (connectedComponent->nodes ().size () != 0); return kdTree_.search(configuration, connectedComponent, minDistance); } void Roadmap::addGoalNode (const ConfigurationPtr_t& config) { NodePtr_t node = addNode (config); goalNodes_.push_back (node); } const DistancePtr_t& Roadmap::distance () const { return distance_; } EdgePtr_t Roadmap::addEdge (const NodePtr_t& n1, const NodePtr_t& n2, const PathPtr_t& path) { EdgePtr_t edge = new Edge (n1, n2, path); n1->addOutEdge (edge); n2->addInEdge (edge); edges_.push_back (edge); hppDout (info, "Added edge between: " << displayConfig (*(n1->configuration ()))); hppDout (info, " and: " << displayConfig (*(n2->configuration ()))); ConnectedComponentPtr_t cc1 = n1->connectedComponent (); ConnectedComponentPtr_t cc2 = n2->connectedComponent (); connect (cc1, cc2); return edge; } void Roadmap::addConnectedComponent (const NodePtr_t& node) { connectedComponents_.insert (node->connectedComponent ()); node->connectedComponent ()->addNode (node); kdTree_.addNode(node); } void Roadmap::connect (const ConnectedComponentPtr_t& cc1, const ConnectedComponentPtr_t& cc2) { if (cc1->canReach (cc2)) return; ConnectedComponents_t cc2Tocc1; if (cc2->canReach (cc1, cc2Tocc1)) { merge (cc1, cc2Tocc1); } else { cc1->reachableTo_.insert (cc2); cc2->reachableFrom_.insert (cc1); } } void Roadmap::merge (const ConnectedComponentPtr_t& cc1, ConnectedComponents_t& ccs) { for (ConnectedComponents_t::iterator itcc = ccs.begin (); itcc != ccs.end (); ++itcc) { if (*itcc != cc1) { cc1->merge (*itcc); #ifndef NDEBUG std::size_t nb = #endif connectedComponents_.erase (*itcc); assert (nb == 1); } } } bool Roadmap::pathExists () const { const ConnectedComponentPtr_t ccInit = initNode ()->connectedComponent (); for (Nodes_t::const_iterator itGoal = goalNodes_.begin (); itGoal != goalNodes_.end (); itGoal++) { if (ccInit->canReach ((*itGoal)->connectedComponent ())) { return true; } } return false; } } // namespace core } // namespace hpp std::ostream& operator<< (std::ostream& os, const hpp::core::Roadmap& r) { using hpp::core::Nodes_t; using hpp::core::NodePtr_t; using hpp::core::Edges_t; using hpp::core::EdgePtr_t; using hpp::core::ConnectedComponents_t; using hpp::core::ConnectedComponentPtr_t; using hpp::core::size_type; // Enumerate nodes and connected components std::map <NodePtr_t, size_type> nodeId; std::map <ConnectedComponentPtr_t, size_type> ccId; std::map <ConnectedComponentPtr_t, size_type> sccId; size_type count = 0; for (Nodes_t::const_iterator it = r.nodes ().begin (); it != r.nodes ().end (); ++it) { nodeId [*it] = count; ++count; } count = 0; for (ConnectedComponents_t::const_iterator it = r.connectedComponents ().begin (); it != r.connectedComponents ().end (); ++it) { ccId [*it] = count; ++count; } // Display list of nodes os << "----------------------------------------------------------------------" << std::endl; os << "Roadmap" << std::endl; os << "----------------------------------------------------------------------" << std::endl; os << "----------------------------------------------------------------------" << std::endl; os << "Nodes" << std::endl; os << "----------------------------------------------------------------------" << std::endl; for (Nodes_t::const_iterator it = r.nodes ().begin (); it != r.nodes ().end (); ++it) { const NodePtr_t node = *it; os << "Node " << nodeId [node] << ": " << *node << std::endl; } os << "----------------------------------------------------------------------" << std::endl; os << "Edges" << std::endl; os << "----------------------------------------------------------------------" << std::endl; for (Edges_t::const_iterator it = r.edges ().begin (); it != r.edges ().end (); ++it) { const EdgePtr_t edge = *it; os << "Edge: " << nodeId [edge->from ()] << " -> " << nodeId [edge->to ()] << std::endl; } os << "----------------------------------------------------------------------" << std::endl; os << "Connected components" << std::endl; os << "----------------------------------------------------------------------" << std::endl; for (ConnectedComponents_t::const_iterator it = r.connectedComponents ().begin (); it != r.connectedComponents ().end (); ++it) { const ConnectedComponentPtr_t cc = *it; os << "Connected component " << ccId [cc] << std::endl; os << "Nodes : "; for (Nodes_t::const_iterator itNode = cc->nodes ().begin (); itNode != cc->nodes ().end (); ++itNode) { os << nodeId [*itNode] << ", "; } os << std::endl; os << "Reachable to :"; for (ConnectedComponents_t::const_iterator itTo = cc->reachableTo ().begin (); itTo != cc->reachableTo ().end (); ++itTo) { os << ccId [*itTo] << ", "; } os << std::endl; os << "Reachable from :"; for (ConnectedComponents_t::const_iterator itFrom = cc->reachableFrom ().begin (); itFrom != cc->reachableFrom ().end (); ++itFrom) { os << ccId [*itFrom] << ", "; } os << std::endl; } os << std::endl; os << "----------------" << std::endl; return os; } <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/wait.h> #include <sys/types.h> #include <boost/tokenizer.hpp> using namespace boost; using namespace std; void displayPrompt(){ char *user = getlogin(); //I assign the login name to a user pointer if(user == NULL){ perror("getlogin"); exit(1); } char hostname[100]; //I allocate space for the hostname if(gethostname(hostname, sizeof(hostname)) == -1){ //checking for errors withostname perror("gethostname"); exit(1); } cout << user << '@' << hostname << '$' << ' '; //here I output the user and hostanme to the screen. } /*void parseCommand(string &cmd){ char_separator<char> delim; tokenizer< char_separator<char> > mytok(cmd, delim); }*/ void executeCommand(char **argv){ int pid = fork(); if(pid == -1){ perror("There was some error with fork()"); exit(1); } else if(pid == 0){ cout << "We are in the child process!"; if(-1 == execvp(*argv, argv)){ perror("There was an error with execvp"); exit(1); } } else if(pid > 0){ if(-1 == wait(0)){ perror("There was an error with wait()"); } } } int main(void){ string cmd; while(cmd != "exit"){ displayPrompt(); //display the username and hostname getline(cin, cmd); } return 0; } //notes to try //------------ // if(strcmp(argv[0], "exit") == 0){ // exit(0); // } //------------ //execute command needs work <commit_msg>commented executeCommand and now working with parseCommands<commit_after>#include <iostream> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <sys/wait.h> #include <sys/types.h> #include <boost/tokenizer.hpp> using namespace boost; using namespace std; void displayPrompt(){ char *user = getlogin(); //I assign the login name to a user pointer if(user == NULL){ perror("getlogin"); exit(1); } char hostname[100]; //I allocate space for the hostname if(gethostname(hostname, sizeof(hostname)) == -1){ //checking for errors withostname perror("gethostname"); exit(1); } cout << user << '@' << hostname << '$' << ' '; //here I output the user and hostanme to the screen. } void parseCommand(string &cmd){ char_separator<char> delim; tokenizer< char_separator<char> > mytok(cmd, delim); } /*void executeCommand(char **argv){ int pid = fork(); if(pid == -1){ perror("There was some error with fork()"); exit(1); } else if(pid == 0){ cout << "We are in the child process!"; if(-1 == execvp(*argv, argv)){ perror("There was an error with execvp"); exit(1); } } else if(pid > 0){ if(-1 == wait(0)){ perror("There was an error with wait()"); } } }*/ int main(void){ string cmd; while(cmd != "exit"){ displayPrompt(); //display the username and hostname getline(cin, cmd); } return 0; } //notes to try //------------ // if(strcmp(argv[0], "exit") == 0){ // exit(0); // } //------------ //execute command needs work <|endoftext|>
<commit_before>#include "gen-cpp/trade_report_types.h" #include "gen-cpp/TradeHistory.h" #include <thrift/TProcessor.h> #include <thrift/transport/TBufferTransports.h> #include <thrift/protocol/TCompactProtocol.h> #include <thrift/server/TNonblockingServer.h> #include <thrift/concurrency/ThreadManager.h> #include <thrift/concurrency/PlatformThreadFactory.h> #include <boost/make_shared.hpp> #include <boost/shared_ptr.hpp> #include <thread> #include <iostream> #include <string> #include <atomic> using namespace ::apache::thrift::transport; using namespace ::apache::thrift::protocol; using namespace ::apache::thrift::server; using namespace ::apache::thrift::concurrency; using namespace ::apache::thrift; using namespace TradeReporting; using boost::shared_ptr; using boost::make_shared; using boost::dynamic_pointer_cast; class TradeHistoryHandler : virtual public TradeHistoryIf { public: TradeHistoryHandler(const TConnectionInfo & ci, int con_count) : con_id(con_count), call_count(0) { auto sock = dynamic_pointer_cast<TSocket>(ci.transport); std::string soc_info; if (sock) { soc_info = sock->getSocketInfo(); } std::cout << "[Server] ConCreate : " << std::this_thread::get_id() << ':' << con_id << ':' << call_count << " (" << soc_info << ')' << std::endl; } virtual ~TradeHistoryHandler() { std::cout << "[Server] ConDelete : " << std::this_thread::get_id() << ':' << con_id << ':' << call_count << std::endl; } void get_last_sale(TradeReport& trade, const std::string& symbol) override { trade.seq_num = (con_id * 10000) + (++call_count); trade.symbol = symbol; if (0 == symbol.compare("APPL")) { trade.price = 127.61; trade.size = 500; } else if (0 == symbol.compare("MSFT")) { trade.price = 46.23; trade.size = 400; } else { trade.price = 0.0; trade.size = 0; } std::cout << "[Server] GetLastSale(" << std::this_thread::get_id() << ':' << con_id << ':' << call_count << ") returning: " << trade.seq_num << "> " << trade.symbol << " - " << trade.size << " @ " << trade.price << std::endl; } private: const int con_id; int call_count; }; class TradeHistoryIfInstanceFactory : virtual public TradeHistoryIfFactory { public: TradeHistoryIfInstanceFactory() : con_count(0) {;} virtual TradeHistoryIf* getHandler(const TConnectionInfo & ci) override { return new TradeHistoryHandler(ci, ++con_count); } virtual void releaseHandler(TradeHistoryIf * handler) override { delete handler; } private: int con_count; }; int main() { //Setup server parameters auto port = 9090; auto hw_threads = std::thread::hardware_concurrency(); int io_threads = hw_threads / 2 + 1; int worker_threads = hw_threads * 1.5 + 1; //Create I/O factories auto handler_fac = make_shared<TradeHistoryIfInstanceFactory>(); auto proc_fac = make_shared<TradeHistoryProcessorFactory>(handler_fac); auto proto_fac = make_shared<TCompactProtocolFactoryT<TMemoryBuffer>>(); //Setup the worker-thread manager auto thread_man = ThreadManager::newSimpleThreadManager(worker_threads); thread_man->threadFactory(make_shared<PlatformThreadFactory>()); thread_man->start(); //Start the server on a background thread TNonblockingServer server(proc_fac, proto_fac, port, thread_man); server.setNumIOThreads(io_threads); std::thread server_thread([&server](){server.serve();}); //Log status and wait for user to quit std::string str; do { std::cout << "[Server (" << hw_threads << ", " << server.getNumIOThreads() << '/' << thread_man->workerCount() << "):" << port << "] Enter 'q' to quit" << std::endl; std::getline(std::cin, str); } while (str[0] != 'q'); //Stop the server, wait for I/O and worker threads then exit server.stop(); std::cout << "waiting for server to exit..." << std::endl; server_thread.join(); std::cout << "service complete, exiting." << std::endl; return 0; } <commit_msg>cpp nbsvr clean up<commit_after>#include "gen-cpp/trade_report_types.h" #include "gen-cpp/TradeHistory.h" #include <thrift/TProcessor.h> #include <thrift/transport/TBufferTransports.h> #include <thrift/protocol/TCompactProtocol.h> #include <thrift/server/TNonblockingServer.h> #include <thrift/concurrency/ThreadManager.h> #include <thrift/concurrency/PlatformThreadFactory.h> #include <boost/make_shared.hpp> #include <boost/shared_ptr.hpp> #include <thread> #include <iostream> #include <string> #include <atomic> using namespace ::apache::thrift::transport; using namespace ::apache::thrift::protocol; using namespace ::apache::thrift::server; using namespace ::apache::thrift::concurrency; using namespace ::apache::thrift; using namespace TradeReporting; using boost::shared_ptr; using boost::make_shared; using boost::dynamic_pointer_cast; class TradeHistoryHandler : virtual public TradeHistoryIf { public: TradeHistoryHandler(const TConnectionInfo & ci, int con_count) : con_id(con_count), call_count(0) { auto sock = dynamic_pointer_cast<TSocket>(ci.transport); std::string soc_info; if (sock) { soc_info = sock->getSocketInfo(); } std::cout << "[Server] ConCreate : " << std::this_thread::get_id() << ':' << con_id << ':' << call_count << " (" << soc_info << ')' << std::endl; } virtual ~TradeHistoryHandler() { std::cout << "[Server] ConDelete : " << std::this_thread::get_id() << ':' << con_id << ':' << call_count << std::endl; } void get_last_sale(TradeReport& trade, const std::string& symbol) override { trade.seq_num = (con_id * 10000) + (++call_count); trade.symbol = symbol; if (0 == symbol.compare("APPL")) { trade.price = 127.61; trade.size = 500; } else if (0 == symbol.compare("MSFT")) { trade.price = 46.23; trade.size = 400; } else { trade.price = 0.0; trade.size = 0; } std::cout << "[Server] GetLastSale(" << std::this_thread::get_id() << ':' << con_id << ':' << call_count << ") returning: " << trade.seq_num << "> " << trade.symbol << " - " << trade.size << " @ " << trade.price << std::endl; } private: const int con_id; int call_count; }; class TradeHistoryFactory : virtual public TradeHistoryIfFactory { public: TradeHistoryFactory() : con_count(0) {;} virtual TradeHistoryIf* getHandler(const TConnectionInfo & ci) override { return new TradeHistoryHandler(ci, ++con_count); } virtual void releaseHandler(TradeHistoryIf * handler) override { delete handler; } private: int con_count; }; int main() { //Setup server parameters auto port = 9090; auto hw_threads = std::thread::hardware_concurrency(); int io_threads = hw_threads / 2 + 1; int worker_threads = hw_threads * 1.5 + 1; //Create I/O factories auto handler_fac = make_shared<TradeHistoryFactory>(); auto proc_fac = make_shared<TradeHistoryProcessorFactory>(handler_fac); auto proto_fac = make_shared<TCompactProtocolFactoryT<TMemoryBuffer>>(); //Setup the worker-thread manager auto thread_man = ThreadManager::newSimpleThreadManager(worker_threads); thread_man->threadFactory(make_shared<PlatformThreadFactory>()); thread_man->start(); //Start the server on a background thread TNonblockingServer server(proc_fac, proto_fac, port, thread_man); server.setNumIOThreads(io_threads); std::thread server_thread([&server](){server.serve();}); //Log status and wait for user to quit std::string str; do { std::cout << "[Server (" << hw_threads << ", " << server.getNumIOThreads() << '/' << thread_man->workerCount() << "):" << port << "] Enter 'q' to quit" << std::endl; std::getline(std::cin, str); } while (str[0] != 'q'); //Stop the server, wait for I/O and worker threads then exit server.stop(); std::cout << "waiting for server to exit..." << std::endl; server_thread.join(); std::cout << "service complete, exiting." << std::endl; return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <stdlib.h> #include <unistd.h> // Sys calls #include <stdio.h> #include <sys/wait.h> // Wait #include <errno.h> // perror() #include <string.h> // strtok #include <cstring> // strcpy() #include <vector> #include <array> void user_prompt(std::string& user) { char login[1024]; if(getlogin_r(login, sizeof(login)-1) != 0) perror("getlogin"); std::string name = login; if(gethostname(login, sizeof(login)-1) == -1) perror("gethostname"); std::string host = login; name += "@"; user = name + host; } bool execute(char** commands) { if(*commands == NULL) { return false; } int status = 0; int pid = fork(); if(pid == -1) { perror("fork"); exit(1); } else if(pid == 0) { status = execvp(commands[0], commands); if(status == -1) { perror("execvp"); exit(1); } } else { int wait = waitpid(pid, &status, 0); if(wait == -1) perror("wait"); std::string cond = commands[0]; if(cond == "true") return true; if(cond == "false") return false; } return true; } int main() { std::string user; user_prompt(user); // Gets login/host info std::string cmd_line; int array_sz = 4096; while(std::cin.good()) { std::cout << user << "$ "; // Prompt and input getline(std::cin, cmd_line); int x = cmd_line.find("#", 0); if(x >= 0) cmd_line = cmd_line.substr(0, x); char* cmd_str = new char [cmd_line.length()+1]; std::strcpy(cmd_str, cmd_line.c_str()); char** commands = new char*[array_sz]; int i = 0; char* cmd = std::strtok(cmd_str, " \t"); while(cmd != NULL) // Populate array of char { // pointers to cmds and flags commands[i] = cmd; cmd = std::strtok(NULL, " \t"); ++i; } std::string exit_key = commands[0]; if(exit_key == "exit") { return 0; } int pid = fork(); if(pid == 0) { execvp(commands[0], commands); } else { if(pid == -1) { perror("fork"); exit(1); } wait(0); } for(unsigned int d = 0; d < sizeof(commands); ++d) { commands[d] = '\0'; } } } <commit_msg>Implemented true, false, amd && and || connectors<commit_after>#include <iostream> #include <stdlib.h> #include <unistd.h> // Sys calls #include <stdio.h> #include <sys/wait.h> // Wait #include <errno.h> // perror() #include <string.h> // strtok #include <cstring> // strcpy() #include <vector> void user_prompt(std::string& user) { char login[1024]; if(getlogin_r(login, sizeof(login)-1) != 0) perror("getlogin"); std::string name = login; if(gethostname(login, sizeof(login)-1) == -1) perror("gethostname"); std::string host = login; name += "@"; user = name + host; } bool execute(char** commands) { if(*commands == NULL) { return false; } int status = 0; int pid = fork(); if(pid == -1) { perror("fork"); exit(1); } else if(pid == 0) { status = execvp(commands[0], commands); if(status == -1) { perror("execvp"); exit(1); } } else { int wait = waitpid(pid, &status, 0); if(wait == -1) perror("wait"); std::string cond = commands[0]; if(cond == "true") return true; if(cond == "false") return false; } return true; } int main() { std::string user; user_prompt(user); // Gets login/host info std::string cmd_line; int array_sz = 4096; while(std::cin.good()) { bool prev = true; std::cout << user << "$ "; // Prompt and input getline(std::cin, cmd_line); int x = cmd_line.find("#", 0); if(x >= 0) cmd_line = cmd_line.substr(0, x); char* cmd_str = new char [cmd_line.length()+1]; std::strcpy(cmd_str, cmd_line.c_str()); char** commands = new char*[array_sz]; std::string key; std::string logic; int i = 0; char* cmd = std::strtok(cmd_str, " \t"); while(cmd != NULL) // First command apart from connectors { logic = cmd; if(logic == "||" || logic == "&&" || logic == ";") break; else{ commands[i] = cmd; ++i; cmd = std::strtok(NULL, " \t"); } } key = logic; if(commands[0] != NULL) { logic = commands[0]; if(logic == "exit") return 0; prev = execute(commands); } for(unsigned int j = 0; j < sizeof(commands); ++j) { commands[j] = '\0'; } cmd = std::strtok(NULL, " \t"); i = 0; while(cmd != NULL) // Everything else w/ connector calculation { std::cout << key << " "; logic = cmd; if(logic != "||" && logic != "&&" && logic != ";") { commands[i] = cmd; ++i; } else if(logic == "||") { key = logic; logic = commands[0]; if(logic == "exit") return 0; if(!prev) prev = execute(commands); else prev = 0; for(unsigned int j = 0; j < sizeof(commands); ++j) { commands[j] = '\0'; } i = 0; } else if(logic == "&&") { key = logic; logic = commands[0]; if(logic == "exit") return 0; if(prev) prev = execute(commands); for(unsigned int j = 0; j < sizeof(commands); ++j) { commands[j] = '\0'; } i = 0; } cmd = std::strtok(NULL, " \t"); } if(i != 0) { std::cout << key << std::endl; if(key == "||") if(!prev) execute(commands); if(key == "&&") if(prev) execute(commands); if(key == ";") execute(commands); } } } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <queue> #include <vector> #include <algorithm> #include <errno.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> using namespace std; const string cmd_delimiter = ";|&#"; void splice_input(queue<string> &cmds, queue<char> &conns, const string &input); string get_input(const string &input, int &start, int &end); int find_delimiter(const string &input, int &start); bool run_command(string &input, char &conn); void tokenize(vector<char*> &comms, string &input); int main() { string input; char logic; queue<string> commands; queue<char> connectors; bool running = true; while(1) { cout << "$ "; getline(cin, input); splice_input(commands, connectors, input); while(!commands.empty() && running) { input = commands.front(); commands.pop(); if(!connectors.empty()) { logic = connectors.front(); connectors.pop(); } if(input.find("exit") == string::npos) running = run_command(input, logic); else exit(1); if(!running) { connectors = queue<char>(); commands = queue<string>(); } } running = true; } return 0; } void splice_input(queue<string> &cmds, queue<char> &conns, const string &input) { int pos = 0; char logic; string new_cmd; string parse = input; while(pos != -1) { pos = parse.find_first_of(cmd_delimiter); new_cmd = parse.substr(0, pos); logic = parse[pos]; while(new_cmd[0] == ' ') new_cmd = new_cmd.substr(1, new_cmd.length()); if(logic == '&' || logic == '|') { cmds.push(new_cmd); parse.erase(0, pos + 2); } else if(logic == ';') { cmds.push(new_cmd); parse.erase(0, pos + 1); } else cmds.push(new_cmd); if(logic == '#') return; conns.push(logic); } } bool run_command(string &input, char &conn) { pid_t pid = fork(); vector<char*> tokens; int status = 0; if(pid == -1) { perror("Error with fork()"); exit(1); } else if(pid == 0) { tokenize(tokens, input); char **cmds = &tokens[0]; execvp(cmds[0], cmds); perror("Execvp failed!"); exit(1); } else { wait(&status); if(conn == '&') { if(status > 0) return false; } } return true; } void tokenize(vector<char*> &comms, string &input) { string convert; string tokenizer = input; size_t pos = 0; while(pos != string::npos) { pos = tokenizer.find(' '); convert = pos == string::npos ? tokenizer \ : tokenizer.substr(0, pos); convert.erase(std::remove_if(convert.begin(), convert.end(), ::isspace), convert.end()); if(!convert.empty()) { char *tmp = new char[convert.length() + 1]; strcpy(tmp, convert.c_str()); comms.push_back(tmp); tokenizer.erase(0, pos + 1); } } comms.push_back(NULL); return; } <commit_msg>Fixed a potential memory leak issue.<commit_after>#include <iostream> #include <string> #include <queue> #include <vector> #include <algorithm> #include <errno.h> #include <sys/types.h> #include <sys/wait.h> #include <string.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> using namespace std; const string cmd_delimiter = ";|&#"; void splice_input(queue<string> &cmds, queue<char> &conns, const string &input); string get_input(const string &input, int &start, int &end); int find_delimiter(const string &input, int &start); bool run_command(string &input, char &conn); void tokenize(vector<char*> &comms, string &input); int main() { string input; char logic; queue<string> commands; queue<char> connectors; bool running = true; while(1) { cout << "$ "; getline(cin, input); splice_input(commands, connectors, input); while(!commands.empty() && running) { input = commands.front(); commands.pop(); if(!connectors.empty()) { logic = connectors.front(); connectors.pop(); } if(input.find("exit") == string::npos) running = run_command(input, logic); else exit(1); if(!running) { connectors = queue<char>(); commands = queue<string>(); } } running = true; } return 0; } void splice_input(queue<string> &cmds, queue<char> &conns, const string &input) { int pos = 0; char logic; string new_cmd; string parse = input; while(pos != -1) { pos = parse.find_first_of(cmd_delimiter); new_cmd = parse.substr(0, pos); logic = parse[pos]; while(new_cmd[0] == ' ') new_cmd = new_cmd.substr(1, new_cmd.length()); if(logic == '&' || logic == '|') { cmds.push(new_cmd); parse.erase(0, pos + 2); } else if(logic == ';') { cmds.push(new_cmd); parse.erase(0, pos + 1); } else cmds.push(new_cmd); if(logic == '#') return; conns.push(logic); } } bool run_command(string &input, char &conn) { pid_t pid = fork(); vector<char*> tokens; int status = 0; if(pid == -1) { perror("Error with fork()"); exit(1); } else if(pid == 0) { tokenize(tokens, input); char **cmds = &tokens[0]; execvp(cmds[0], cmds); perror("Execvp failed!"); exit(1); } else { wait(&status); tokens.clear(); if(conn == '&') { if(status > 0) return false; } } return true; } void tokenize(vector<char*> &comms, string &input) { string convert; string tokenizer = input; size_t pos = 0; while(pos != string::npos) { pos = tokenizer.find(' '); convert = pos == string::npos ? tokenizer \ : tokenizer.substr(0, pos); convert.erase(std::remove_if(convert.begin(), convert.end(), ::isspace), convert.end()); if(!convert.empty()) { char *tmp = new char[convert.length() + 1]; strcpy(tmp, convert.c_str()); comms.push_back(tmp); tokenizer.erase(0, pos + 1); } } comms.push_back(NULL); return; } <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include <string.h> #include <cstdlib> #include <errno.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> using namespace std; int main(int argc, char** argv) { if(argc == 0) { cout << "No argument." << endl; exit(1); } int pid = fork(); if(pid == 0) { // argv[0] = new char[6]; // strcpy(argv[0], "ls"); // argv[1] = new char[6]; // strcpy(argv[1], "-a"); // argv[2] = new char [6]; // strcpy(argv[2], "-l"); cout << "before" << endl; int r = execvp(argv[1], argv); if(r == -1) { perror("execvp"); exit(1); } cout << "after" << endl; } else { wait(NULL); } return 0; } <commit_msg>more attempts at getting rshell to work<commit_after>#include <boost/tokenizer.hpp> #include <iostream> #include <unistd.h> #include <string.h> #include <cstdlib> #include <errno.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <string> #include <sstream> using namespace boost; using namespace std; int main(int argc, char** argv) { if(argc == 0) { cout << "No argument." << endl; exit(1); } stringstream input; for(int i = 0; i < argc; ++i) { input << argv[i] << " "; } string sent; input >> sent; tokenizer<> tok(sent); for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg) { cout << *beg << "\n"; } int pid = fork(); if(pid == -1) { perror("fork"); exit(1); } if(pid == 0) { //char *argv2[4]; //argv2[0] = new char[6]; //strcpy(argv[0], "ls"); //argv2[1] = new char[6]; //strcpy(argv[1], "-a"); //argv2[2] = new char [6]; //strcpy(argv[2], "-l"); int pid2 = fork(); if(pid2 == -1) { perror("fork"); exit(1); } if(pid2 == 0) { if(execvp(argv[0], argv) == -1) { perror("execvp"); exit(1); } } else { if(-1 == waitpid(pid2,&pid2,0 )) perror("waitpid"); } if(execvp(argv[1], argv) == -1) { perror("execvp"); exit(1); } cout << "after" << endl; } else { if(-1 == waitpid(pid, &pid, 0)) perror("waitpid"); } return 0; } <|endoftext|>
<commit_before>/* * String hash map. * * author: Max Kellermann <mk@cm4all.com> */ #include "strmap.hxx" #include "pool.hxx" #include <string.h> bool StringMap::Item::Compare::Less(const char *a, const char *b) const { return strcmp(a, b) < 0; } StringMap::Item * StringMap::Item::Cloner::operator()(const Item &src) const { return NewFromPool<Item>(pool, p_strdup(&pool, src.key), p_strdup(&pool, src.value)); } StringMap::Item * StringMap::Item::ShallowCloner::operator()(const Item &src) const { return NewFromPool<Item>(pool, ShallowCopy(), src); } StringMap::StringMap(struct pool &_pool, const StringMap &src) :pool(_pool) { map.clone_from(src.map, Item::Cloner(pool), [](Item *){}); } StringMap::StringMap(struct pool &_pool, const StringMap *src) :pool(_pool) { if (src != nullptr) map.clone_from(src->map, Item::Cloner(pool), [](Item *){}); } StringMap::StringMap(ShallowCopy, struct pool &_pool, const StringMap &src) :pool(_pool) { map.clone_from(src.map, Item::ShallowCloner(pool), [](Item *){}); } void StringMap::Clear() { map.clear_and_dispose(PoolDisposer(pool)); } void StringMap::Add(const char *key, const char *value) { Item *item = NewFromPool<Item>(pool, key, value); map.insert(*item); } const char * StringMap::Set(const char *key, const char *value) { auto i = map.upper_bound(key, Item::Compare()); if (i != map.begin() && strcmp(std::prev(i)->key, key) == 0) { --i; const char *old_value = i->value; i->value = value; return old_value; } else { map.insert_before(i, *NewFromPool<Item>(pool, key, value)); return nullptr; } } const char * StringMap::Remove(const char *key) { auto i = map.find(key, Item::Compare()); if (i == map.end()) return nullptr; const char *value = i->value; map.erase_and_dispose(i, PoolDisposer(pool)); return value; } void StringMap::RemoveAll(const char *key) { map.erase_and_dispose(key, Item::Compare(), PoolDisposer(pool)); } void StringMap::SecureSet(const char *key, const char *value) { auto r = map.equal_range(key, Item::Compare()); if (r.first != r.second) { if (value != nullptr) { /* replace the first value */ r.first->value = value; ++r.first; } /* and erase all other values with the same key */ map.erase_and_dispose(r.first, r.second, PoolDisposer(pool)); } else if (value != nullptr) map.insert_before(r.second, *NewFromPool<Item>(pool, key, value)); } const char * StringMap::Get(const char *key) const { auto i = map.find(key, Item::Compare()); if (i == map.end()) return nullptr; return i->value; } std::pair<StringMap::const_iterator, StringMap::const_iterator> StringMap::EqualRange(const char *key) const { return map.equal_range(key, Item::Compare()); } StringMap * strmap_new(struct pool *pool) { return NewFromPool<StringMap>(*pool, *pool); } StringMap *gcc_malloc strmap_dup(struct pool *pool, const StringMap *src) { return NewFromPool<StringMap>(*pool, *pool, *src); } <commit_msg>strmap: add missing include<commit_after>/* * String hash map. * * author: Max Kellermann <mk@cm4all.com> */ #include "strmap.hxx" #include "pool.hxx" #include <iterator> #include <string.h> bool StringMap::Item::Compare::Less(const char *a, const char *b) const { return strcmp(a, b) < 0; } StringMap::Item * StringMap::Item::Cloner::operator()(const Item &src) const { return NewFromPool<Item>(pool, p_strdup(&pool, src.key), p_strdup(&pool, src.value)); } StringMap::Item * StringMap::Item::ShallowCloner::operator()(const Item &src) const { return NewFromPool<Item>(pool, ShallowCopy(), src); } StringMap::StringMap(struct pool &_pool, const StringMap &src) :pool(_pool) { map.clone_from(src.map, Item::Cloner(pool), [](Item *){}); } StringMap::StringMap(struct pool &_pool, const StringMap *src) :pool(_pool) { if (src != nullptr) map.clone_from(src->map, Item::Cloner(pool), [](Item *){}); } StringMap::StringMap(ShallowCopy, struct pool &_pool, const StringMap &src) :pool(_pool) { map.clone_from(src.map, Item::ShallowCloner(pool), [](Item *){}); } void StringMap::Clear() { map.clear_and_dispose(PoolDisposer(pool)); } void StringMap::Add(const char *key, const char *value) { Item *item = NewFromPool<Item>(pool, key, value); map.insert(*item); } const char * StringMap::Set(const char *key, const char *value) { auto i = map.upper_bound(key, Item::Compare()); if (i != map.begin() && strcmp(std::prev(i)->key, key) == 0) { --i; const char *old_value = i->value; i->value = value; return old_value; } else { map.insert_before(i, *NewFromPool<Item>(pool, key, value)); return nullptr; } } const char * StringMap::Remove(const char *key) { auto i = map.find(key, Item::Compare()); if (i == map.end()) return nullptr; const char *value = i->value; map.erase_and_dispose(i, PoolDisposer(pool)); return value; } void StringMap::RemoveAll(const char *key) { map.erase_and_dispose(key, Item::Compare(), PoolDisposer(pool)); } void StringMap::SecureSet(const char *key, const char *value) { auto r = map.equal_range(key, Item::Compare()); if (r.first != r.second) { if (value != nullptr) { /* replace the first value */ r.first->value = value; ++r.first; } /* and erase all other values with the same key */ map.erase_and_dispose(r.first, r.second, PoolDisposer(pool)); } else if (value != nullptr) map.insert_before(r.second, *NewFromPool<Item>(pool, key, value)); } const char * StringMap::Get(const char *key) const { auto i = map.find(key, Item::Compare()); if (i == map.end()) return nullptr; return i->value; } std::pair<StringMap::const_iterator, StringMap::const_iterator> StringMap::EqualRange(const char *key) const { return map.equal_range(key, Item::Compare()); } StringMap * strmap_new(struct pool *pool) { return NewFromPool<StringMap>(*pool, *pool); } StringMap *gcc_malloc strmap_dup(struct pool *pool, const StringMap *src) { return NewFromPool<StringMap>(*pool, *pool, *src); } <|endoftext|>
<commit_before>#include "system.hpp" #include <thread> #include <dirent.h> #include <sys/stat.h> #if defined ARCH_LIN #include <pthread.h> #include <sched.h> #endif #if defined ARCH_WIN #include <windows.h> #include <shellapi.h> #include <processthreadsapi.h> #endif namespace rack { namespace system { std::list<std::string> listEntries(const std::string &path) { std::list<std::string> filenames; DIR *dir = opendir(path.c_str()); if (dir) { struct dirent *d; while ((d = readdir(dir))) { std::string filename = d->d_name; if (filename == "." || filename == "..") continue; filenames.push_back(path + "/" + filename); } closedir(dir); } return filenames; } bool isFile(const std::string &path) { struct stat statbuf; if (stat(path.c_str(), &statbuf)) return false; return S_ISREG(statbuf.st_mode); } bool isDirectory(const std::string &path) { struct stat statbuf; if (stat(path.c_str(), &statbuf)) return false; return S_ISDIR(statbuf.st_mode); } void copyFile(const std::string &srcPath, const std::string &destPath) { // Open files FILE *source = fopen(srcPath.c_str(), "rb"); if (!source) return; DEFER({ fclose(source); }); FILE *dest = fopen(destPath.c_str(), "wb"); if (!dest) return; DEFER({ fclose(dest); }); // Copy buffer const int bufferSize = (1<<15); char buffer[bufferSize]; while (1) { size_t size = fread(buffer, 1, bufferSize, source); if (size == 0) break; size = fwrite(buffer, 1, size, dest); if (size == 0) break; } } void createDirectory(const std::string &path) { #if defined ARCH_WIN CreateDirectory(path.c_str(), NULL); #else mkdir(path.c_str(), 0755); #endif } int getPhysicalCoreCount() { // TODO Return the physical cores, not logical cores. return std::thread::hardware_concurrency(); } void setThreadName(const std::string &name) { #if defined ARCH_LIN || defined ARCH_MAC pthread_setname_np(pthread_self(), name.c_str()); #elif defined ARCH_WIN SetThreadDescription(GetCurrentThread(), name.c_str()); #endif } void setThreadRealTime() { #if defined ARCH_LIN || defined ARCH_MAC int policy = SCHED_RR; struct sched_param param; param.sched_priority = sched_get_priority_max(policy); pthread_setschedparam(pthread_self(), policy, &param); #elif defined ARCH_WIN // Set entire process as realtime SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); #endif } void openBrowser(const std::string &url) { #if defined ARCH_LIN std::string command = "xdg-open " + url; (void) std::system(command.c_str()); #endif #if defined ARCH_MAC std::string command = "open " + url; std::system(command.c_str()); #endif #if defined ARCH_WIN ShellExecute(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL); #endif } } // namespace system } // namespace rack <commit_msg>Remove SetThreadDescription call on windows.<commit_after>#include "system.hpp" #include <thread> #include <dirent.h> #include <sys/stat.h> #if defined ARCH_LIN #include <pthread.h> #include <sched.h> #endif #if defined ARCH_WIN #include <windows.h> #include <shellapi.h> #endif namespace rack { namespace system { std::list<std::string> listEntries(const std::string &path) { std::list<std::string> filenames; DIR *dir = opendir(path.c_str()); if (dir) { struct dirent *d; while ((d = readdir(dir))) { std::string filename = d->d_name; if (filename == "." || filename == "..") continue; filenames.push_back(path + "/" + filename); } closedir(dir); } return filenames; } bool isFile(const std::string &path) { struct stat statbuf; if (stat(path.c_str(), &statbuf)) return false; return S_ISREG(statbuf.st_mode); } bool isDirectory(const std::string &path) { struct stat statbuf; if (stat(path.c_str(), &statbuf)) return false; return S_ISDIR(statbuf.st_mode); } void copyFile(const std::string &srcPath, const std::string &destPath) { // Open files FILE *source = fopen(srcPath.c_str(), "rb"); if (!source) return; DEFER({ fclose(source); }); FILE *dest = fopen(destPath.c_str(), "wb"); if (!dest) return; DEFER({ fclose(dest); }); // Copy buffer const int bufferSize = (1<<15); char buffer[bufferSize]; while (1) { size_t size = fread(buffer, 1, bufferSize, source); if (size == 0) break; size = fwrite(buffer, 1, size, dest); if (size == 0) break; } } void createDirectory(const std::string &path) { #if defined ARCH_WIN CreateDirectory(path.c_str(), NULL); #else mkdir(path.c_str(), 0755); #endif } int getPhysicalCoreCount() { // TODO Return the physical cores, not logical cores. return std::thread::hardware_concurrency(); } void setThreadName(const std::string &name) { #if defined ARCH_LIN || defined ARCH_MAC pthread_setname_np(pthread_self(), name.c_str()); #elif defined ARCH_WIN // Unsupported on Windows #endif } void setThreadRealTime() { #if defined ARCH_LIN || defined ARCH_MAC // Round-robin scheduler policy int policy = SCHED_RR; struct sched_param param; param.sched_priority = sched_get_priority_max(policy); pthread_setschedparam(pthread_self(), policy, &param); #elif defined ARCH_WIN // Set process class first SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL); #endif } void openBrowser(const std::string &url) { #if defined ARCH_LIN std::string command = "xdg-open " + url; (void) std::system(command.c_str()); #endif #if defined ARCH_MAC std::string command = "open " + url; std::system(command.c_str()); #endif #if defined ARCH_WIN ShellExecute(NULL, "open", url.c_str(), NULL, NULL, SW_SHOWNORMAL); #endif } } // namespace system } // namespace rack <|endoftext|>
<commit_before>#define BOOST_TEST_MODULE testHdf #include "boost/test/included/unit_test.hpp" #include "H5Array.hh" #include "arrayCommon.hh" #include <algorithm> #include <iostream> struct HdfFixture { HdfFixture() {} ~HdfFixture() {} }; char fName[] = "sxrcom10-r0232.h5"; char path[] = "/Configure:0000/Run:0000/CalibCycle:0000/Camera::FrameV1/SxrBeamline.0:Opal1000.1/image"; BOOST_FIXTURE_TEST_SUITE(Hdf, HdfFixture) BOOST_AUTO_TEST_CASE(testH5Array) { H5Array h(fName, path); } BOOST_AUTO_TEST_CASE(checkDesc) { H5Array h(fName, path); SalVectorPtr sal = h.getScidbAttrs(); std::cout << "Checking descriptor for file:" << fName << " on path " << path << std::endl; std::copy(sal->begin(), sal->end(), std::ostream_iterator<ScidbAttrLite>(std::cout, " ")); SdlVectorPtr sdl = h.getScidbDims(); std::copy(sdl->begin(), sdl->end(), std::ostream_iterator<ScidbDimLite>(std::cout, " ")); std::cout << "done." << std::endl; } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Add test for slab iterator<commit_after>#define BOOST_TEST_MODULE testHdf #include "boost/test/included/unit_test.hpp" #include "H5Array.hh" #include "arrayCommon.hh" #include <algorithm> #include <iostream> struct HdfFixture { HdfFixture() {} ~HdfFixture() {} }; char fName[] = "sxrcom10-r0232.h5"; char path[] = "/Configure:0000/Run:0000/CalibCycle:0000/Camera::FrameV1/SxrBeamline.0:Opal1000.1/image"; BOOST_FIXTURE_TEST_SUITE(Hdf, HdfFixture) BOOST_AUTO_TEST_CASE(testH5Array) { H5Array h(fName, path); } BOOST_AUTO_TEST_CASE(checkDesc) { H5Array h(fName, path); SalVectorPtr sal = h.getScidbAttrs(); std::cout << "Checking descriptor for file:" << fName << " on path " << path << std::endl; std::copy(sal->begin(), sal->end(), std::ostream_iterator<ScidbAttrLite>(std::cout, " ")); SdlVectorPtr sdl = h.getScidbDims(); std::copy(sdl->begin(), sdl->end(), std::ostream_iterator<ScidbDimLite>(std::cout, " ")); std::cout << "done." << std::endl; } BOOST_AUTO_TEST_CASE(checkSlabIter) { H5Array h(fName, path); std::cout << "Iterating... " << fName << " --> " << path << std::endl; std::cout << "begin: " << h.begin() << std::endl; std::cout << "end: " << h.end() << std::endl; for(H5Array::SlabIter i = h.begin(); i != h.end(); ++i) { std::cout << i << std::endl; } } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include <cpr/cpr.h> #include <json/json.h> #include <iomanip> #include <sstream> #include "lynxbot.h" #include "timers.h" #define MAX_URL 128 static const char *UPTIME_API = "https://api.twitch.tv/kraken/streams/"; static time_t bot_time; static time_t chan_time; /* init_timers: initialize bot and channel start timers */ void init_timers(const char *channel) { bot_time = time(NULL); check_channel(channel); } /* check_channel: update stream start timer */ void check_channel(const char *channel) { cpr::Response resp; Json::Reader reader; Json::Value val; char url[MAX_URL]; struct tm start; std::istringstream ss; _sprintf(url, MAX_URL, "%s%s", UPTIME_API, channel); resp = cpr::Get(cpr::Url(url), cpr::Header{{ "Connection", "close" }}); printf("%s\n", resp.text.c_str()); if (!reader.parse(resp.text, val)) { fprintf(stderr, "could not parse uptime response\n"); return; } if (val["stream"].isNull()) { chan_time = 0; return; } ss = std::istringstream(val["stream"]["created_at"].asString()); #ifdef __linux__ ss.imbue(std::locale("en_US.utf-8")); #endif #ifdef _WIN32 ss.imbue(std::locale("en-US")); #endif ss >> std::get_time(&start, "%Y-%m-%dT%H:%M:%S"); start.tm_isdst = 0; chan_time = std::mktime(&start); } /* bot_uptime: return how long bot has been running */ time_t bot_uptime() { return time(NULL) - bot_time; } /* channel_uptime: return how long stream has been live */ time_t channel_uptime() { if (chan_time == 0) return 0; time_t now; struct tm curr; now = time(NULL); #ifdef __linux__ curr = *std::gmtime(&now); #endif #ifdef _WIN32 gmtime_s(&curr, &now); #endif curr.tm_isdst = 0; now = std::mktime(&curr); return now - chan_time; } <commit_msg>Remove print<commit_after>#include <cpr/cpr.h> #include <json/json.h> #include <iomanip> #include <sstream> #include "lynxbot.h" #include "timers.h" #define MAX_URL 128 static const char *UPTIME_API = "https://api.twitch.tv/kraken/streams/"; static time_t bot_time; static time_t chan_time; /* init_timers: initialize bot and channel start timers */ void init_timers(const char *channel) { bot_time = time(NULL); check_channel(channel); } /* check_channel: update stream start timer */ void check_channel(const char *channel) { cpr::Response resp; Json::Reader reader; Json::Value val; char url[MAX_URL]; struct tm start; std::istringstream ss; _sprintf(url, MAX_URL, "%s%s", UPTIME_API, channel); resp = cpr::Get(cpr::Url(url), cpr::Header{{ "Connection", "close" }}); if (!reader.parse(resp.text, val)) { fprintf(stderr, "could not parse uptime response\n"); return; } if (val["stream"].isNull()) { chan_time = 0; return; } ss = std::istringstream(val["stream"]["created_at"].asString()); #ifdef __linux__ ss.imbue(std::locale("en_US.utf-8")); #endif #ifdef _WIN32 ss.imbue(std::locale("en-US")); #endif ss >> std::get_time(&start, "%Y-%m-%dT%H:%M:%S"); start.tm_isdst = 0; chan_time = std::mktime(&start); } /* bot_uptime: return how long bot has been running */ time_t bot_uptime() { return time(NULL) - bot_time; } /* channel_uptime: return how long stream has been live */ time_t channel_uptime() { if (chan_time == 0) return 0; time_t now; struct tm curr; now = time(NULL); #ifdef __linux__ curr = *std::gmtime(&now); #endif #ifdef _WIN32 gmtime_s(&curr, &now); #endif curr.tm_isdst = 0; now = std::mktime(&curr); return now - chan_time; } <|endoftext|>
<commit_before>// Copyright 2008 Paul Hodge #include "common_headers.h" #include "circa.h" #include "values.h" namespace circa { void alloc_value(Term* term) { term->value = alloc_from_type(term->type); update_owner(term); } void dealloc_value(Term* term) { if (term->value == NULL) return; if (term->type == NULL) return; if (term->type->value == NULL) throw std::runtime_error("type is undefined"); if (term->ownsValue) { if (as_type(term->type).dealloc == NULL) throw std::runtime_error("type " + as_type(term->type).name + " has no dealloc function"); as_type(term->type).dealloc(term->value); } term->value = NULL; } void recycle_value(Term* source, Term* dest) { assert_type(source, dest->type); // Usually don't steal. Later, as an optimization, we will sometimes steal. bool steal = false; // Steal if this type has no copy function if (as_type(source->type).copy == NULL) steal = true; if (steal) { steal_value(source, dest); } else { copy_value(source, dest); } } void copy_value(Term* source, Term* dest) { // Temp: Do a type specialization if dest has type 'any'. // This should be removed once type inference rules are smarter. if (dest->type == ANY_TYPE) specialize_type(dest, source->type); assert_type(source, dest->type); if (dest->value == NULL) alloc_value(dest); Type::CopyFunc copy = as_type(source->type).copy; if (copy == NULL) throw std::runtime_error(std::string("type ") + as_type(source->type).name + " has no copy function"); copy(source, dest); } void copy_value_but_dont_copy_inner_branch(Term* source, Term* dest) { // Special case: functions. Need to copy a bunch of data, but not the // subroutineBranch. assert_type(source, dest->type); if (source->type == FUNCTION_TYPE) { Function::copyExceptBranch(source,dest); return; } if (has_inner_branch(dest)) return; copy_value(source, dest); } void steal_value(Term* source, Term* dest) { assert_type(source, dest->type); // if 'dest' has a value, delete it dealloc_value(dest); dest->value = source->value; source->value = NULL; source->needsUpdate = true; update_owner(dest); } void update_owner(Term* term) { if (term->value == NULL) return; Type &type = as_type(term->type); if (type.updateOwner == NULL) return; type.updateOwner(term); } bool values_equal(Term* a, Term* b) { if (a->type != b->type) return false; return as_type(a->type).equals(a,b); } Term* create_value(Branch* branch, Term* type, std::string const& name) { assert(type != NULL); if (branch == NULL) assert(name == ""); assert(is_type(type)); Term *var_function = get_value_function(type); Term *term = create_term(branch, var_function, RefList()); alloc_value(term); term->stealingOk = false; //term->syntaxHints.declarationStyle = TermSyntaxHints::LITERAL_VALUE; if (name != "") branch->bindName(term, name); return term; } Term* create_value(Branch* branch, std::string const& typeName, std::string const& name) { Term *type = NULL; type = find_named(branch, typeName); if (type == NULL) throw std::runtime_error(std::string("Couldn't find type: ")+typeName); return create_value(branch, type, name); } Term* import_value(Branch& branch, Term* type, void* initialValue, std::string const& name) { assert(type != NULL); Term *var_function = get_value_function(type); Term *term = create_term(&branch, var_function, RefList()); term->value = initialValue; term->ownsValue = false; term->stealingOk = false; if (name != "") branch.bindName(term, name); return term; } Term* import_value(Branch& branch, std::string const& typeName, void* initialValue, std::string const& name) { Term* type = find_named(&branch, typeName); if (type == NULL) throw std::runtime_error("Couldn't find type: "+typeName); return import_value(branch, type, initialValue, name); } Term* string_value(Branch& branch, std::string const& s, std::string const& name) { Term* term = create_value(&branch, STRING_TYPE); as_string(term) = s; if (name != "") branch.bindName(term, name); return term; } Term* int_value(Branch& branch, int i, std::string const& name) { Term* term = create_value(&branch, INT_TYPE); as_int(term) = i; if (name != "") branch.bindName(term, name); return term; } Term* float_value(Branch& branch, float f, std::string const& name) { Term* term = create_value(&branch, FLOAT_TYPE); as_float(term) = f; if (name != "") branch.bindName(term, name); return term; } Term* bool_value(Branch& branch, bool b, std::string const& name) { Term* term = create_value(&branch, BOOL_TYPE); as_bool(term) = b; if (name != "") branch.bindName(term, name); return term; } Term* create_alias(Branch& branch, Term* term) { return eval_function(branch, ALIAS_FUNC, RefList(term)); } } // namespace circa <commit_msg>Fix problem where copy_value_but_dont_copy_inner_branch didn't do type specialization<commit_after>// Copyright 2008 Paul Hodge #include "common_headers.h" #include "circa.h" #include "values.h" namespace circa { void alloc_value(Term* term) { term->value = alloc_from_type(term->type); update_owner(term); } void dealloc_value(Term* term) { if (term->value == NULL) return; if (term->type == NULL) return; if (term->type->value == NULL) throw std::runtime_error("type is undefined"); if (term->ownsValue) { if (as_type(term->type).dealloc == NULL) throw std::runtime_error("type " + as_type(term->type).name + " has no dealloc function"); as_type(term->type).dealloc(term->value); } term->value = NULL; } void recycle_value(Term* source, Term* dest) { assert_type(source, dest->type); // Usually don't steal. Later, as an optimization, we will sometimes steal. bool steal = false; // Steal if this type has no copy function if (as_type(source->type).copy == NULL) steal = true; if (steal) { steal_value(source, dest); } else { copy_value(source, dest); } } void copy_value(Term* source, Term* dest) { // Temp: Do a type specialization if dest has type 'any'. // This should be removed once type inference rules are smarter. if (dest->type == ANY_TYPE) specialize_type(dest, source->type); assert_type(source, dest->type); if (dest->value == NULL) alloc_value(dest); Type::CopyFunc copy = as_type(source->type).copy; if (copy == NULL) throw std::runtime_error(std::string("type ") + as_type(source->type).name + " has no copy function"); copy(source, dest); } void copy_value_but_dont_copy_inner_branch(Term* source, Term* dest) { // Temp: Do a type specialization if dest has type 'any'. // This should be removed once type inference rules are smarter. if (dest->type == ANY_TYPE) specialize_type(dest, source->type); assert_type(source, dest->type); // Special case for functions if (source->type == FUNCTION_TYPE) { Function::copyExceptBranch(source,dest); return; } // Otherwise, do nothing for types with branches if (has_inner_branch(dest)) return; copy_value(source, dest); } void steal_value(Term* source, Term* dest) { assert_type(source, dest->type); // if 'dest' has a value, delete it dealloc_value(dest); dest->value = source->value; source->value = NULL; source->needsUpdate = true; update_owner(dest); } void update_owner(Term* term) { if (term->value == NULL) return; Type &type = as_type(term->type); if (type.updateOwner == NULL) return; type.updateOwner(term); } bool values_equal(Term* a, Term* b) { if (a->type != b->type) return false; return as_type(a->type).equals(a,b); } Term* create_value(Branch* branch, Term* type, std::string const& name) { assert(type != NULL); if (branch == NULL) assert(name == ""); assert(is_type(type)); Term *var_function = get_value_function(type); Term *term = create_term(branch, var_function, RefList()); alloc_value(term); term->stealingOk = false; //term->syntaxHints.declarationStyle = TermSyntaxHints::LITERAL_VALUE; if (name != "") branch->bindName(term, name); return term; } Term* create_value(Branch* branch, std::string const& typeName, std::string const& name) { Term *type = NULL; type = find_named(branch, typeName); if (type == NULL) throw std::runtime_error(std::string("Couldn't find type: ")+typeName); return create_value(branch, type, name); } Term* import_value(Branch& branch, Term* type, void* initialValue, std::string const& name) { assert(type != NULL); Term *var_function = get_value_function(type); Term *term = create_term(&branch, var_function, RefList()); term->value = initialValue; term->ownsValue = false; term->stealingOk = false; if (name != "") branch.bindName(term, name); return term; } Term* import_value(Branch& branch, std::string const& typeName, void* initialValue, std::string const& name) { Term* type = find_named(&branch, typeName); if (type == NULL) throw std::runtime_error("Couldn't find type: "+typeName); return import_value(branch, type, initialValue, name); } Term* string_value(Branch& branch, std::string const& s, std::string const& name) { Term* term = create_value(&branch, STRING_TYPE); as_string(term) = s; if (name != "") branch.bindName(term, name); return term; } Term* int_value(Branch& branch, int i, std::string const& name) { Term* term = create_value(&branch, INT_TYPE); as_int(term) = i; if (name != "") branch.bindName(term, name); return term; } Term* float_value(Branch& branch, float f, std::string const& name) { Term* term = create_value(&branch, FLOAT_TYPE); as_float(term) = f; if (name != "") branch.bindName(term, name); return term; } Term* bool_value(Branch& branch, bool b, std::string const& name) { Term* term = create_value(&branch, BOOL_TYPE); as_bool(term) = b; if (name != "") branch.bindName(term, name); return term; } Term* create_alias(Branch& branch, Term* term) { return eval_function(branch, ALIAS_FUNC, RefList(term)); } } // namespace circa <|endoftext|>
<commit_before>#pragma once #include <cmath> #include <iostream> namespace sim { struct Vector { double x, y, z; double norm_sq() { return x*x + y*y + z*z; } double norm() { return std::sqrt( norm_sq() ); } Vector operator+( const Vector& rhs ) { return Vector { .x = x + rhs.x, .y = y + rhs.y, .z = z + rhs.z }; } Vector operator-( const Vector& rhs ) { return Vector { .x = x - rhs.x, .y = y - rhs.y, .z = z - rhs.z }; } Vector operator/( const double rhs ) { return Vector { .x = x / rhs, .y = y / rhs, .z = z / rhs }; } Vector& operator+=( const Vector& rhs ) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } Vector& operator=( const Vector& rhs ) { x = rhs.x; y = rhs.y; z = rhs.z; return *this; } }; inline Vector operator*( double lhs, const Vector& rhs ) { return Vector { lhs * rhs.x, lhs * rhs.y, lhs * rhs.z }; } inline Vector operator*( const Vector& lhs, double rhs ) { return Vector { rhs * lhs.x, rhs * lhs.y, rhs * lhs.z }; } inline std::ostream& operator<<( std::ostream &os, const Vector& v ) { os << v.x << ", " << v.y << ", " << v.z; return os; } struct LatLon { float lat, lon; //LatLon( float _lat, float _lon ) { lat = _lat; lon = _lon; } }; inline std::ostream& operator<<( std::ostream &os, const LatLon& ll ) { os << ll.lat << ", " << ll.lon; return os; } } // namespace sim<commit_msg>math: added dot and cross products<commit_after>#pragma once #include <cmath> #include <iostream> namespace sim { struct Vector { double x, y, z; Vector() {} Vector( double x, double y, double z ) : x(x), y(y), z(z) {} double norm_sq() { return x*x + y*y + z*z; } double norm() { return std::sqrt( norm_sq() ); } Vector operator+( const Vector& rhs ) { return Vector( x + rhs.x, y + rhs.y, z + rhs.z ); } Vector operator-( const Vector& rhs ) { return Vector( x - rhs.x, y - rhs.y, z - rhs.z ); } Vector operator/( const double rhs ) { return Vector( x / rhs, y / rhs, z / rhs ); } Vector& operator+=( const Vector& rhs ) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } Vector& operator=( const Vector& rhs ) { x = rhs.x; y = rhs.y; z = rhs.z; return *this; } }; inline double dot( const Vector& u, const Vector& v ) { return u.x * v.x + u.y * v.y + u.z * v.z; } inline Vector operator*( const Vector& u, const Vector& v ) { return Vector( u.y * v.z - u.z * v.y, u.z * v.x - u.x * v.z, u.x * v.y - u.y * v.x ); } inline Vector cross( const Vector& u, const Vector& v ) { return u * v; } inline Vector operator*( double lhs, const Vector& rhs ) { return Vector { lhs * rhs.x, lhs * rhs.y, lhs * rhs.z }; } inline Vector operator*( const Vector& lhs, double rhs ) { return Vector { rhs * lhs.x, rhs * lhs.y, rhs * lhs.z }; } inline std::ostream& operator<<( std::ostream &os, const Vector& v ) { os << v.x << ", " << v.y << ", " << v.z; return os; } struct LatLon { float lat, lon; //LatLon( float _lat, float _lon ) { lat = _lat; lon = _lon; } }; inline std::ostream& operator<<( std::ostream &os, const LatLon& ll ) { os << ll.lat << ", " << ll.lon; return os; } } // namespace sim<|endoftext|>
<commit_before>#include "wgf.h" #include <math.h> #include <sys/time.h> #include <memory> double time_stamp() { struct timeval t; if(gettimeofday(&t, 0) != 0) exit(-1); return t.tv_sec + t.tv_usec/1e6; } WorkGroupFunc::WorkGroupFunc(int N) { runtime = clRuntime::getInstance(); file = clFile::getInstance(); platform = runtime->getPlatformID(); device = runtime->getDevice(); context = runtime->getContext(); cmdQueue = runtime->getCmdQueue(0); numElems = N; numElemsBytes = numElems * sizeof(int); InitKernel(); InitBuffer(); } WorkGroupFunc::~WorkGroupFunc() { FreeBuffer(); FreeKernel(); } void WorkGroupFunc::InitKernel() { cl_int err; // Open kernel file file->open("wgf_Kernels.cl"); // Create program const char *source = file->getSourceChar(); program = clCreateProgramWithSource(context, 1, (const char **)&source, NULL, &err); checkOpenCLErrors(err, "Failed to create Program with source\n"); // Create program with OpenCL 2.0 support err = clBuildProgram(program, 0, NULL, "-cl-std=CL2.0", NULL, NULL); if (err != CL_SUCCESS) { // Debug char buf[0x10000]; clGetProgramBuildInfo( program, device, CL_PROGRAM_BUILD_LOG, 0x10000, buf, NULL); printf("%s\n", buf); exit(-1); } // Create kernel kernel_wgf_reduce = clCreateKernel(program, "wgf_reduce", &err); checkOpenCLErrors(err, "Failed to clCreateKernel wgf_reduce"); kernel_wgf_reduce_atomic = clCreateKernel(program, "wgf_reduce_atomic", &err); checkOpenCLErrors(err, "Failed to clCreateKernel wgf_reduce_atomic"); } void WorkGroupFunc::InitBuffer() { cl_int err; src_0 = (int *)clSVMAlloc(context, CL_MEM_READ_ONLY, numElemsBytes, 0); dst_0 = (int *)clSVMAlloc(context, CL_MEM_WRITE_ONLY, numElemsBytes, 0); src_1 = (int *)clSVMAlloc(context, CL_MEM_READ_ONLY, numElemsBytes, 0); dst_1 = (int *)clSVMAlloc(context, CL_MEM_WRITE_ONLY, numElemsBytes, 0); int zero = 0; int one = 1; err = clEnqueueSVMMemFill(cmdQueue, src_0, (const void *)&one, sizeof(int), numElemsBytes, 0, NULL, NULL); err |= clEnqueueSVMMemFill(cmdQueue, dst_0, (const void *)&zero, sizeof(int), numElemsBytes, 0, NULL, NULL); err |= clEnqueueSVMMemFill(cmdQueue, src_1, (const void *)&one, sizeof(int), numElemsBytes, 0, NULL, NULL); err |= clEnqueueSVMMemFill(cmdQueue, dst_1, (const void *)&zero, sizeof(int), numElemsBytes, 0, NULL, NULL); checkOpenCLErrors(err, "Failed to clEnqueueSVMMemFill src_0"); } void WorkGroupFunc::FreeKernel() { cl_int err; err = clReleaseKernel(kernel_wgf_reduce); checkOpenCLErrors(err, "Failed to release kernel_wgf_reduce"); err = clReleaseKernel(kernel_wgf_reduce_atomic); checkOpenCLErrors(err, "Failed to release kernel_wgf_reduce"); err = clReleaseProgram(program); checkOpenCLErrors(err, "Failed to release program"); } void WorkGroupFunc::FreeBuffer() { clSVMFreeSafe(context, src_0); clSVMFreeSafe(context, dst_0); clSVMFreeSafe(context, src_1); clSVMFreeSafe(context, dst_1); } void WorkGroupFunc::Run2Pass() { cl_int err; size_t globalSize_0 = std::min(int(ceil(numElems/256) * 256), 1024); size_t localSize_0 = 256; size_t globalSize_1 = 256; size_t localSize_1 = 256; int N = numElems; err = clSetKernelArg(kernel_wgf_reduce, 0, sizeof(int), (void *)&N); err |= clSetKernelArgSVMPointer(kernel_wgf_reduce, 1, src_0); err |= clSetKernelArgSVMPointer(kernel_wgf_reduce, 2, dst_0); checkOpenCLErrors(err, "Failed to set args in kernel_wgf_reduce"); double start_0 = time_stamp(); err = clEnqueueNDRangeKernel( cmdQueue, kernel_wgf_reduce, 1, 0, &globalSize_0, &localSize_0, 0, 0, 0 ); double end_0 = time_stamp(); checkOpenCLErrors(err, "Failed at clEnqueueNDRangeKernel"); printf("Pass 0 takes %f\n", end_0 - start_0); int numWG = globalSize_0 / localSize_0; err = clSetKernelArg(kernel_wgf_reduce, 0, sizeof(int), (void *)&numWG); err |= clSetKernelArgSVMPointer(kernel_wgf_reduce, 1, dst_0); err |= clSetKernelArgSVMPointer(kernel_wgf_reduce, 2, dst_0); checkOpenCLErrors(err, "Failed to set args in kernel_wgf_reduce"); double start_1 = time_stamp(); err = clEnqueueNDRangeKernel( cmdQueue, kernel_wgf_reduce, 1, 0, &globalSize_1, &localSize_1, 0, 0, 0 ); double end_1 = time_stamp(); checkOpenCLErrors(err, "Failed at clEnqueueNDRangeKernel"); printf("Pass 1 takes %f\n", end_1 - start_1); printf("Run2Pass takes %f\n", end_0 - start_0 + end_1 - start_1); // Reduction result Dump(dst_0, 1); } void WorkGroupFunc::RunAtomic() { cl_int err; size_t globalSize_0 = std::min(int(ceil(numElems/256) * 256), 1024); size_t localSize_0 = 256; int N = numElems; err = clSetKernelArg(kernel_wgf_reduce_atomic, 0, sizeof(int), (void *)&N); err |= clSetKernelArgSVMPointer(kernel_wgf_reduce_atomic, 1, src_0); err |= clSetKernelArgSVMPointer(kernel_wgf_reduce_atomic, 2, dst_0); checkOpenCLErrors(err, "Failed to set args in kernel_wgf_reduce"); double start_0 = time_stamp(); err = clEnqueueNDRangeKernel( cmdQueue, kernel_wgf_reduce_atomic, 1, 0, &globalSize_0, &localSize_0, 0, 0, 0 ); double end_0 = time_stamp(); checkOpenCLErrors(err, "Failed at clEnqueueNDRangeKernel"); printf("RunAtomic takes %f\n", end_0 - start_0); // Reduction result Dump(dst_1, 1); } void WorkGroupFunc::Dump(int *svm_ptr, int N) { cl_int err; clEnqueueSVMMap(cmdQueue, CL_TRUE, CL_MAP_READ, svm_ptr, sizeof(int) * N, 0, NULL, NULL); for (int i = 0; i < N; ++i) std::cout << dst_0[i] << std::endl; } int main(int argc, char const *argv[]) { if (argc != 2) { printf("wgf #elements\n"); exit(-1); } std::unique_ptr<WorkGroupFunc> wgf(new WorkGroupFunc(atoi(argv[1]))); wgf->Run2Pass(); wgf->RunAtomic(); return 0; } <commit_msg>Update<commit_after>#include "wgf.h" #include <math.h> #include <sys/time.h> #include <memory> double time_stamp() { struct timeval t; if(gettimeofday(&t, 0) != 0) exit(-1); return t.tv_sec + t.tv_usec/1e6; } WorkGroupFunc::WorkGroupFunc(int N) { runtime = clRuntime::getInstance(); file = clFile::getInstance(); platform = runtime->getPlatformID(); device = runtime->getDevice(); context = runtime->getContext(); cmdQueue = runtime->getCmdQueue(0); numElems = N; numElemsBytes = numElems * sizeof(int); InitKernel(); InitBuffer(); } WorkGroupFunc::~WorkGroupFunc() { FreeBuffer(); FreeKernel(); } void WorkGroupFunc::InitKernel() { cl_int err; // Open kernel file file->open("wgf_Kernels.cl"); // Create program const char *source = file->getSourceChar(); program = clCreateProgramWithSource(context, 1, (const char **)&source, NULL, &err); checkOpenCLErrors(err, "Failed to create Program with source\n"); // Create program with OpenCL 2.0 support err = clBuildProgram(program, 0, NULL, "-cl-std=CL2.0", NULL, NULL); if (err != CL_SUCCESS) { // Debug char buf[0x10000]; clGetProgramBuildInfo( program, device, CL_PROGRAM_BUILD_LOG, 0x10000, buf, NULL); printf("%s\n", buf); exit(-1); } // Create kernel kernel_wgf_reduce = clCreateKernel(program, "wgf_reduce", &err); checkOpenCLErrors(err, "Failed to clCreateKernel wgf_reduce"); kernel_wgf_reduce_atomic = clCreateKernel(program, "wgf_reduce_atomic", &err); checkOpenCLErrors(err, "Failed to clCreateKernel wgf_reduce_atomic"); } void WorkGroupFunc::InitBuffer() { cl_int err; src_0 = (int *)clSVMAlloc(context, CL_MEM_READ_ONLY, numElemsBytes, 0); dst_0 = (int *)clSVMAlloc(context, CL_MEM_WRITE_ONLY, numElemsBytes, 0); src_1 = (int *)clSVMAlloc(context, CL_MEM_READ_ONLY, numElemsBytes, 0); dst_1 = (int *)clSVMAlloc(context, CL_MEM_WRITE_ONLY, numElemsBytes, 0); int zero = 0; int one = 1; err = clEnqueueSVMMemFill(cmdQueue, src_0, (const void *)&one, sizeof(int), numElemsBytes, 0, NULL, NULL); err |= clEnqueueSVMMemFill(cmdQueue, dst_0, (const void *)&zero, sizeof(int), numElemsBytes, 0, NULL, NULL); err |= clEnqueueSVMMemFill(cmdQueue, src_1, (const void *)&one, sizeof(int), numElemsBytes, 0, NULL, NULL); err |= clEnqueueSVMMemFill(cmdQueue, dst_1, (const void *)&zero, sizeof(int), numElemsBytes, 0, NULL, NULL); checkOpenCLErrors(err, "Failed to clEnqueueSVMMemFill src_0"); } void WorkGroupFunc::FreeKernel() { cl_int err; err = clReleaseKernel(kernel_wgf_reduce); checkOpenCLErrors(err, "Failed to release kernel_wgf_reduce"); err = clReleaseKernel(kernel_wgf_reduce_atomic); checkOpenCLErrors(err, "Failed to release kernel_wgf_reduce"); err = clReleaseProgram(program); checkOpenCLErrors(err, "Failed to release program"); } void WorkGroupFunc::FreeBuffer() { clSVMFreeSafe(context, src_0); clSVMFreeSafe(context, dst_0); clSVMFreeSafe(context, src_1); clSVMFreeSafe(context, dst_1); } void WorkGroupFunc::Run2Pass() { cl_int err; size_t globalSize_0 = std::min(int(ceil(numElems/256) * 256), 1024); size_t localSize_0 = 256; size_t globalSize_1 = 256; size_t localSize_1 = 256; int N = numElems; err = clSetKernelArg(kernel_wgf_reduce, 0, sizeof(int), (void *)&N); err |= clSetKernelArgSVMPointer(kernel_wgf_reduce, 1, src_0); err |= clSetKernelArgSVMPointer(kernel_wgf_reduce, 2, dst_0); checkOpenCLErrors(err, "Failed to set args in kernel_wgf_reduce"); double start_0 = time_stamp(); err = clEnqueueNDRangeKernel( cmdQueue, kernel_wgf_reduce, 1, 0, &globalSize_0, &localSize_0, 0, 0, 0 ); double end_0 = time_stamp(); checkOpenCLErrors(err, "Failed at clEnqueueNDRangeKernel"); printf("Pass 0 takes %f\n", end_0 - start_0); int numWG = globalSize_0 / localSize_0; err = clSetKernelArg(kernel_wgf_reduce, 0, sizeof(int), (void *)&numWG); err |= clSetKernelArgSVMPointer(kernel_wgf_reduce, 1, dst_0); err |= clSetKernelArgSVMPointer(kernel_wgf_reduce, 2, dst_0); checkOpenCLErrors(err, "Failed to set args in kernel_wgf_reduce"); double start_1 = time_stamp(); err = clEnqueueNDRangeKernel( cmdQueue, kernel_wgf_reduce, 1, 0, &globalSize_1, &localSize_1, 0, 0, 0 ); double end_1 = time_stamp(); checkOpenCLErrors(err, "Failed at clEnqueueNDRangeKernel"); printf("Pass 1 takes %f\n", end_1 - start_1); printf("Run2Pass takes %f\n", end_0 - start_0 + end_1 - start_1); // Reduction result Dump(dst_0, 1); } void WorkGroupFunc::RunAtomic() { cl_int err; size_t globalSize_0 = std::min(int(ceil(numElems/256) * 256), 1024); size_t localSize_0 = 256; int N = numElems; err = clSetKernelArg(kernel_wgf_reduce_atomic, 0, sizeof(int), (void *)&N); err |= clSetKernelArgSVMPointer(kernel_wgf_reduce_atomic, 1, src_1); err |= clSetKernelArgSVMPointer(kernel_wgf_reduce_atomic, 2, dst_1); checkOpenCLErrors(err, "Failed to set args in kernel_wgf_reduce"); double start_0 = time_stamp(); err = clEnqueueNDRangeKernel( cmdQueue, kernel_wgf_reduce_atomic, 1, 0, &globalSize_0, &localSize_0, 0, 0, 0 ); double end_0 = time_stamp(); checkOpenCLErrors(err, "Failed at clEnqueueNDRangeKernel"); printf("RunAtomic takes %f\n", end_0 - start_0); // Reduction result Dump(dst_1, 1); } void WorkGroupFunc::Dump(int *svm_ptr, int N) { cl_int err; clEnqueueSVMMap(cmdQueue, CL_TRUE, CL_MAP_READ, svm_ptr, sizeof(int) * N, 0, NULL, NULL); for (int i = 0; i < N; ++i) std::cout << dst_0[i] << std::endl; } int main(int argc, char const *argv[]) { if (argc != 2) { printf("wgf #elements\n"); exit(-1); } std::unique_ptr<WorkGroupFunc> wgf(new WorkGroupFunc(atoi(argv[1]))); wgf->Run2Pass(); wgf->RunAtomic(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2013, Hernan Saez * 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 <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CRIMILD_SCENEGRAPH_CAMERA_ #define CRIMILD_SCENEGRAPH_CAMERA_ #include "Group.hpp" #include "Mathematics/Matrix.hpp" #include "Mathematics/Frustum.hpp" #include "Mathematics/Ray.hpp" #include "Mathematics/Rect.hpp" #include <memory> namespace crimild { namespace rendergraph { class RenderGraph; } class Camera : public Group { public: static Camera *getMainCamera( void ) { return _mainCamera; } /** \remarks Internal use only */ static void setMainCamera( Camera *camera ) { _mainCamera = camera; } /** remarks Internal use only */ static void setMainCamera( SharedPointer< Camera > const &camera ) { _mainCamera = crimild::get_ptr( camera ); } private: static Camera *_mainCamera; public: explicit Camera( void ); Camera( float fov, float aspect, float near, float far ); virtual ~Camera( void ); bool isMainCamera( void ) const { return _isMainCamera; } void setIsMainCamera( bool value ) { _isMainCamera = value; } private: bool _isMainCamera = false; public: void setFrustum( const Frustumf &f ); const Frustumf &getFrustum( void ) const { return _frustum; } void setProjectionMatrix( const Matrix4f &projection ) { _projectionMatrix = projection; } const Matrix4f &getProjectionMatrix( void ) const { return _projectionMatrix; } void setOrthographicMatrix( const Matrix4f &orthographic ) { _orthographicMatrix = orthographic; } const Matrix4f &getOrthographicMatrix( void ) const { return _orthographicMatrix; } void setViewMatrix( const Matrix4f &view ); const Matrix4f &getViewMatrix( void ); void setViewMatrixIsCurrent( bool value ) { _viewMatrixIsCurrent = value; } bool viewMatrixIsCurrent( void ) const { return _viewMatrixIsCurrent; } void setViewport( const Rectf &rect ) { _viewport = rect; } const Rectf &getViewport( void ) const { return _viewport; } virtual bool getPickRay( float normalizedX, float normalizedY, Ray3f &result ) const; void setAspectRatio( float aspect ); float computeAspect( void ) const; private: Frustumf _frustum; Rectf _viewport; Matrix4f _projectionMatrix; Matrix4f _orthographicMatrix; Matrix4f _viewMatrix; bool _viewMatrixIsCurrent; public: virtual void accept( NodeVisitor &visitor ) override; /** \name Render graph */ //@{ public: void setRenderGraph( SharedPointer< rendergraph::RenderGraph > const &rg ) { _renderGraph = rg; } rendergraph::RenderGraph *getRenderGraph( void ) { return crimild::get_ptr( _renderGraph ); } private: SharedPointer< rendergraph::RenderGraph > _renderGraph; //@} public: void computeCullingPlanes( void ); void setCullingEnabled( bool value ) { _cullingEnabled = value; } bool isCullingEnabled( void ) const { return _cullingEnabled; } bool culled( const BoundingVolume *volume ) const; private: bool _cullingEnabled = true; Plane3f _cullingPlanes[ 6 ]; }; } #endif <commit_msg>Fix RTTI for Camera<commit_after>/* * Copyright (c) 2013, Hernan Saez * 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 <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CRIMILD_SCENEGRAPH_CAMERA_ #define CRIMILD_SCENEGRAPH_CAMERA_ #include "Group.hpp" #include "Mathematics/Frustum.hpp" #include "Mathematics/Matrix.hpp" #include "Mathematics/Ray.hpp" #include "Mathematics/Rect.hpp" #include <memory> namespace crimild { namespace rendergraph { class RenderGraph; } class Camera : public Group { CRIMILD_IMPLEMENT_RTTI( crimild::Camera ) public: static Camera *getMainCamera( void ) { return _mainCamera; } /** \remarks Internal use only */ static void setMainCamera( Camera *camera ) { _mainCamera = camera; } /** remarks Internal use only */ static void setMainCamera( SharedPointer< Camera > const &camera ) { _mainCamera = crimild::get_ptr( camera ); } private: static Camera *_mainCamera; public: explicit Camera( void ); Camera( float fov, float aspect, float near, float far ); virtual ~Camera( void ); bool isMainCamera( void ) const { return _isMainCamera; } void setIsMainCamera( bool value ) { _isMainCamera = value; } private: bool _isMainCamera = false; public: void setFrustum( const Frustumf &f ); const Frustumf &getFrustum( void ) const { return _frustum; } void setProjectionMatrix( const Matrix4f &projection ) { _projectionMatrix = projection; } const Matrix4f &getProjectionMatrix( void ) const { return _projectionMatrix; } void setOrthographicMatrix( const Matrix4f &orthographic ) { _orthographicMatrix = orthographic; } const Matrix4f &getOrthographicMatrix( void ) const { return _orthographicMatrix; } void setViewMatrix( const Matrix4f &view ); const Matrix4f &getViewMatrix( void ); void setViewMatrixIsCurrent( bool value ) { _viewMatrixIsCurrent = value; } bool viewMatrixIsCurrent( void ) const { return _viewMatrixIsCurrent; } void setViewport( const Rectf &rect ) { _viewport = rect; } const Rectf &getViewport( void ) const { return _viewport; } virtual bool getPickRay( float normalizedX, float normalizedY, Ray3f &result ) const; void setAspectRatio( float aspect ); float computeAspect( void ) const; private: Frustumf _frustum; Rectf _viewport; Matrix4f _projectionMatrix; Matrix4f _orthographicMatrix; Matrix4f _viewMatrix; bool _viewMatrixIsCurrent; public: virtual void accept( NodeVisitor &visitor ) override; /** \name Render graph */ //@{ public: void setRenderGraph( SharedPointer< rendergraph::RenderGraph > const &rg ) { _renderGraph = rg; } rendergraph::RenderGraph *getRenderGraph( void ) { return crimild::get_ptr( _renderGraph ); } private: SharedPointer< rendergraph::RenderGraph > _renderGraph; //@} public: void computeCullingPlanes( void ); void setCullingEnabled( bool value ) { _cullingEnabled = value; } bool isCullingEnabled( void ) const { return _cullingEnabled; } bool culled( const BoundingVolume *volume ) const; private: bool _cullingEnabled = true; Plane3f _cullingPlanes[ 6 ]; }; } #endif <|endoftext|>
<commit_before>#include <iostream> #include <string> #include "help.h" #include <libproc.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #define KwmDaemonPort 3020 int KwmcSockFD; void Fatal(const std::string &err) { std::cout << err << std::endl; exit(1); } std::string ReadFromSocket(int SockFD) { std::string Message; char Cur; while(recv(SockFD, &Cur, 1, 0)) Message += Cur; return Message; } void KwmcForwardMessageThroughSocket(int argc, char **argv) { std::string Msg; for(int i = 1; i < argc; ++i) { Msg += argv[i]; if(i < argc - 1) Msg += " "; } Msg += "\n"; send(KwmcSockFD, Msg.c_str(), Msg.size(), 0); std::string Response = ReadFromSocket(KwmcSockFD); if(!Response.empty()) std::cout << Response << std::endl; } void KwmcConnectToDaemon() { struct sockaddr_in srv_addr; struct hostent *server; if((KwmcSockFD = socket(PF_INET, SOCK_STREAM, 0)) == -1) Fatal("Could not create socket!"); server = gethostbyname("localhost"); srv_addr.sin_family = AF_INET; srv_addr.sin_port = htons(KwmDaemonPort); std::memcpy(&srv_addr.sin_addr.s_addr, server->h_addr, server->h_length); std::memset(&srv_addr.sin_zero, '\0', 8); if(connect(KwmcSockFD, (struct sockaddr*) &srv_addr, sizeof(struct sockaddr)) == -1) Fatal("Connection failed!"); } int main(int argc, char **argv) { if(argc >= 2) { std::string Command = argv[1]; if(Command == "help" && argc >= 3) { ShowHelp(argv[2]); } else if (Command == "help") { ShowUsage(); } else { KwmcConnectToDaemon(); KwmcForwardMessageThroughSocket(argc, argv); close(KwmcSockFD); } } else { ShowUsage(); } return 0; } <commit_msg>kwmc interpreter mode for remote control through ssh<commit_after>#include <iostream> #include <string> #include "help.h" #include <libproc.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #define KwmDaemonPort 3020 int KwmcSockFD; void Fatal(const std::string &err) { std::cout << err << std::endl; exit(1); } std::string ReadFromSocket(int SockFD) { std::string Message; char Cur; while(recv(SockFD, &Cur, 1, 0)) Message += Cur; return Message; } void WriteToSocket(std::string Msg) { send(KwmcSockFD, Msg.c_str(), Msg.size(), 0); std::string Response = ReadFromSocket(KwmcSockFD); if(!Response.empty()) std::cout << Response << std::endl; shutdown(KwmcSockFD); close(KwmcSockFD); } void KwmcForwardMessageThroughSocket(int argc, char **argv) { std::string Msg; for(int i = 1; i < argc; ++i) { Msg += argv[i]; if(i < argc - 1) Msg += " "; } Msg += "\n"; WriteToSocket(Msg); } void KwmcConnectToDaemon() { struct sockaddr_in srv_addr; struct hostent *server; if((KwmcSockFD = socket(PF_INET, SOCK_STREAM, 0)) == -1) Fatal("Could not create socket!"); server = gethostbyname("localhost"); srv_addr.sin_family = AF_INET; srv_addr.sin_port = htons(KwmDaemonPort); std::memcpy(&srv_addr.sin_addr.s_addr, server->h_addr, server->h_length); std::memset(&srv_addr.sin_zero, '\0', 8); if(connect(KwmcSockFD, (struct sockaddr*) &srv_addr, sizeof(struct sockaddr)) == -1) Fatal("Connection failed!"); } void KwmcInterpreter() { while(true) { std::string Msg; std::getline(std::cin, Msg); if(Msg == "/quit" || Msg == "/q") break; KwmcConnectToDaemon(); WriteToSocket(Msg); } } int main(int argc, char **argv) { if(argc <= 1) ShowUsage(); else if(argc >= 2) { std::string Command = argv[1]; if(Command == "interpret") KwmcInterpreter(); else if(Command == "help" && argc >= 3) ShowHelp(argv[2]); else if(Command == "help") ShowUsage(); else { KwmcConnectToDaemon(); KwmcForwardMessageThroughSocket(argc, argv); } } return 0; } <|endoftext|>
<commit_before>// Copyright 2016 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include <gtest/gtest.h> #include "packager/media/filters/ec3_audio_util.h" namespace edash_packager { namespace media { TEST(EC3AudioUtilTest, CalculateEC3ChannelMapTest1) { // audio_coding_mode is 7, which is Left, Center, Right, Left surround, Right // surround. No dependent substreams. LFE channel on. const std::vector<uint8_t> ec3_data = {0, 0, 0, 0x0f, 0}; uint32_t channel_map; EXPECT_TRUE(CalculateEC3ChannelMap(ec3_data, &channel_map)); EXPECT_EQ(0xF801u, channel_map); } TEST(EC3AudioUtilTest, CalculateEC3ChannelMapTest2) { // audio_coding_mode is 2, which is Left and Right. No dependent substreams. // LFE channel off. const std::vector<uint8_t> ec3_data = {0, 0, 0, 0x04, 0}; uint32_t channel_map; EXPECT_TRUE(CalculateEC3ChannelMap(ec3_data, &channel_map)); EXPECT_EQ(0xA000u, channel_map); } TEST(EC3AudioUtilTest, CalculateEC3ChannelMapTest3) { // audio_coding_mode is 3, which is Left, Center, and Right. Dependent // substreams layout is 0b100000011, which is Left center/ Right center pair, // Left rear surround/ Right rear surround pair, LFE2 on. LFE channel on. const std::vector<uint8_t> ec3_data = {0, 0, 0, 0x07, 0x07, 0x03}; uint32_t channel_map; EXPECT_TRUE(CalculateEC3ChannelMap(ec3_data, &channel_map)); EXPECT_EQ(0xE603u, channel_map); } } // namespace media } // namespace edash_packager <commit_msg>Fix unittest break in Mac due to C++11 incompatibility<commit_after>// Copyright 2016 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd #include <gtest/gtest.h> #include "packager/base/macros.h" #include "packager/media/filters/ec3_audio_util.h" namespace edash_packager { namespace media { TEST(EC3AudioUtilTest, CalculateEC3ChannelMapTest1) { // audio_coding_mode is 7, which is Left, Center, Right, Left surround, Right // surround. No dependent substreams. LFE channel on. const uint8_t kEc3Data[] = {0, 0, 0, 0x0f, 0}; uint32_t channel_map; EXPECT_TRUE(CalculateEC3ChannelMap( std::vector<uint8_t>(kEc3Data, kEc3Data + arraysize(kEc3Data)), &channel_map)); EXPECT_EQ(0xF801u, channel_map); } TEST(EC3AudioUtilTest, CalculateEC3ChannelMapTest2) { // audio_coding_mode is 2, which is Left and Right. No dependent substreams. // LFE channel off. const uint8_t kEc3Data[] = {0, 0, 0, 0x04, 0}; uint32_t channel_map; EXPECT_TRUE(CalculateEC3ChannelMap( std::vector<uint8_t>(kEc3Data, kEc3Data + arraysize(kEc3Data)), &channel_map)); EXPECT_EQ(0xA000u, channel_map); } TEST(EC3AudioUtilTest, CalculateEC3ChannelMapTest3) { // audio_coding_mode is 3, which is Left, Center, and Right. Dependent // substreams layout is 0b100000011, which is Left center/ Right center pair, // Left rear surround/ Right rear surround pair, LFE2 on. LFE channel on. const uint8_t kEc3Data[] = {0, 0, 0, 0x07, 0x07, 0x03}; uint32_t channel_map; EXPECT_TRUE(CalculateEC3ChannelMap( std::vector<uint8_t>(kEc3Data, kEc3Data + arraysize(kEc3Data)), &channel_map)); EXPECT_EQ(0xE603u, channel_map); } } // namespace media } // namespace edash_packager <|endoftext|>